[X86][SSE] An empty target shuffle mask is always a failure.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86ShuffleDecodeConstantPool.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/EHPersonalities.h"
30 #include "llvm/CodeGen/IntrinsicLowering.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/WinEHFuncInfo.h"
38 #include "llvm/IR/CallSite.h"
39 #include "llvm/IR/CallingConv.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalAlias.h"
44 #include "llvm/IR/GlobalVariable.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/Intrinsics.h"
47 #include "llvm/MC/MCAsmInfo.h"
48 #include "llvm/MC/MCContext.h"
49 #include "llvm/MC/MCExpr.h"
50 #include "llvm/MC/MCSymbol.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Target/TargetOptions.h"
56 #include "X86IntrinsicsInfo.h"
57 #include <bitset>
58 #include <numeric>
59 #include <cctype>
60 using namespace llvm;
61
62 #define DEBUG_TYPE "x86-isel"
63
64 STATISTIC(NumTailCalls, "Number of tail calls");
65
66 static cl::opt<bool> ExperimentalVectorWideningLegalization(
67     "x86-experimental-vector-widening-legalization", cl::init(false),
68     cl::desc("Enable an experimental vector type legalization through widening "
69              "rather than promotion."),
70     cl::Hidden);
71
72 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
73                                      const X86Subtarget &STI)
74     : TargetLowering(TM), Subtarget(&STI) {
75   X86ScalarSSEf64 = Subtarget->hasSSE2();
76   X86ScalarSSEf32 = Subtarget->hasSSE1();
77   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
78
79   // Set up the TargetLowering object.
80
81   // X86 is weird. It always uses i8 for shift amounts and setcc results.
82   setBooleanContents(ZeroOrOneBooleanContent);
83   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
84   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
85
86   // For 64-bit, since we have so many registers, use the ILP scheduler.
87   // For 32-bit, use the register pressure specific scheduling.
88   // For Atom, always use ILP scheduling.
89   if (Subtarget->isAtom())
90     setSchedulingPreference(Sched::ILP);
91   else if (Subtarget->is64Bit())
92     setSchedulingPreference(Sched::ILP);
93   else
94     setSchedulingPreference(Sched::RegPressure);
95   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
96   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
97
98   // Bypass expensive divides on Atom when compiling with O2.
99   if (TM.getOptLevel() >= CodeGenOpt::Default) {
100     if (Subtarget->hasSlowDivide32())
101       addBypassSlowDiv(32, 8);
102     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
103       addBypassSlowDiv(64, 16);
104   }
105
106   if (Subtarget->isTargetKnownWindowsMSVC()) {
107     // Setup Windows compiler runtime calls.
108     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
109     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
110     setLibcallName(RTLIB::SREM_I64, "_allrem");
111     setLibcallName(RTLIB::UREM_I64, "_aullrem");
112     setLibcallName(RTLIB::MUL_I64, "_allmul");
113     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
114     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
115     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
116     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
117     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
118   }
119
120   if (Subtarget->isTargetDarwin()) {
121     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
122     setUseUnderscoreSetJmp(false);
123     setUseUnderscoreLongJmp(false);
124   } else if (Subtarget->isTargetWindowsGNU()) {
125     // MS runtime is weird: it exports _setjmp, but longjmp!
126     setUseUnderscoreSetJmp(true);
127     setUseUnderscoreLongJmp(false);
128   } else {
129     setUseUnderscoreSetJmp(true);
130     setUseUnderscoreLongJmp(true);
131   }
132
133   // Set up the register classes.
134   addRegisterClass(MVT::i8, &X86::GR8RegClass);
135   addRegisterClass(MVT::i16, &X86::GR16RegClass);
136   addRegisterClass(MVT::i32, &X86::GR32RegClass);
137   if (Subtarget->is64Bit())
138     addRegisterClass(MVT::i64, &X86::GR64RegClass);
139
140   for (MVT VT : MVT::integer_valuetypes())
141     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
142
143   // We don't accept any truncstore of integer registers.
144   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
145   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
146   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
147   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
148   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
149   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
150
151   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
152
153   // SETOEQ and SETUNE require checking two conditions.
154   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
155   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
156   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
157   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
158   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
159   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
160
161   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
162   // operation.
163   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
164   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
165   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
166
167   if (Subtarget->is64Bit()) {
168     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512())
169       // f32/f64 are legal, f80 is custom.
170       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
171     else
172       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
173     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
174   } else if (!Subtarget->useSoftFloat()) {
175     // We have an algorithm for SSE2->double, and we turn this into a
176     // 64-bit FILD followed by conditional FADD for other targets.
177     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
178     // We have an algorithm for SSE2, and we turn this into a 64-bit
179     // FILD or VCVTUSI2SS/SD for other targets.
180     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
181   }
182
183   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
184   // this operation.
185   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
186   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
187
188   if (!Subtarget->useSoftFloat()) {
189     // SSE has no i16 to fp conversion, only i32
190     if (X86ScalarSSEf32) {
191       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
192       // f32 and f64 cases are Legal, f80 case is not
193       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
194     } else {
195       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
196       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
197     }
198   } else {
199     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
200     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
201   }
202
203   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
204   // this operation.
205   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
206   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
207
208   if (!Subtarget->useSoftFloat()) {
209     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
210     // are Legal, f80 is custom lowered.
211     setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
212     setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
213
214     if (X86ScalarSSEf32) {
215       setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
216       // f32 and f64 cases are Legal, f80 case is not
217       setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
218     } else {
219       setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
220       setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
221     }
222   } else {
223     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
224     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Expand);
225     setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Expand);
226   }
227
228   // Handle FP_TO_UINT by promoting the destination to a larger signed
229   // conversion.
230   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
231   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
232   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
233
234   if (Subtarget->is64Bit()) {
235     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
236       // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
237       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
238       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Custom);
239     } else {
240       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
241       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Expand);
242     }
243   } else if (!Subtarget->useSoftFloat()) {
244     // Since AVX is a superset of SSE3, only check for SSE here.
245     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
246       // Expand FP_TO_UINT into a select.
247       // FIXME: We would like to use a Custom expander here eventually to do
248       // the optimal thing for SSE vs. the default expansion in the legalizer.
249       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
250     else
251       // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
252       // With SSE3 we can use fisttpll to convert to a signed i64; without
253       // SSE, we're stuck with a fistpll.
254       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
255
256     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
257   }
258
259   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
260   if (!X86ScalarSSEf64) {
261     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
262     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
263     if (Subtarget->is64Bit()) {
264       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
265       // Without SSE, i64->f64 goes through memory.
266       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
267     }
268   }
269
270   // Scalar integer divide and remainder are lowered to use operations that
271   // produce two results, to match the available instructions. This exposes
272   // the two-result form to trivial CSE, which is able to combine x/y and x%y
273   // into a single instruction.
274   //
275   // Scalar integer multiply-high is also lowered to use two-result
276   // operations, to match the available instructions. However, plain multiply
277   // (low) operations are left as Legal, as there are single-result
278   // instructions for this in x86. Using the two-result multiply instructions
279   // when both high and low results are needed must be arranged by dagcombine.
280   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
281     setOperationAction(ISD::MULHS, VT, Expand);
282     setOperationAction(ISD::MULHU, VT, Expand);
283     setOperationAction(ISD::SDIV, VT, Expand);
284     setOperationAction(ISD::UDIV, VT, Expand);
285     setOperationAction(ISD::SREM, VT, Expand);
286     setOperationAction(ISD::UREM, VT, Expand);
287
288     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
289     setOperationAction(ISD::ADDC, VT, Custom);
290     setOperationAction(ISD::ADDE, VT, Custom);
291     setOperationAction(ISD::SUBC, VT, Custom);
292     setOperationAction(ISD::SUBE, VT, Custom);
293   }
294
295   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
296   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
297   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
298   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
299   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
300   setOperationAction(ISD::BR_CC            , MVT::f128,  Expand);
301   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
302   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
303   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
304   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
305   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
306   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
307   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::f128,  Expand);
309   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
310   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
311   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
312   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
313   if (Subtarget->is64Bit())
314     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
315   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
316   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
317   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
318   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
319
320   if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
321     // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
322     // is. We should promote the value to 64-bits to solve this.
323     // This is what the CRT headers do - `fmodf` is an inline header
324     // function casting to f64 and calling `fmod`.
325     setOperationAction(ISD::FREM           , MVT::f32  , Promote);
326   } else {
327     setOperationAction(ISD::FREM           , MVT::f32  , Expand);
328   }
329
330   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
331   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
332   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
333
334   // Promote the i8 variants and force them on up to i32 which has a shorter
335   // encoding.
336   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
337   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
338   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
339   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
340   if (Subtarget->hasBMI()) {
341     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
342     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
343     if (Subtarget->is64Bit())
344       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
345   } else {
346     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
347     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
348     if (Subtarget->is64Bit())
349       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
350   }
351
352   if (Subtarget->hasLZCNT()) {
353     // When promoting the i8 variants, force them to i32 for a shorter
354     // encoding.
355     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
356     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
357     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
358     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
359     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
360     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
361     if (Subtarget->is64Bit())
362       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
363   } else {
364     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
365     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
366     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
367     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
368     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
369     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
370     if (Subtarget->is64Bit()) {
371       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
372       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
373     }
374   }
375
376   // Special handling for half-precision floating point conversions.
377   // If we don't have F16C support, then lower half float conversions
378   // into library calls.
379   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
380     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
381     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
382   }
383
384   // There's never any support for operations beyond MVT::f32.
385   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
386   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
387   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
388   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
389
390   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
391   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
392   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
393   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
394   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
395   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
396
397   if (Subtarget->hasPOPCNT()) {
398     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
399   } else {
400     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
401     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
402     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
403     if (Subtarget->is64Bit())
404       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
405   }
406
407   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
408
409   if (!Subtarget->hasMOVBE())
410     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
411
412   // These should be promoted to a larger select which is supported.
413   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
414   // X86 wants to expand cmov itself.
415   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
416   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
417   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
418   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
419   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
420   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
421   setOperationAction(ISD::SELECT          , MVT::f128 , Custom);
422   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
423   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
424   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
425   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
426   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
427   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
428   setOperationAction(ISD::SETCC           , MVT::f128 , Custom);
429   setOperationAction(ISD::SETCCE          , MVT::i8   , Custom);
430   setOperationAction(ISD::SETCCE          , MVT::i16  , Custom);
431   setOperationAction(ISD::SETCCE          , MVT::i32  , Custom);
432   if (Subtarget->is64Bit()) {
433     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
434     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
435     setOperationAction(ISD::SETCCE        , MVT::i64  , Custom);
436   }
437   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
438   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
439   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
440   // support continuation, user-level threading, and etc.. As a result, no
441   // other SjLj exception interfaces are implemented and please don't build
442   // your own exception handling based on them.
443   // LLVM/Clang supports zero-cost DWARF exception handling.
444   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
445   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
446
447   // Darwin ABI issue.
448   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
449   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
450   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
451   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
452   if (Subtarget->is64Bit())
453     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
454   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
455   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
456   if (Subtarget->is64Bit()) {
457     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
458     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
459     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
460     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
461     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
462   }
463   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
464   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
465   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
466   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
467   if (Subtarget->is64Bit()) {
468     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
469     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
470     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
471   }
472
473   if (Subtarget->hasSSE1())
474     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
475
476   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
477
478   // Expand certain atomics
479   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
480     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
481     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
482     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
483   }
484
485   if (Subtarget->hasCmpxchg16b()) {
486     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
487   }
488
489   // FIXME - use subtarget debug flags
490   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
491       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
492     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
493   }
494
495   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
496   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
497
498   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
499   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
500
501   setOperationAction(ISD::TRAP, MVT::Other, Legal);
502   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
503
504   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
505   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
506   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
507   if (Subtarget->is64Bit()) {
508     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
509     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
510   } else {
511     // TargetInfo::CharPtrBuiltinVaList
512     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
513     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
514   }
515
516   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
517   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
518
519   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
520
521   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
522   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
523   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
524
525   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
526     // f32 and f64 use SSE.
527     // Set up the FP register classes.
528     addRegisterClass(MVT::f32, &X86::FR32RegClass);
529     addRegisterClass(MVT::f64, &X86::FR64RegClass);
530
531     // Use ANDPD to simulate FABS.
532     setOperationAction(ISD::FABS , MVT::f64, Custom);
533     setOperationAction(ISD::FABS , MVT::f32, Custom);
534
535     // Use XORP to simulate FNEG.
536     setOperationAction(ISD::FNEG , MVT::f64, Custom);
537     setOperationAction(ISD::FNEG , MVT::f32, Custom);
538
539     // Use ANDPD and ORPD to simulate FCOPYSIGN.
540     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
541     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
542
543     // Lower this to FGETSIGNx86 plus an AND.
544     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
545     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
546
547     // We don't support sin/cos/fmod
548     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
549     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
550     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
551     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
552     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
553     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
554
555     // Expand FP immediates into loads from the stack, except for the special
556     // cases we handle.
557     addLegalFPImmediate(APFloat(+0.0)); // xorpd
558     addLegalFPImmediate(APFloat(+0.0f)); // xorps
559   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
560     // Use SSE for f32, x87 for f64.
561     // Set up the FP register classes.
562     addRegisterClass(MVT::f32, &X86::FR32RegClass);
563     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
564
565     // Use ANDPS to simulate FABS.
566     setOperationAction(ISD::FABS , MVT::f32, Custom);
567
568     // Use XORP to simulate FNEG.
569     setOperationAction(ISD::FNEG , MVT::f32, Custom);
570
571     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
572
573     // Use ANDPS and ORPS to simulate FCOPYSIGN.
574     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
575     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
576
577     // We don't support sin/cos/fmod
578     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
579     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
580     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
581
582     // Special cases we handle for FP constants.
583     addLegalFPImmediate(APFloat(+0.0f)); // xorps
584     addLegalFPImmediate(APFloat(+0.0)); // FLD0
585     addLegalFPImmediate(APFloat(+1.0)); // FLD1
586     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
587     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
588
589     if (!TM.Options.UnsafeFPMath) {
590       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
591       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
592       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
593     }
594   } else if (!Subtarget->useSoftFloat()) {
595     // f32 and f64 in x87.
596     // Set up the FP register classes.
597     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
598     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
599
600     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
601     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
602     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
603     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
604
605     if (!TM.Options.UnsafeFPMath) {
606       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
607       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
608       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
609       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
610       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
611       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
612     }
613     addLegalFPImmediate(APFloat(+0.0)); // FLD0
614     addLegalFPImmediate(APFloat(+1.0)); // FLD1
615     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
616     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
617     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
618     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
619     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
620     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
621   }
622
623   // We don't support FMA.
624   setOperationAction(ISD::FMA, MVT::f64, Expand);
625   setOperationAction(ISD::FMA, MVT::f32, Expand);
626
627   // Long double always uses X87, except f128 in MMX.
628   if (!Subtarget->useSoftFloat()) {
629     if (Subtarget->is64Bit() && Subtarget->hasMMX()) {
630       addRegisterClass(MVT::f128, &X86::FR128RegClass);
631       ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
632       setOperationAction(ISD::FABS , MVT::f128, Custom);
633       setOperationAction(ISD::FNEG , MVT::f128, Custom);
634       setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
635     }
636
637     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
638     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
639     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
640     {
641       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
642       addLegalFPImmediate(TmpFlt);  // FLD0
643       TmpFlt.changeSign();
644       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
645
646       bool ignored;
647       APFloat TmpFlt2(+1.0);
648       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
649                       &ignored);
650       addLegalFPImmediate(TmpFlt2);  // FLD1
651       TmpFlt2.changeSign();
652       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
653     }
654
655     if (!TM.Options.UnsafeFPMath) {
656       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
657       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
658       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
659     }
660
661     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
662     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
663     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
664     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
665     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
666     setOperationAction(ISD::FMA, MVT::f80, Expand);
667   }
668
669   // Always use a library call for pow.
670   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
671   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
672   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
673
674   setOperationAction(ISD::FLOG, MVT::f80, Expand);
675   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
676   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
677   setOperationAction(ISD::FEXP, MVT::f80, Expand);
678   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
679   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
680   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
681
682   // First set operation action for all vector types to either promote
683   // (for widening) or expand (for scalarization). Then we will selectively
684   // turn on ones that can be effectively codegen'd.
685   for (MVT VT : MVT::vector_valuetypes()) {
686     setOperationAction(ISD::ADD , VT, Expand);
687     setOperationAction(ISD::SUB , VT, Expand);
688     setOperationAction(ISD::FADD, VT, Expand);
689     setOperationAction(ISD::FNEG, VT, Expand);
690     setOperationAction(ISD::FSUB, VT, Expand);
691     setOperationAction(ISD::MUL , VT, Expand);
692     setOperationAction(ISD::FMUL, VT, Expand);
693     setOperationAction(ISD::SDIV, VT, Expand);
694     setOperationAction(ISD::UDIV, VT, Expand);
695     setOperationAction(ISD::FDIV, VT, Expand);
696     setOperationAction(ISD::SREM, VT, Expand);
697     setOperationAction(ISD::UREM, VT, Expand);
698     setOperationAction(ISD::LOAD, VT, Expand);
699     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
700     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
701     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
702     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
703     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
704     setOperationAction(ISD::FABS, VT, Expand);
705     setOperationAction(ISD::FSIN, VT, Expand);
706     setOperationAction(ISD::FSINCOS, VT, Expand);
707     setOperationAction(ISD::FCOS, VT, Expand);
708     setOperationAction(ISD::FSINCOS, VT, Expand);
709     setOperationAction(ISD::FREM, VT, Expand);
710     setOperationAction(ISD::FMA,  VT, Expand);
711     setOperationAction(ISD::FPOWI, VT, Expand);
712     setOperationAction(ISD::FSQRT, VT, Expand);
713     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
714     setOperationAction(ISD::FFLOOR, VT, Expand);
715     setOperationAction(ISD::FCEIL, VT, Expand);
716     setOperationAction(ISD::FTRUNC, VT, Expand);
717     setOperationAction(ISD::FRINT, VT, Expand);
718     setOperationAction(ISD::FNEARBYINT, VT, Expand);
719     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
720     setOperationAction(ISD::MULHS, VT, Expand);
721     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
722     setOperationAction(ISD::MULHU, VT, Expand);
723     setOperationAction(ISD::SDIVREM, VT, Expand);
724     setOperationAction(ISD::UDIVREM, VT, Expand);
725     setOperationAction(ISD::FPOW, VT, Expand);
726     setOperationAction(ISD::CTPOP, VT, Expand);
727     setOperationAction(ISD::CTTZ, VT, Expand);
728     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
729     setOperationAction(ISD::CTLZ, VT, Expand);
730     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
731     setOperationAction(ISD::SHL, VT, Expand);
732     setOperationAction(ISD::SRA, VT, Expand);
733     setOperationAction(ISD::SRL, VT, Expand);
734     setOperationAction(ISD::ROTL, VT, Expand);
735     setOperationAction(ISD::ROTR, VT, Expand);
736     setOperationAction(ISD::BSWAP, VT, Expand);
737     setOperationAction(ISD::SETCC, VT, Expand);
738     setOperationAction(ISD::FLOG, VT, Expand);
739     setOperationAction(ISD::FLOG2, VT, Expand);
740     setOperationAction(ISD::FLOG10, VT, Expand);
741     setOperationAction(ISD::FEXP, VT, Expand);
742     setOperationAction(ISD::FEXP2, VT, Expand);
743     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
744     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
745     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
746     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
747     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
748     setOperationAction(ISD::TRUNCATE, VT, Expand);
749     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
750     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
751     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
752     setOperationAction(ISD::VSELECT, VT, Expand);
753     setOperationAction(ISD::SELECT_CC, VT, Expand);
754     for (MVT InnerVT : MVT::vector_valuetypes()) {
755       setTruncStoreAction(InnerVT, VT, Expand);
756
757       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
758       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
759
760       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
761       // types, we have to deal with them whether we ask for Expansion or not.
762       // Setting Expand causes its own optimisation problems though, so leave
763       // them legal.
764       if (VT.getVectorElementType() == MVT::i1)
765         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
766
767       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
768       // split/scalarized right now.
769       if (VT.getVectorElementType() == MVT::f16)
770         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
771     }
772   }
773
774   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
775   // with -msoft-float, disable use of MMX as well.
776   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
777     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
778     // No operations on x86mmx supported, everything uses intrinsics.
779   }
780
781   // MMX-sized vectors (other than x86mmx) are expected to be expanded
782   // into smaller operations.
783   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
784     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
785     setOperationAction(ISD::AND,                MMXTy,      Expand);
786     setOperationAction(ISD::OR,                 MMXTy,      Expand);
787     setOperationAction(ISD::XOR,                MMXTy,      Expand);
788     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
789     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
790     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
791   }
792   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
793
794   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
795     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
796
797     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
798     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
799     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
800     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
801     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
802     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
803     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
804     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
805     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
806     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
807     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
808     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
809     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
810     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
811   }
812
813   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
814     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
815
816     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
817     // registers cannot be used even for integer operations.
818     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
819     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
820     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
821     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
822
823     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
824     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
825     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
826     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
827     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
828     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
829     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
830     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
831     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
832     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
833     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
834     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
835     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
836     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
837     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
838     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
839     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
840     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
841     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
842     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
843     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
844     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
845     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
846
847     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
848     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
849     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
850     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
851
852     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
853     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
854     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
855     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
856
857     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
858     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
859     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
860     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
861     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
862
863     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
864     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
865     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
866     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
867
868     setOperationAction(ISD::CTTZ,               MVT::v16i8, Custom);
869     setOperationAction(ISD::CTTZ,               MVT::v8i16, Custom);
870     setOperationAction(ISD::CTTZ,               MVT::v4i32, Custom);
871     // ISD::CTTZ v2i64 - scalarization is faster.
872     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v16i8, Custom);
873     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v8i16, Custom);
874     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v4i32, Custom);
875     // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
876
877     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
878     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
879       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
880       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
881       setOperationAction(ISD::VSELECT,            VT, Custom);
882       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
883     }
884
885     // We support custom legalizing of sext and anyext loads for specific
886     // memory vector types which we can load as a scalar (or sequence of
887     // scalars) and extend in-register to a legal 128-bit vector type. For sext
888     // loads these must work with a single scalar load.
889     for (MVT VT : MVT::integer_vector_valuetypes()) {
890       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
891       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
892       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
893       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
894       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
895       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
896       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
897       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
898       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
899     }
900
901     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
902     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
903     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
904     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
905     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
906     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
907     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
908     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
909
910     if (Subtarget->is64Bit()) {
911       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
912       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
913     }
914
915     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
916     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
917       setOperationAction(ISD::AND,    VT, Promote);
918       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
919       setOperationAction(ISD::OR,     VT, Promote);
920       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
921       setOperationAction(ISD::XOR,    VT, Promote);
922       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
923       setOperationAction(ISD::LOAD,   VT, Promote);
924       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
925       setOperationAction(ISD::SELECT, VT, Promote);
926       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
927     }
928
929     // Custom lower v2i64 and v2f64 selects.
930     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
931     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
932     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
933     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
934
935     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
936     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
937
938     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
939
940     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
941     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
942     // As there is no 64-bit GPR available, we need build a special custom
943     // sequence to convert from v2i32 to v2f32.
944     if (!Subtarget->is64Bit())
945       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
946
947     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
948     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
949
950     for (MVT VT : MVT::fp_vector_valuetypes())
951       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
952
953     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
954     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
955     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
956   }
957
958   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
959     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
960       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
961       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
962       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
963       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
964       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
965     }
966
967     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
968     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
969     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
970     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
971     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
972     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
973     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
974     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
975
976     // FIXME: Do we need to handle scalar-to-vector here?
977     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
978
979     // We directly match byte blends in the backend as they match the VSELECT
980     // condition form.
981     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
982
983     // SSE41 brings specific instructions for doing vector sign extend even in
984     // cases where we don't have SRA.
985     for (MVT VT : MVT::integer_vector_valuetypes()) {
986       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
987       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
988       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
989     }
990
991     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
992     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
993     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
994     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
995     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
996     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
997     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
998
999     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
1000     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
1001     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
1002     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1003     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1004     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1005
1006     // i8 and i16 vectors are custom because the source register and source
1007     // source memory operand types are not the same width.  f32 vectors are
1008     // custom since the immediate controlling the insert encodes additional
1009     // information.
1010     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1011     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1012     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1013     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1014
1015     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1016     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1017     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1018     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1019
1020     // FIXME: these should be Legal, but that's only for the case where
1021     // the index is constant.  For now custom expand to deal with that.
1022     if (Subtarget->is64Bit()) {
1023       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1024       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1025     }
1026   }
1027
1028   if (Subtarget->hasSSE2()) {
1029     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1030     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1031     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1032
1033     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1034     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1035
1036     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1037     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1038
1039     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1040     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1041
1042     // In the customized shift lowering, the legal cases in AVX2 will be
1043     // recognized.
1044     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1045     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1046
1047     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1048     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1049
1050     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1051     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1052   }
1053
1054   if (Subtarget->hasXOP()) {
1055     setOperationAction(ISD::ROTL,              MVT::v16i8, Custom);
1056     setOperationAction(ISD::ROTL,              MVT::v8i16, Custom);
1057     setOperationAction(ISD::ROTL,              MVT::v4i32, Custom);
1058     setOperationAction(ISD::ROTL,              MVT::v2i64, Custom);
1059     setOperationAction(ISD::ROTL,              MVT::v32i8, Custom);
1060     setOperationAction(ISD::ROTL,              MVT::v16i16, Custom);
1061     setOperationAction(ISD::ROTL,              MVT::v8i32, Custom);
1062     setOperationAction(ISD::ROTL,              MVT::v4i64, Custom);
1063   }
1064
1065   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1066     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1067     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1068     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1069     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1070     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1071     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1072
1073     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1074     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1075     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1076
1077     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1078     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1079     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1080     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1081     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1082     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1083     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1084     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1085     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1086     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1087     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1088     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1089
1090     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1091     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1092     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1093     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1094     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1095     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1096     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1097     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1098     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1099     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1100     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1101     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1102
1103     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1104     // even though v8i16 is a legal type.
1105     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1106     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1107     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1108
1109     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1110     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1111     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1112
1113     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1114     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1115
1116     for (MVT VT : MVT::fp_vector_valuetypes())
1117       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1118
1119     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1120     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1121
1122     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1123     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1124
1125     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1126     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1127
1128     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1129     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1130     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1131     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1132
1133     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1134     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1135     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1136
1137     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1138     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1139     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1140     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1141     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1142     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1143     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1144     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1145     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1146     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1147     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1148     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1149
1150     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1151     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1152     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1153     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1154
1155     setOperationAction(ISD::CTTZ,              MVT::v32i8, Custom);
1156     setOperationAction(ISD::CTTZ,              MVT::v16i16, Custom);
1157     setOperationAction(ISD::CTTZ,              MVT::v8i32, Custom);
1158     setOperationAction(ISD::CTTZ,              MVT::v4i64, Custom);
1159     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v32i8, Custom);
1160     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v16i16, Custom);
1161     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v8i32, Custom);
1162     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v4i64, Custom);
1163
1164     if (Subtarget->hasAnyFMA()) {
1165       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1166       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1167       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1168       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1169       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1170       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1171     }
1172
1173     if (Subtarget->hasInt256()) {
1174       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1175       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1176       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1177       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1178
1179       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1180       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1181       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1182       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1183
1184       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1185       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1186       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1187       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1188
1189       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1190       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1191       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1192       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1193
1194       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1195       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1196       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1197       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1198       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1199       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1200       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1201       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1202       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1203       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1204       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1205       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1206
1207       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1208       // when we have a 256bit-wide blend with immediate.
1209       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1210
1211       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1212       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1213       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1214       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1215       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1216       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1217       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1218
1219       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1220       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1221       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1222       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1223       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1224       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1225     } else {
1226       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1227       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1228       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1229       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1230
1231       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1232       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1233       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1234       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1235
1236       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1237       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1238       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1239       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1240
1241       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1242       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1243       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1244       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1245       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1246       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1247       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1248       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1249       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1250       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1251       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1252       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1253     }
1254
1255     // In the customized shift lowering, the legal cases in AVX2 will be
1256     // recognized.
1257     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1258     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1259
1260     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1261     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1262
1263     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1264     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1265
1266     // Custom lower several nodes for 256-bit types.
1267     for (MVT VT : MVT::vector_valuetypes()) {
1268       if (VT.getScalarSizeInBits() >= 32) {
1269         setOperationAction(ISD::MLOAD,  VT, Legal);
1270         setOperationAction(ISD::MSTORE, VT, Legal);
1271       }
1272       // Extract subvector is special because the value type
1273       // (result) is 128-bit but the source is 256-bit wide.
1274       if (VT.is128BitVector()) {
1275         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1276       }
1277       // Do not attempt to custom lower other non-256-bit vectors
1278       if (!VT.is256BitVector())
1279         continue;
1280
1281       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1282       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1283       setOperationAction(ISD::VSELECT,            VT, Custom);
1284       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1285       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1286       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1287       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1288       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1289     }
1290
1291     if (Subtarget->hasInt256())
1292       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1293
1294     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1295     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1296       setOperationAction(ISD::AND,    VT, Promote);
1297       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1298       setOperationAction(ISD::OR,     VT, Promote);
1299       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1300       setOperationAction(ISD::XOR,    VT, Promote);
1301       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1302       setOperationAction(ISD::LOAD,   VT, Promote);
1303       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1304       setOperationAction(ISD::SELECT, VT, Promote);
1305       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1306     }
1307   }
1308
1309   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1310     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1311     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1312     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1313     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1314
1315     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1316     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1317     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1318
1319     for (MVT VT : MVT::fp_vector_valuetypes())
1320       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1321
1322     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1323     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1324     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1325     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1326     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1327     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1328     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1329     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1330     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1331     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1332     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1333     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1334
1335     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1336     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1337     setOperationAction(ISD::SELECT_CC,          MVT::i1,    Expand);
1338     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1339     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1340     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1341     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1342     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1343     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1344     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1345     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1346     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1347     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1348     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1349
1350     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1351     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1352     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1353     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1354     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1355     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1356     setOperationAction(ISD::FABS,               MVT::v16f32, Custom);
1357
1358     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1359     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1360     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1361     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1362     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1363     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1364     setOperationAction(ISD::FABS,               MVT::v8f64, Custom);
1365     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1366     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1367
1368     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1369     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1370     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1371     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1372     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1373     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1374     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1375     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1376     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1377     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1378     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1379     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1380     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1381     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1382     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1383     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1384
1385     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1386     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1387     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1388     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1389     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1390     if (Subtarget->hasVLX()){
1391       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1392       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1393       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1394       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1395       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1396
1397       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1398       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1399       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1400       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1401       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1402     } else {
1403       setOperationAction(ISD::MLOAD,    MVT::v8i32, Custom);
1404       setOperationAction(ISD::MLOAD,    MVT::v8f32, Custom);
1405       setOperationAction(ISD::MSTORE,   MVT::v8i32, Custom);
1406       setOperationAction(ISD::MSTORE,   MVT::v8f32, Custom);
1407     }
1408     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1409     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1410     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1411     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i1,  Custom);
1412     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v16i1, Custom);
1413     if (Subtarget->hasDQI()) {
1414       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1415       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1416
1417       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1418       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1419       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1420       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1421       if (Subtarget->hasVLX()) {
1422         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1423         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1424         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1425         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1426         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1427         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1428         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1429         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1430       }
1431     }
1432     if (Subtarget->hasVLX()) {
1433       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1434       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1435       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1436       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1437       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1438       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1439       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1440       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1441     }
1442     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1443     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1444     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1445     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1446     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1447     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1448     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1449     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1450     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1451     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1452     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1453     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1454     if (Subtarget->hasDQI()) {
1455       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1456       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1457     }
1458     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1459     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1460     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1461     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1462     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1463     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1464     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1465     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1466     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1467     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1468
1469     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1470     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1471     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1472     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1473     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1,   Custom);
1474
1475     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1476     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1477
1478     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1479
1480     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1481     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1482     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v16i1, Custom);
1483     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1484     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1485     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1486     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1487     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1488     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1489     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1490     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1491     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1492
1493     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1494     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1495     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1496     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1497     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1498     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1499     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1500     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1501
1502     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1503     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1504
1505     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1506     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1507
1508     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1509
1510     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1511     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1512
1513     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1514     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1515
1516     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1517     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1518
1519     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1520     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1521     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1522     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1523     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1524     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1525
1526     if (Subtarget->hasCDI()) {
1527       setOperationAction(ISD::CTLZ,             MVT::v8i64,  Legal);
1528       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1529       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64,  Expand);
1530       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Expand);
1531
1532       setOperationAction(ISD::CTLZ,             MVT::v8i16,  Custom);
1533       setOperationAction(ISD::CTLZ,             MVT::v16i8,  Custom);
1534       setOperationAction(ISD::CTLZ,             MVT::v16i16, Custom);
1535       setOperationAction(ISD::CTLZ,             MVT::v32i8,  Custom);
1536       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i16,  Expand);
1537       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i8,  Expand);
1538       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i16, Expand);
1539       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v32i8,  Expand);
1540
1541       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i64,  Custom);
1542       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v16i32, Custom);
1543
1544       if (Subtarget->hasVLX()) {
1545         setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1546         setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1547         setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1548         setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1549         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Expand);
1550         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Expand);
1551         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Expand);
1552         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Expand);
1553
1554         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1555         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1556         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1557         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1558       } else {
1559         setOperationAction(ISD::CTLZ,             MVT::v4i64, Custom);
1560         setOperationAction(ISD::CTLZ,             MVT::v8i32, Custom);
1561         setOperationAction(ISD::CTLZ,             MVT::v2i64, Custom);
1562         setOperationAction(ISD::CTLZ,             MVT::v4i32, Custom);
1563         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Expand);
1564         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Expand);
1565         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Expand);
1566         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Expand);
1567       }
1568     } // Subtarget->hasCDI()
1569
1570     if (Subtarget->hasDQI()) {
1571       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1572       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1573       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1574     }
1575     // Custom lower several nodes.
1576     for (MVT VT : MVT::vector_valuetypes()) {
1577       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1578       if (EltSize == 1) {
1579         setOperationAction(ISD::AND, VT, Legal);
1580         setOperationAction(ISD::OR,  VT, Legal);
1581         setOperationAction(ISD::XOR,  VT, Legal);
1582       }
1583       if ((VT.is128BitVector() || VT.is256BitVector()) && EltSize >= 32) {
1584         setOperationAction(ISD::MGATHER,  VT, Custom);
1585         setOperationAction(ISD::MSCATTER, VT, Custom);
1586       }
1587       // Extract subvector is special because the value type
1588       // (result) is 256/128-bit but the source is 512-bit wide.
1589       if (VT.is128BitVector() || VT.is256BitVector()) {
1590         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1591       }
1592       if (VT.getVectorElementType() == MVT::i1)
1593         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1594
1595       // Do not attempt to custom lower other non-512-bit vectors
1596       if (!VT.is512BitVector())
1597         continue;
1598
1599       if (EltSize >= 32) {
1600         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1601         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1602         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1603         setOperationAction(ISD::VSELECT,             VT, Legal);
1604         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1605         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1606         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1607         setOperationAction(ISD::MLOAD,               VT, Legal);
1608         setOperationAction(ISD::MSTORE,              VT, Legal);
1609         setOperationAction(ISD::MGATHER,  VT, Legal);
1610         setOperationAction(ISD::MSCATTER, VT, Custom);
1611       }
1612     }
1613     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1614       setOperationAction(ISD::SELECT, VT, Promote);
1615       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1616     }
1617   }// has  AVX-512
1618
1619   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1620     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1621     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1622
1623     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1624     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1625
1626     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1627     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1628     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1629     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1630     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1631     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1632     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1633     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1634     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1635     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1636     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1637     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1638     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1639     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i16, Custom);
1640     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i8, Custom);
1641     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1642     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1643     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i16, Custom);
1644     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i8, Custom);
1645     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1646     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1647     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1648     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1649     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1650     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1651     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1652     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1653     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1654     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i8, Custom);
1655     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1656     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1657     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1658     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1659     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i16, Custom);
1660     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i8, Custom);
1661     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1662     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1663     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1664     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1665     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1666     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i1, Custom);
1667     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i1, Custom);
1668
1669     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1670     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1671     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1672     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1673     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1674     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1675     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1676     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1677
1678     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1679     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1680     if (Subtarget->hasVLX())
1681       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1682
1683     if (Subtarget->hasCDI()) {
1684       setOperationAction(ISD::CTLZ,            MVT::v32i16, Custom);
1685       setOperationAction(ISD::CTLZ,            MVT::v64i8,  Custom);
1686       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Expand);
1687       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8,  Expand);
1688     }
1689
1690     for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1691       setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1692       setOperationAction(ISD::VSELECT,             VT, Legal);
1693       setOperationAction(ISD::SRL,                 VT, Custom);
1694       setOperationAction(ISD::SHL,                 VT, Custom);
1695       setOperationAction(ISD::SRA,                 VT, Custom);
1696
1697       setOperationAction(ISD::AND,    VT, Promote);
1698       AddPromotedToType (ISD::AND,    VT, MVT::v8i64);
1699       setOperationAction(ISD::OR,     VT, Promote);
1700       AddPromotedToType (ISD::OR,     VT, MVT::v8i64);
1701       setOperationAction(ISD::XOR,    VT, Promote);
1702       AddPromotedToType (ISD::XOR,    VT, MVT::v8i64);
1703     }
1704   }
1705
1706   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1707     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1708     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1709
1710     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1711     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1712     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1713     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1714     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1715     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1716     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1717     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1718     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1719     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1720     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i1, Custom);
1721     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i1, Custom);
1722
1723     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1724     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1725     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1726     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1727     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1728     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1729     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1730     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1731
1732     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1733     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1734     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1735     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1736     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1737     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1738     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1739     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1740   }
1741
1742   // We want to custom lower some of our intrinsics.
1743   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1744   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1745   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1746   if (!Subtarget->is64Bit()) {
1747     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1748     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1749   }
1750
1751   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1752   // handle type legalization for these operations here.
1753   //
1754   // FIXME: We really should do custom legalization for addition and
1755   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1756   // than generic legalization for 64-bit multiplication-with-overflow, though.
1757   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1758     if (VT == MVT::i64 && !Subtarget->is64Bit())
1759       continue;
1760     // Add/Sub/Mul with overflow operations are custom lowered.
1761     setOperationAction(ISD::SADDO, VT, Custom);
1762     setOperationAction(ISD::UADDO, VT, Custom);
1763     setOperationAction(ISD::SSUBO, VT, Custom);
1764     setOperationAction(ISD::USUBO, VT, Custom);
1765     setOperationAction(ISD::SMULO, VT, Custom);
1766     setOperationAction(ISD::UMULO, VT, Custom);
1767   }
1768
1769   if (!Subtarget->is64Bit()) {
1770     // These libcalls are not available in 32-bit.
1771     setLibcallName(RTLIB::SHL_I128, nullptr);
1772     setLibcallName(RTLIB::SRL_I128, nullptr);
1773     setLibcallName(RTLIB::SRA_I128, nullptr);
1774   }
1775
1776   // Combine sin / cos into one node or libcall if possible.
1777   if (Subtarget->hasSinCos()) {
1778     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1779     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1780     if (Subtarget->isTargetDarwin()) {
1781       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1782       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1783       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1784       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1785     }
1786   }
1787
1788   if (Subtarget->isTargetWin64()) {
1789     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1790     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1791     setOperationAction(ISD::SREM, MVT::i128, Custom);
1792     setOperationAction(ISD::UREM, MVT::i128, Custom);
1793     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1794     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1795   }
1796
1797   // We have target-specific dag combine patterns for the following nodes:
1798   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1799   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1800   setTargetDAGCombine(ISD::BITCAST);
1801   setTargetDAGCombine(ISD::VSELECT);
1802   setTargetDAGCombine(ISD::SELECT);
1803   setTargetDAGCombine(ISD::SHL);
1804   setTargetDAGCombine(ISD::SRA);
1805   setTargetDAGCombine(ISD::SRL);
1806   setTargetDAGCombine(ISD::OR);
1807   setTargetDAGCombine(ISD::AND);
1808   setTargetDAGCombine(ISD::ADD);
1809   setTargetDAGCombine(ISD::FADD);
1810   setTargetDAGCombine(ISD::FSUB);
1811   setTargetDAGCombine(ISD::FNEG);
1812   setTargetDAGCombine(ISD::FMA);
1813   setTargetDAGCombine(ISD::FMINNUM);
1814   setTargetDAGCombine(ISD::FMAXNUM);
1815   setTargetDAGCombine(ISD::SUB);
1816   setTargetDAGCombine(ISD::LOAD);
1817   setTargetDAGCombine(ISD::MLOAD);
1818   setTargetDAGCombine(ISD::STORE);
1819   setTargetDAGCombine(ISD::MSTORE);
1820   setTargetDAGCombine(ISD::TRUNCATE);
1821   setTargetDAGCombine(ISD::ZERO_EXTEND);
1822   setTargetDAGCombine(ISD::ANY_EXTEND);
1823   setTargetDAGCombine(ISD::SIGN_EXTEND);
1824   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1825   setTargetDAGCombine(ISD::SINT_TO_FP);
1826   setTargetDAGCombine(ISD::UINT_TO_FP);
1827   setTargetDAGCombine(ISD::SETCC);
1828   setTargetDAGCombine(ISD::BUILD_VECTOR);
1829   setTargetDAGCombine(ISD::MUL);
1830   setTargetDAGCombine(ISD::XOR);
1831   setTargetDAGCombine(ISD::MSCATTER);
1832   setTargetDAGCombine(ISD::MGATHER);
1833
1834   computeRegisterProperties(Subtarget->getRegisterInfo());
1835
1836   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1837   MaxStoresPerMemsetOptSize = 8;
1838   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1839   MaxStoresPerMemcpyOptSize = 4;
1840   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1841   MaxStoresPerMemmoveOptSize = 4;
1842   setPrefLoopAlignment(4); // 2^4 bytes.
1843
1844   // A predictable cmov does not hurt on an in-order CPU.
1845   // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1846   PredictableSelectIsExpensive = !Subtarget->isAtom();
1847   EnableExtLdPromotion = true;
1848   setPrefFunctionAlignment(4); // 2^4 bytes.
1849
1850   verifyIntrinsicTables();
1851 }
1852
1853 // This has so far only been implemented for 64-bit MachO.
1854 bool X86TargetLowering::useLoadStackGuardNode() const {
1855   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1856 }
1857
1858 TargetLoweringBase::LegalizeTypeAction
1859 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1860   if (ExperimentalVectorWideningLegalization &&
1861       VT.getVectorNumElements() != 1 &&
1862       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1863     return TypeWidenVector;
1864
1865   return TargetLoweringBase::getPreferredVectorAction(VT);
1866 }
1867
1868 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1869                                           EVT VT) const {
1870   if (!VT.isVector())
1871     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1872
1873   if (VT.isSimple()) {
1874     MVT VVT = VT.getSimpleVT();
1875     const unsigned NumElts = VVT.getVectorNumElements();
1876     const MVT EltVT = VVT.getVectorElementType();
1877     if (VVT.is512BitVector()) {
1878       if (Subtarget->hasAVX512())
1879         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1880             EltVT == MVT::f32 || EltVT == MVT::f64)
1881           switch(NumElts) {
1882           case  8: return MVT::v8i1;
1883           case 16: return MVT::v16i1;
1884         }
1885       if (Subtarget->hasBWI())
1886         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1887           switch(NumElts) {
1888           case 32: return MVT::v32i1;
1889           case 64: return MVT::v64i1;
1890         }
1891     }
1892
1893     if (VVT.is256BitVector() || VVT.is128BitVector()) {
1894       if (Subtarget->hasVLX())
1895         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1896             EltVT == MVT::f32 || EltVT == MVT::f64)
1897           switch(NumElts) {
1898           case 2: return MVT::v2i1;
1899           case 4: return MVT::v4i1;
1900           case 8: return MVT::v8i1;
1901         }
1902       if (Subtarget->hasBWI() && Subtarget->hasVLX())
1903         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1904           switch(NumElts) {
1905           case  8: return MVT::v8i1;
1906           case 16: return MVT::v16i1;
1907           case 32: return MVT::v32i1;
1908         }
1909     }
1910   }
1911
1912   return VT.changeVectorElementTypeToInteger();
1913 }
1914
1915 /// Helper for getByValTypeAlignment to determine
1916 /// the desired ByVal argument alignment.
1917 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1918   if (MaxAlign == 16)
1919     return;
1920   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1921     if (VTy->getBitWidth() == 128)
1922       MaxAlign = 16;
1923   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1924     unsigned EltAlign = 0;
1925     getMaxByValAlign(ATy->getElementType(), EltAlign);
1926     if (EltAlign > MaxAlign)
1927       MaxAlign = EltAlign;
1928   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1929     for (auto *EltTy : STy->elements()) {
1930       unsigned EltAlign = 0;
1931       getMaxByValAlign(EltTy, EltAlign);
1932       if (EltAlign > MaxAlign)
1933         MaxAlign = EltAlign;
1934       if (MaxAlign == 16)
1935         break;
1936     }
1937   }
1938 }
1939
1940 /// Return the desired alignment for ByVal aggregate
1941 /// function arguments in the caller parameter area. For X86, aggregates
1942 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1943 /// are at 4-byte boundaries.
1944 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1945                                                   const DataLayout &DL) const {
1946   if (Subtarget->is64Bit()) {
1947     // Max of 8 and alignment of type.
1948     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1949     if (TyAlign > 8)
1950       return TyAlign;
1951     return 8;
1952   }
1953
1954   unsigned Align = 4;
1955   if (Subtarget->hasSSE1())
1956     getMaxByValAlign(Ty, Align);
1957   return Align;
1958 }
1959
1960 /// Returns the target specific optimal type for load
1961 /// and store operations as a result of memset, memcpy, and memmove
1962 /// lowering. If DstAlign is zero that means it's safe to destination
1963 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1964 /// means there isn't a need to check it against alignment requirement,
1965 /// probably because the source does not need to be loaded. If 'IsMemset' is
1966 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1967 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1968 /// source is constant so it does not need to be loaded.
1969 /// It returns EVT::Other if the type should be determined using generic
1970 /// target-independent logic.
1971 EVT
1972 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1973                                        unsigned DstAlign, unsigned SrcAlign,
1974                                        bool IsMemset, bool ZeroMemset,
1975                                        bool MemcpyStrSrc,
1976                                        MachineFunction &MF) const {
1977   const Function *F = MF.getFunction();
1978   if ((!IsMemset || ZeroMemset) &&
1979       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1980     if (Size >= 16 &&
1981         (!Subtarget->isUnalignedMem16Slow() ||
1982          ((DstAlign == 0 || DstAlign >= 16) &&
1983           (SrcAlign == 0 || SrcAlign >= 16)))) {
1984       if (Size >= 32) {
1985         // FIXME: Check if unaligned 32-byte accesses are slow.
1986         if (Subtarget->hasInt256())
1987           return MVT::v8i32;
1988         if (Subtarget->hasFp256())
1989           return MVT::v8f32;
1990       }
1991       if (Subtarget->hasSSE2())
1992         return MVT::v4i32;
1993       if (Subtarget->hasSSE1())
1994         return MVT::v4f32;
1995     } else if (!MemcpyStrSrc && Size >= 8 &&
1996                !Subtarget->is64Bit() &&
1997                Subtarget->hasSSE2()) {
1998       // Do not use f64 to lower memcpy if source is string constant. It's
1999       // better to use i32 to avoid the loads.
2000       return MVT::f64;
2001     }
2002   }
2003   // This is a compromise. If we reach here, unaligned accesses may be slow on
2004   // this target. However, creating smaller, aligned accesses could be even
2005   // slower and would certainly be a lot more code.
2006   if (Subtarget->is64Bit() && Size >= 8)
2007     return MVT::i64;
2008   return MVT::i32;
2009 }
2010
2011 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2012   if (VT == MVT::f32)
2013     return X86ScalarSSEf32;
2014   else if (VT == MVT::f64)
2015     return X86ScalarSSEf64;
2016   return true;
2017 }
2018
2019 bool
2020 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
2021                                                   unsigned,
2022                                                   unsigned,
2023                                                   bool *Fast) const {
2024   if (Fast) {
2025     switch (VT.getSizeInBits()) {
2026     default:
2027       // 8-byte and under are always assumed to be fast.
2028       *Fast = true;
2029       break;
2030     case 128:
2031       *Fast = !Subtarget->isUnalignedMem16Slow();
2032       break;
2033     case 256:
2034       *Fast = !Subtarget->isUnalignedMem32Slow();
2035       break;
2036     // TODO: What about AVX-512 (512-bit) accesses?
2037     }
2038   }
2039   // Misaligned accesses of any size are always allowed.
2040   return true;
2041 }
2042
2043 /// Return the entry encoding for a jump table in the
2044 /// current function.  The returned value is a member of the
2045 /// MachineJumpTableInfo::JTEntryKind enum.
2046 unsigned X86TargetLowering::getJumpTableEncoding() const {
2047   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2048   // symbol.
2049   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2050       Subtarget->isPICStyleGOT())
2051     return MachineJumpTableInfo::EK_Custom32;
2052
2053   // Otherwise, use the normal jump table encoding heuristics.
2054   return TargetLowering::getJumpTableEncoding();
2055 }
2056
2057 bool X86TargetLowering::useSoftFloat() const {
2058   return Subtarget->useSoftFloat();
2059 }
2060
2061 const MCExpr *
2062 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2063                                              const MachineBasicBlock *MBB,
2064                                              unsigned uid,MCContext &Ctx) const{
2065   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2066          Subtarget->isPICStyleGOT());
2067   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2068   // entries.
2069   return MCSymbolRefExpr::create(MBB->getSymbol(),
2070                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2071 }
2072
2073 /// Returns relocation base for the given PIC jumptable.
2074 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2075                                                     SelectionDAG &DAG) const {
2076   if (!Subtarget->is64Bit())
2077     // This doesn't have SDLoc associated with it, but is not really the
2078     // same as a Register.
2079     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2080                        getPointerTy(DAG.getDataLayout()));
2081   return Table;
2082 }
2083
2084 /// This returns the relocation base for the given PIC jumptable,
2085 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2086 const MCExpr *X86TargetLowering::
2087 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2088                              MCContext &Ctx) const {
2089   // X86-64 uses RIP relative addressing based on the jump table label.
2090   if (Subtarget->isPICStyleRIPRel())
2091     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2092
2093   // Otherwise, the reference is relative to the PIC base.
2094   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2095 }
2096
2097 std::pair<const TargetRegisterClass *, uint8_t>
2098 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2099                                            MVT VT) const {
2100   const TargetRegisterClass *RRC = nullptr;
2101   uint8_t Cost = 1;
2102   switch (VT.SimpleTy) {
2103   default:
2104     return TargetLowering::findRepresentativeClass(TRI, VT);
2105   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2106     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2107     break;
2108   case MVT::x86mmx:
2109     RRC = &X86::VR64RegClass;
2110     break;
2111   case MVT::f32: case MVT::f64:
2112   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2113   case MVT::v4f32: case MVT::v2f64:
2114   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2115   case MVT::v4f64:
2116     RRC = &X86::VR128RegClass;
2117     break;
2118   }
2119   return std::make_pair(RRC, Cost);
2120 }
2121
2122 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2123                                                unsigned &Offset) const {
2124   if (!Subtarget->isTargetLinux())
2125     return false;
2126
2127   if (Subtarget->is64Bit()) {
2128     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2129     Offset = 0x28;
2130     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2131       AddressSpace = 256;
2132     else
2133       AddressSpace = 257;
2134   } else {
2135     // %gs:0x14 on i386
2136     Offset = 0x14;
2137     AddressSpace = 256;
2138   }
2139   return true;
2140 }
2141
2142 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2143   if (!Subtarget->isTargetAndroid())
2144     return TargetLowering::getSafeStackPointerLocation(IRB);
2145
2146   // Android provides a fixed TLS slot for the SafeStack pointer. See the
2147   // definition of TLS_SLOT_SAFESTACK in
2148   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2149   unsigned AddressSpace, Offset;
2150   if (Subtarget->is64Bit()) {
2151     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2152     Offset = 0x48;
2153     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2154       AddressSpace = 256;
2155     else
2156       AddressSpace = 257;
2157   } else {
2158     // %gs:0x24 on i386
2159     Offset = 0x24;
2160     AddressSpace = 256;
2161   }
2162
2163   return ConstantExpr::getIntToPtr(
2164       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2165       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2166 }
2167
2168 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2169                                             unsigned DestAS) const {
2170   assert(SrcAS != DestAS && "Expected different address spaces!");
2171
2172   return SrcAS < 256 && DestAS < 256;
2173 }
2174
2175 //===----------------------------------------------------------------------===//
2176 //               Return Value Calling Convention Implementation
2177 //===----------------------------------------------------------------------===//
2178
2179 #include "X86GenCallingConv.inc"
2180
2181 bool X86TargetLowering::CanLowerReturn(
2182     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2183     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2184   SmallVector<CCValAssign, 16> RVLocs;
2185   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2186   return CCInfo.CheckReturn(Outs, RetCC_X86);
2187 }
2188
2189 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2190   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2191   return ScratchRegs;
2192 }
2193
2194 SDValue
2195 X86TargetLowering::LowerReturn(SDValue Chain,
2196                                CallingConv::ID CallConv, bool isVarArg,
2197                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2198                                const SmallVectorImpl<SDValue> &OutVals,
2199                                SDLoc dl, SelectionDAG &DAG) const {
2200   MachineFunction &MF = DAG.getMachineFunction();
2201   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2202
2203   if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2204     report_fatal_error("X86 interrupts may not return any value");
2205
2206   SmallVector<CCValAssign, 16> RVLocs;
2207   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2208   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2209
2210   SDValue Flag;
2211   SmallVector<SDValue, 6> RetOps;
2212   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2213   // Operand #1 = Bytes To Pop
2214   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2215                    MVT::i16));
2216
2217   // Copy the result values into the output registers.
2218   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2219     CCValAssign &VA = RVLocs[i];
2220     assert(VA.isRegLoc() && "Can only return in registers!");
2221     SDValue ValToCopy = OutVals[i];
2222     EVT ValVT = ValToCopy.getValueType();
2223
2224     // Promote values to the appropriate types.
2225     if (VA.getLocInfo() == CCValAssign::SExt)
2226       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2227     else if (VA.getLocInfo() == CCValAssign::ZExt)
2228       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2229     else if (VA.getLocInfo() == CCValAssign::AExt) {
2230       if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2231         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2232       else
2233         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2234     }
2235     else if (VA.getLocInfo() == CCValAssign::BCvt)
2236       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2237
2238     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2239            "Unexpected FP-extend for return value.");
2240
2241     // If this is x86-64, and we disabled SSE, we can't return FP values,
2242     // or SSE or MMX vectors.
2243     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2244          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2245           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2246       report_fatal_error("SSE register return with SSE disabled");
2247     }
2248     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2249     // llvm-gcc has never done it right and no one has noticed, so this
2250     // should be OK for now.
2251     if (ValVT == MVT::f64 &&
2252         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2253       report_fatal_error("SSE2 register return with SSE2 disabled");
2254
2255     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2256     // the RET instruction and handled by the FP Stackifier.
2257     if (VA.getLocReg() == X86::FP0 ||
2258         VA.getLocReg() == X86::FP1) {
2259       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2260       // change the value to the FP stack register class.
2261       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2262         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2263       RetOps.push_back(ValToCopy);
2264       // Don't emit a copytoreg.
2265       continue;
2266     }
2267
2268     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2269     // which is returned in RAX / RDX.
2270     if (Subtarget->is64Bit()) {
2271       if (ValVT == MVT::x86mmx) {
2272         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2273           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2274           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2275                                   ValToCopy);
2276           // If we don't have SSE2 available, convert to v4f32 so the generated
2277           // register is legal.
2278           if (!Subtarget->hasSSE2())
2279             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2280         }
2281       }
2282     }
2283
2284     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2285     Flag = Chain.getValue(1);
2286     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2287   }
2288
2289   // All x86 ABIs require that for returning structs by value we copy
2290   // the sret argument into %rax/%eax (depending on ABI) for the return.
2291   // We saved the argument into a virtual register in the entry block,
2292   // so now we copy the value out and into %rax/%eax.
2293   //
2294   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2295   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2296   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2297   // either case FuncInfo->setSRetReturnReg() will have been called.
2298   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2299     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2300                                      getPointerTy(MF.getDataLayout()));
2301
2302     unsigned RetValReg
2303         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2304           X86::RAX : X86::EAX;
2305     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2306     Flag = Chain.getValue(1);
2307
2308     // RAX/EAX now acts like a return value.
2309     RetOps.push_back(
2310         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2311   }
2312
2313   RetOps[0] = Chain;  // Update chain.
2314
2315   // Add the flag if we have it.
2316   if (Flag.getNode())
2317     RetOps.push_back(Flag);
2318
2319   X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2320   if (CallConv == CallingConv::X86_INTR)
2321     opcode = X86ISD::IRET;
2322   return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2323 }
2324
2325 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2326   if (N->getNumValues() != 1)
2327     return false;
2328   if (!N->hasNUsesOfValue(1, 0))
2329     return false;
2330
2331   SDValue TCChain = Chain;
2332   SDNode *Copy = *N->use_begin();
2333   if (Copy->getOpcode() == ISD::CopyToReg) {
2334     // If the copy has a glue operand, we conservatively assume it isn't safe to
2335     // perform a tail call.
2336     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2337       return false;
2338     TCChain = Copy->getOperand(0);
2339   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2340     return false;
2341
2342   bool HasRet = false;
2343   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2344        UI != UE; ++UI) {
2345     if (UI->getOpcode() != X86ISD::RET_FLAG)
2346       return false;
2347     // If we are returning more than one value, we can definitely
2348     // not make a tail call see PR19530
2349     if (UI->getNumOperands() > 4)
2350       return false;
2351     if (UI->getNumOperands() == 4 &&
2352         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2353       return false;
2354     HasRet = true;
2355   }
2356
2357   if (!HasRet)
2358     return false;
2359
2360   Chain = TCChain;
2361   return true;
2362 }
2363
2364 EVT
2365 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2366                                             ISD::NodeType ExtendKind) const {
2367   MVT ReturnMVT;
2368   // TODO: Is this also valid on 32-bit?
2369   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2370     ReturnMVT = MVT::i8;
2371   else
2372     ReturnMVT = MVT::i32;
2373
2374   EVT MinVT = getRegisterType(Context, ReturnMVT);
2375   return VT.bitsLT(MinVT) ? MinVT : VT;
2376 }
2377
2378 /// Lower the result values of a call into the
2379 /// appropriate copies out of appropriate physical registers.
2380 ///
2381 SDValue
2382 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2383                                    CallingConv::ID CallConv, bool isVarArg,
2384                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2385                                    SDLoc dl, SelectionDAG &DAG,
2386                                    SmallVectorImpl<SDValue> &InVals) const {
2387
2388   // Assign locations to each value returned by this call.
2389   SmallVector<CCValAssign, 16> RVLocs;
2390   bool Is64Bit = Subtarget->is64Bit();
2391   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2392                  *DAG.getContext());
2393   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2394
2395   // Copy all of the result registers out of their specified physreg.
2396   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2397     CCValAssign &VA = RVLocs[i];
2398     EVT CopyVT = VA.getLocVT();
2399
2400     // If this is x86-64, and we disabled SSE, we can't return FP values
2401     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2402         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2403       report_fatal_error("SSE register return with SSE disabled");
2404     }
2405
2406     // If we prefer to use the value in xmm registers, copy it out as f80 and
2407     // use a truncate to move it from fp stack reg to xmm reg.
2408     bool RoundAfterCopy = false;
2409     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2410         isScalarFPTypeInSSEReg(VA.getValVT())) {
2411       CopyVT = MVT::f80;
2412       RoundAfterCopy = (CopyVT != VA.getLocVT());
2413     }
2414
2415     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2416                                CopyVT, InFlag).getValue(1);
2417     SDValue Val = Chain.getValue(0);
2418
2419     if (RoundAfterCopy)
2420       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2421                         // This truncation won't change the value.
2422                         DAG.getIntPtrConstant(1, dl));
2423
2424     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2425       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2426
2427     InFlag = Chain.getValue(2);
2428     InVals.push_back(Val);
2429   }
2430
2431   return Chain;
2432 }
2433
2434 //===----------------------------------------------------------------------===//
2435 //                C & StdCall & Fast Calling Convention implementation
2436 //===----------------------------------------------------------------------===//
2437 //  StdCall calling convention seems to be standard for many Windows' API
2438 //  routines and around. It differs from C calling convention just a little:
2439 //  callee should clean up the stack, not caller. Symbols should be also
2440 //  decorated in some fancy way :) It doesn't support any vector arguments.
2441 //  For info on fast calling convention see Fast Calling Convention (tail call)
2442 //  implementation LowerX86_32FastCCCallTo.
2443
2444 /// CallIsStructReturn - Determines whether a call uses struct return
2445 /// semantics.
2446 enum StructReturnType {
2447   NotStructReturn,
2448   RegStructReturn,
2449   StackStructReturn
2450 };
2451 static StructReturnType
2452 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsMCU) {
2453   if (Outs.empty())
2454     return NotStructReturn;
2455
2456   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2457   if (!Flags.isSRet())
2458     return NotStructReturn;
2459   if (Flags.isInReg() || IsMCU)
2460     return RegStructReturn;
2461   return StackStructReturn;
2462 }
2463
2464 /// Determines whether a function uses struct return semantics.
2465 static StructReturnType
2466 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsMCU) {
2467   if (Ins.empty())
2468     return NotStructReturn;
2469
2470   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2471   if (!Flags.isSRet())
2472     return NotStructReturn;
2473   if (Flags.isInReg() || IsMCU)
2474     return RegStructReturn;
2475   return StackStructReturn;
2476 }
2477
2478 /// Make a copy of an aggregate at address specified by "Src" to address
2479 /// "Dst" with size and alignment information specified by the specific
2480 /// parameter attribute. The copy will be passed as a byval function parameter.
2481 static SDValue
2482 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2483                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2484                           SDLoc dl) {
2485   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2486
2487   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2488                        /*isVolatile*/false, /*AlwaysInline=*/true,
2489                        /*isTailCall*/false,
2490                        MachinePointerInfo(), MachinePointerInfo());
2491 }
2492
2493 /// Return true if the calling convention is one that we can guarantee TCO for.
2494 static bool canGuaranteeTCO(CallingConv::ID CC) {
2495   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2496           CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2497 }
2498
2499 /// Return true if we might ever do TCO for calls with this calling convention.
2500 static bool mayTailCallThisCC(CallingConv::ID CC) {
2501   switch (CC) {
2502   // C calling conventions:
2503   case CallingConv::C:
2504   case CallingConv::X86_64_Win64:
2505   case CallingConv::X86_64_SysV:
2506   // Callee pop conventions:
2507   case CallingConv::X86_ThisCall:
2508   case CallingConv::X86_StdCall:
2509   case CallingConv::X86_VectorCall:
2510   case CallingConv::X86_FastCall:
2511     return true;
2512   default:
2513     return canGuaranteeTCO(CC);
2514   }
2515 }
2516
2517 /// Return true if the function is being made into a tailcall target by
2518 /// changing its ABI.
2519 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2520   return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2521 }
2522
2523 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2524   auto Attr =
2525       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2526   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2527     return false;
2528
2529   CallSite CS(CI);
2530   CallingConv::ID CalleeCC = CS.getCallingConv();
2531   if (!mayTailCallThisCC(CalleeCC))
2532     return false;
2533
2534   return true;
2535 }
2536
2537 SDValue
2538 X86TargetLowering::LowerMemArgument(SDValue Chain,
2539                                     CallingConv::ID CallConv,
2540                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2541                                     SDLoc dl, SelectionDAG &DAG,
2542                                     const CCValAssign &VA,
2543                                     MachineFrameInfo *MFI,
2544                                     unsigned i) const {
2545   // Create the nodes corresponding to a load from this parameter slot.
2546   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2547   bool AlwaysUseMutable = shouldGuaranteeTCO(
2548       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2549   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2550   EVT ValVT;
2551
2552   // If value is passed by pointer we have address passed instead of the value
2553   // itself.
2554   bool ExtendedInMem = VA.isExtInLoc() &&
2555     VA.getValVT().getScalarType() == MVT::i1;
2556
2557   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2558     ValVT = VA.getLocVT();
2559   else
2560     ValVT = VA.getValVT();
2561
2562   // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2563   // taken by a return address.
2564   int Offset = 0;
2565   if (CallConv == CallingConv::X86_INTR) {
2566     const X86Subtarget& Subtarget =
2567         static_cast<const X86Subtarget&>(DAG.getSubtarget());
2568     // X86 interrupts may take one or two arguments.
2569     // On the stack there will be no return address as in regular call.
2570     // Offset of last argument need to be set to -4/-8 bytes.
2571     // Where offset of the first argument out of two, should be set to 0 bytes.
2572     Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2573   }
2574
2575   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2576   // changed with more analysis.
2577   // In case of tail call optimization mark all arguments mutable. Since they
2578   // could be overwritten by lowering of arguments in case of a tail call.
2579   if (Flags.isByVal()) {
2580     unsigned Bytes = Flags.getByValSize();
2581     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2582     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2583     // Adjust SP offset of interrupt parameter.
2584     if (CallConv == CallingConv::X86_INTR) {
2585       MFI->setObjectOffset(FI, Offset);
2586     }
2587     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2588   } else {
2589     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2590                                     VA.getLocMemOffset(), isImmutable);
2591     // Adjust SP offset of interrupt parameter.
2592     if (CallConv == CallingConv::X86_INTR) {
2593       MFI->setObjectOffset(FI, Offset);
2594     }
2595
2596     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2597     SDValue Val = DAG.getLoad(
2598         ValVT, dl, Chain, FIN,
2599         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2600         false, false, 0);
2601     return ExtendedInMem ?
2602       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2603   }
2604 }
2605
2606 // FIXME: Get this from tablegen.
2607 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2608                                                 const X86Subtarget *Subtarget) {
2609   assert(Subtarget->is64Bit());
2610
2611   if (Subtarget->isCallingConvWin64(CallConv)) {
2612     static const MCPhysReg GPR64ArgRegsWin64[] = {
2613       X86::RCX, X86::RDX, X86::R8,  X86::R9
2614     };
2615     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2616   }
2617
2618   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2619     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2620   };
2621   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2622 }
2623
2624 // FIXME: Get this from tablegen.
2625 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2626                                                 CallingConv::ID CallConv,
2627                                                 const X86Subtarget *Subtarget) {
2628   assert(Subtarget->is64Bit());
2629   if (Subtarget->isCallingConvWin64(CallConv)) {
2630     // The XMM registers which might contain var arg parameters are shadowed
2631     // in their paired GPR.  So we only need to save the GPR to their home
2632     // slots.
2633     // TODO: __vectorcall will change this.
2634     return None;
2635   }
2636
2637   const Function *Fn = MF.getFunction();
2638   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2639   bool isSoftFloat = Subtarget->useSoftFloat();
2640   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2641          "SSE register cannot be used when SSE is disabled!");
2642   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2643     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2644     // registers.
2645     return None;
2646
2647   static const MCPhysReg XMMArgRegs64Bit[] = {
2648     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2649     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2650   };
2651   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2652 }
2653
2654 SDValue X86TargetLowering::LowerFormalArguments(
2655     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2656     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2657     SmallVectorImpl<SDValue> &InVals) const {
2658   MachineFunction &MF = DAG.getMachineFunction();
2659   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2660   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2661
2662   const Function* Fn = MF.getFunction();
2663   if (Fn->hasExternalLinkage() &&
2664       Subtarget->isTargetCygMing() &&
2665       Fn->getName() == "main")
2666     FuncInfo->setForceFramePointer(true);
2667
2668   MachineFrameInfo *MFI = MF.getFrameInfo();
2669   bool Is64Bit = Subtarget->is64Bit();
2670   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2671
2672   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2673          "Var args not supported with calling convention fastcc, ghc or hipe");
2674
2675   if (CallConv == CallingConv::X86_INTR) {
2676     bool isLegal = Ins.size() == 1 ||
2677                    (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
2678                                         (!Is64Bit && Ins[1].VT == MVT::i32)));
2679     if (!isLegal)
2680       report_fatal_error("X86 interrupts may take one or two arguments");
2681   }
2682
2683   // Assign locations to all of the incoming arguments.
2684   SmallVector<CCValAssign, 16> ArgLocs;
2685   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2686
2687   // Allocate shadow area for Win64
2688   if (IsWin64)
2689     CCInfo.AllocateStack(32, 8);
2690
2691   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2692
2693   unsigned LastVal = ~0U;
2694   SDValue ArgValue;
2695   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2696     CCValAssign &VA = ArgLocs[i];
2697     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2698     // places.
2699     assert(VA.getValNo() != LastVal &&
2700            "Don't support value assigned to multiple locs yet");
2701     (void)LastVal;
2702     LastVal = VA.getValNo();
2703
2704     if (VA.isRegLoc()) {
2705       EVT RegVT = VA.getLocVT();
2706       const TargetRegisterClass *RC;
2707       if (RegVT == MVT::i32)
2708         RC = &X86::GR32RegClass;
2709       else if (Is64Bit && RegVT == MVT::i64)
2710         RC = &X86::GR64RegClass;
2711       else if (RegVT == MVT::f32)
2712         RC = &X86::FR32RegClass;
2713       else if (RegVT == MVT::f64)
2714         RC = &X86::FR64RegClass;
2715       else if (RegVT == MVT::f128)
2716         RC = &X86::FR128RegClass;
2717       else if (RegVT.is512BitVector())
2718         RC = &X86::VR512RegClass;
2719       else if (RegVT.is256BitVector())
2720         RC = &X86::VR256RegClass;
2721       else if (RegVT.is128BitVector())
2722         RC = &X86::VR128RegClass;
2723       else if (RegVT == MVT::x86mmx)
2724         RC = &X86::VR64RegClass;
2725       else if (RegVT == MVT::i1)
2726         RC = &X86::VK1RegClass;
2727       else if (RegVT == MVT::v8i1)
2728         RC = &X86::VK8RegClass;
2729       else if (RegVT == MVT::v16i1)
2730         RC = &X86::VK16RegClass;
2731       else if (RegVT == MVT::v32i1)
2732         RC = &X86::VK32RegClass;
2733       else if (RegVT == MVT::v64i1)
2734         RC = &X86::VK64RegClass;
2735       else
2736         llvm_unreachable("Unknown argument type!");
2737
2738       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2739       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2740
2741       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2742       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2743       // right size.
2744       if (VA.getLocInfo() == CCValAssign::SExt)
2745         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2746                                DAG.getValueType(VA.getValVT()));
2747       else if (VA.getLocInfo() == CCValAssign::ZExt)
2748         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2749                                DAG.getValueType(VA.getValVT()));
2750       else if (VA.getLocInfo() == CCValAssign::BCvt)
2751         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2752
2753       if (VA.isExtInLoc()) {
2754         // Handle MMX values passed in XMM regs.
2755         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2756           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2757         else
2758           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2759       }
2760     } else {
2761       assert(VA.isMemLoc());
2762       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2763     }
2764
2765     // If value is passed via pointer - do a load.
2766     if (VA.getLocInfo() == CCValAssign::Indirect)
2767       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2768                              MachinePointerInfo(), false, false, false, 0);
2769
2770     InVals.push_back(ArgValue);
2771   }
2772
2773   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2774     // All x86 ABIs require that for returning structs by value we copy the
2775     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2776     // the argument into a virtual register so that we can access it from the
2777     // return points.
2778     if (Ins[i].Flags.isSRet()) {
2779       unsigned Reg = FuncInfo->getSRetReturnReg();
2780       if (!Reg) {
2781         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2782         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2783         FuncInfo->setSRetReturnReg(Reg);
2784       }
2785       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2786       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2787       break;
2788     }
2789   }
2790
2791   unsigned StackSize = CCInfo.getNextStackOffset();
2792   // Align stack specially for tail calls.
2793   if (shouldGuaranteeTCO(CallConv,
2794                          MF.getTarget().Options.GuaranteedTailCallOpt))
2795     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2796
2797   // If the function takes variable number of arguments, make a frame index for
2798   // the start of the first vararg value... for expansion of llvm.va_start. We
2799   // can skip this if there are no va_start calls.
2800   if (MFI->hasVAStart() &&
2801       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2802                    CallConv != CallingConv::X86_ThisCall))) {
2803     FuncInfo->setVarArgsFrameIndex(
2804         MFI->CreateFixedObject(1, StackSize, true));
2805   }
2806
2807   // Figure out if XMM registers are in use.
2808   assert(!(Subtarget->useSoftFloat() &&
2809            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2810          "SSE register cannot be used when SSE is disabled!");
2811
2812   // 64-bit calling conventions support varargs and register parameters, so we
2813   // have to do extra work to spill them in the prologue.
2814   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2815     // Find the first unallocated argument registers.
2816     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2817     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2818     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2819     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2820     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2821            "SSE register cannot be used when SSE is disabled!");
2822
2823     // Gather all the live in physical registers.
2824     SmallVector<SDValue, 6> LiveGPRs;
2825     SmallVector<SDValue, 8> LiveXMMRegs;
2826     SDValue ALVal;
2827     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2828       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2829       LiveGPRs.push_back(
2830           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2831     }
2832     if (!ArgXMMs.empty()) {
2833       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2834       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2835       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2836         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2837         LiveXMMRegs.push_back(
2838             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2839       }
2840     }
2841
2842     if (IsWin64) {
2843       // Get to the caller-allocated home save location.  Add 8 to account
2844       // for the return address.
2845       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2846       FuncInfo->setRegSaveFrameIndex(
2847           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2848       // Fixup to set vararg frame on shadow area (4 x i64).
2849       if (NumIntRegs < 4)
2850         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2851     } else {
2852       // For X86-64, if there are vararg parameters that are passed via
2853       // registers, then we must store them to their spots on the stack so
2854       // they may be loaded by deferencing the result of va_next.
2855       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2856       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2857       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2858           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2859     }
2860
2861     // Store the integer parameter registers.
2862     SmallVector<SDValue, 8> MemOps;
2863     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2864                                       getPointerTy(DAG.getDataLayout()));
2865     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2866     for (SDValue Val : LiveGPRs) {
2867       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2868                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2869       SDValue Store =
2870           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2871                        MachinePointerInfo::getFixedStack(
2872                            DAG.getMachineFunction(),
2873                            FuncInfo->getRegSaveFrameIndex(), Offset),
2874                        false, false, 0);
2875       MemOps.push_back(Store);
2876       Offset += 8;
2877     }
2878
2879     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2880       // Now store the XMM (fp + vector) parameter registers.
2881       SmallVector<SDValue, 12> SaveXMMOps;
2882       SaveXMMOps.push_back(Chain);
2883       SaveXMMOps.push_back(ALVal);
2884       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2885                              FuncInfo->getRegSaveFrameIndex(), dl));
2886       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2887                              FuncInfo->getVarArgsFPOffset(), dl));
2888       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2889                         LiveXMMRegs.end());
2890       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2891                                    MVT::Other, SaveXMMOps));
2892     }
2893
2894     if (!MemOps.empty())
2895       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2896   }
2897
2898   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2899     // Find the largest legal vector type.
2900     MVT VecVT = MVT::Other;
2901     // FIXME: Only some x86_32 calling conventions support AVX512.
2902     if (Subtarget->hasAVX512() &&
2903         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2904                      CallConv == CallingConv::Intel_OCL_BI)))
2905       VecVT = MVT::v16f32;
2906     else if (Subtarget->hasAVX())
2907       VecVT = MVT::v8f32;
2908     else if (Subtarget->hasSSE2())
2909       VecVT = MVT::v4f32;
2910
2911     // We forward some GPRs and some vector types.
2912     SmallVector<MVT, 2> RegParmTypes;
2913     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2914     RegParmTypes.push_back(IntVT);
2915     if (VecVT != MVT::Other)
2916       RegParmTypes.push_back(VecVT);
2917
2918     // Compute the set of forwarded registers. The rest are scratch.
2919     SmallVectorImpl<ForwardedRegister> &Forwards =
2920         FuncInfo->getForwardedMustTailRegParms();
2921     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2922
2923     // Conservatively forward AL on x86_64, since it might be used for varargs.
2924     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2925       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2926       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2927     }
2928
2929     // Copy all forwards from physical to virtual registers.
2930     for (ForwardedRegister &F : Forwards) {
2931       // FIXME: Can we use a less constrained schedule?
2932       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2933       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2934       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2935     }
2936   }
2937
2938   // Some CCs need callee pop.
2939   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2940                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2941     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2942   } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
2943     // X86 interrupts must pop the error code if present
2944     FuncInfo->setBytesToPopOnReturn(Is64Bit ? 8 : 4);
2945   } else {
2946     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2947     // If this is an sret function, the return should pop the hidden pointer.
2948     if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2949         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2950         argsAreStructReturn(Ins, Subtarget->isTargetMCU()) == StackStructReturn)
2951       FuncInfo->setBytesToPopOnReturn(4);
2952   }
2953
2954   if (!Is64Bit) {
2955     // RegSaveFrameIndex is X86-64 only.
2956     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2957     if (CallConv == CallingConv::X86_FastCall ||
2958         CallConv == CallingConv::X86_ThisCall)
2959       // fastcc functions can't have varargs.
2960       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2961   }
2962
2963   FuncInfo->setArgumentStackSize(StackSize);
2964
2965   if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
2966     EHPersonality Personality = classifyEHPersonality(Fn->getPersonalityFn());
2967     if (Personality == EHPersonality::CoreCLR) {
2968       assert(Is64Bit);
2969       // TODO: Add a mechanism to frame lowering that will allow us to indicate
2970       // that we'd prefer this slot be allocated towards the bottom of the frame
2971       // (i.e. near the stack pointer after allocating the frame).  Every
2972       // funclet needs a copy of this slot in its (mostly empty) frame, and the
2973       // offset from the bottom of this and each funclet's frame must be the
2974       // same, so the size of funclets' (mostly empty) frames is dictated by
2975       // how far this slot is from the bottom (since they allocate just enough
2976       // space to accomodate holding this slot at the correct offset).
2977       int PSPSymFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2978       EHInfo->PSPSymFrameIdx = PSPSymFI;
2979     }
2980   }
2981
2982   return Chain;
2983 }
2984
2985 SDValue
2986 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2987                                     SDValue StackPtr, SDValue Arg,
2988                                     SDLoc dl, SelectionDAG &DAG,
2989                                     const CCValAssign &VA,
2990                                     ISD::ArgFlagsTy Flags) const {
2991   unsigned LocMemOffset = VA.getLocMemOffset();
2992   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2993   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2994                        StackPtr, PtrOff);
2995   if (Flags.isByVal())
2996     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2997
2998   return DAG.getStore(
2999       Chain, dl, Arg, PtrOff,
3000       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
3001       false, false, 0);
3002 }
3003
3004 /// Emit a load of return address if tail call
3005 /// optimization is performed and it is required.
3006 SDValue
3007 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
3008                                            SDValue &OutRetAddr, SDValue Chain,
3009                                            bool IsTailCall, bool Is64Bit,
3010                                            int FPDiff, SDLoc dl) const {
3011   // Adjust the Return address stack slot.
3012   EVT VT = getPointerTy(DAG.getDataLayout());
3013   OutRetAddr = getReturnAddressFrameIndex(DAG);
3014
3015   // Load the "old" Return address.
3016   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
3017                            false, false, false, 0);
3018   return SDValue(OutRetAddr.getNode(), 1);
3019 }
3020
3021 /// Emit a store of the return address if tail call
3022 /// optimization is performed and it is required (FPDiff!=0).
3023 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
3024                                         SDValue Chain, SDValue RetAddrFrIdx,
3025                                         EVT PtrVT, unsigned SlotSize,
3026                                         int FPDiff, SDLoc dl) {
3027   // Store the return address to the appropriate stack slot.
3028   if (!FPDiff) return Chain;
3029   // Calculate the new stack slot for the return address.
3030   int NewReturnAddrFI =
3031     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3032                                          false);
3033   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3034   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3035                        MachinePointerInfo::getFixedStack(
3036                            DAG.getMachineFunction(), NewReturnAddrFI),
3037                        false, false, 0);
3038   return Chain;
3039 }
3040
3041 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3042 /// operation of specified width.
3043 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
3044                        SDValue V2) {
3045   unsigned NumElems = VT.getVectorNumElements();
3046   SmallVector<int, 8> Mask;
3047   Mask.push_back(NumElems);
3048   for (unsigned i = 1; i != NumElems; ++i)
3049     Mask.push_back(i);
3050   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3051 }
3052
3053 SDValue
3054 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3055                              SmallVectorImpl<SDValue> &InVals) const {
3056   SelectionDAG &DAG                     = CLI.DAG;
3057   SDLoc &dl                             = CLI.DL;
3058   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3059   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3060   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3061   SDValue Chain                         = CLI.Chain;
3062   SDValue Callee                        = CLI.Callee;
3063   CallingConv::ID CallConv              = CLI.CallConv;
3064   bool &isTailCall                      = CLI.IsTailCall;
3065   bool isVarArg                         = CLI.IsVarArg;
3066
3067   MachineFunction &MF = DAG.getMachineFunction();
3068   bool Is64Bit        = Subtarget->is64Bit();
3069   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
3070   StructReturnType SR = callIsStructReturn(Outs, Subtarget->isTargetMCU());
3071   bool IsSibcall      = false;
3072   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3073   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
3074
3075   if (CallConv == CallingConv::X86_INTR)
3076     report_fatal_error("X86 interrupts may not be called directly");
3077
3078   if (Attr.getValueAsString() == "true")
3079     isTailCall = false;
3080
3081   if (Subtarget->isPICStyleGOT() &&
3082       !MF.getTarget().Options.GuaranteedTailCallOpt) {
3083     // If we are using a GOT, disable tail calls to external symbols with
3084     // default visibility. Tail calling such a symbol requires using a GOT
3085     // relocation, which forces early binding of the symbol. This breaks code
3086     // that require lazy function symbol resolution. Using musttail or
3087     // GuaranteedTailCallOpt will override this.
3088     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3089     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3090                G->getGlobal()->hasDefaultVisibility()))
3091       isTailCall = false;
3092   }
3093
3094   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3095   if (IsMustTail) {
3096     // Force this to be a tail call.  The verifier rules are enough to ensure
3097     // that we can lower this successfully without moving the return address
3098     // around.
3099     isTailCall = true;
3100   } else if (isTailCall) {
3101     // Check if it's really possible to do a tail call.
3102     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3103                     isVarArg, SR != NotStructReturn,
3104                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3105                     Outs, OutVals, Ins, DAG);
3106
3107     // Sibcalls are automatically detected tailcalls which do not require
3108     // ABI changes.
3109     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3110       IsSibcall = true;
3111
3112     if (isTailCall)
3113       ++NumTailCalls;
3114   }
3115
3116   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3117          "Var args not supported with calling convention fastcc, ghc or hipe");
3118
3119   // Analyze operands of the call, assigning locations to each operand.
3120   SmallVector<CCValAssign, 16> ArgLocs;
3121   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3122
3123   // Allocate shadow area for Win64
3124   if (IsWin64)
3125     CCInfo.AllocateStack(32, 8);
3126
3127   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3128
3129   // Get a count of how many bytes are to be pushed on the stack.
3130   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3131   if (IsSibcall)
3132     // This is a sibcall. The memory operands are available in caller's
3133     // own caller's stack.
3134     NumBytes = 0;
3135   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3136            canGuaranteeTCO(CallConv))
3137     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3138
3139   int FPDiff = 0;
3140   if (isTailCall && !IsSibcall && !IsMustTail) {
3141     // Lower arguments at fp - stackoffset + fpdiff.
3142     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3143
3144     FPDiff = NumBytesCallerPushed - NumBytes;
3145
3146     // Set the delta of movement of the returnaddr stackslot.
3147     // But only set if delta is greater than previous delta.
3148     if (FPDiff < X86Info->getTCReturnAddrDelta())
3149       X86Info->setTCReturnAddrDelta(FPDiff);
3150   }
3151
3152   unsigned NumBytesToPush = NumBytes;
3153   unsigned NumBytesToPop = NumBytes;
3154
3155   // If we have an inalloca argument, all stack space has already been allocated
3156   // for us and be right at the top of the stack.  We don't support multiple
3157   // arguments passed in memory when using inalloca.
3158   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3159     NumBytesToPush = 0;
3160     if (!ArgLocs.back().isMemLoc())
3161       report_fatal_error("cannot use inalloca attribute on a register "
3162                          "parameter");
3163     if (ArgLocs.back().getLocMemOffset() != 0)
3164       report_fatal_error("any parameter with the inalloca attribute must be "
3165                          "the only memory argument");
3166   }
3167
3168   if (!IsSibcall)
3169     Chain = DAG.getCALLSEQ_START(
3170         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3171
3172   SDValue RetAddrFrIdx;
3173   // Load return address for tail calls.
3174   if (isTailCall && FPDiff)
3175     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3176                                     Is64Bit, FPDiff, dl);
3177
3178   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3179   SmallVector<SDValue, 8> MemOpChains;
3180   SDValue StackPtr;
3181
3182   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3183   // of tail call optimization arguments are handle later.
3184   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3185   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3186     // Skip inalloca arguments, they have already been written.
3187     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3188     if (Flags.isInAlloca())
3189       continue;
3190
3191     CCValAssign &VA = ArgLocs[i];
3192     EVT RegVT = VA.getLocVT();
3193     SDValue Arg = OutVals[i];
3194     bool isByVal = Flags.isByVal();
3195
3196     // Promote the value if needed.
3197     switch (VA.getLocInfo()) {
3198     default: llvm_unreachable("Unknown loc info!");
3199     case CCValAssign::Full: break;
3200     case CCValAssign::SExt:
3201       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3202       break;
3203     case CCValAssign::ZExt:
3204       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3205       break;
3206     case CCValAssign::AExt:
3207       if (Arg.getValueType().isVector() &&
3208           Arg.getValueType().getVectorElementType() == MVT::i1)
3209         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3210       else if (RegVT.is128BitVector()) {
3211         // Special case: passing MMX values in XMM registers.
3212         Arg = DAG.getBitcast(MVT::i64, Arg);
3213         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3214         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3215       } else
3216         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3217       break;
3218     case CCValAssign::BCvt:
3219       Arg = DAG.getBitcast(RegVT, Arg);
3220       break;
3221     case CCValAssign::Indirect: {
3222       // Store the argument.
3223       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3224       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3225       Chain = DAG.getStore(
3226           Chain, dl, Arg, SpillSlot,
3227           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3228           false, false, 0);
3229       Arg = SpillSlot;
3230       break;
3231     }
3232     }
3233
3234     if (VA.isRegLoc()) {
3235       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3236       if (isVarArg && IsWin64) {
3237         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3238         // shadow reg if callee is a varargs function.
3239         unsigned ShadowReg = 0;
3240         switch (VA.getLocReg()) {
3241         case X86::XMM0: ShadowReg = X86::RCX; break;
3242         case X86::XMM1: ShadowReg = X86::RDX; break;
3243         case X86::XMM2: ShadowReg = X86::R8; break;
3244         case X86::XMM3: ShadowReg = X86::R9; break;
3245         }
3246         if (ShadowReg)
3247           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3248       }
3249     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3250       assert(VA.isMemLoc());
3251       if (!StackPtr.getNode())
3252         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3253                                       getPointerTy(DAG.getDataLayout()));
3254       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3255                                              dl, DAG, VA, Flags));
3256     }
3257   }
3258
3259   if (!MemOpChains.empty())
3260     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3261
3262   if (Subtarget->isPICStyleGOT()) {
3263     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3264     // GOT pointer.
3265     if (!isTailCall) {
3266       RegsToPass.push_back(std::make_pair(
3267           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3268                                           getPointerTy(DAG.getDataLayout()))));
3269     } else {
3270       // If we are tail calling and generating PIC/GOT style code load the
3271       // address of the callee into ECX. The value in ecx is used as target of
3272       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3273       // for tail calls on PIC/GOT architectures. Normally we would just put the
3274       // address of GOT into ebx and then call target@PLT. But for tail calls
3275       // ebx would be restored (since ebx is callee saved) before jumping to the
3276       // target@PLT.
3277
3278       // Note: The actual moving to ECX is done further down.
3279       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3280       if (G && !G->getGlobal()->hasLocalLinkage() &&
3281           G->getGlobal()->hasDefaultVisibility())
3282         Callee = LowerGlobalAddress(Callee, DAG);
3283       else if (isa<ExternalSymbolSDNode>(Callee))
3284         Callee = LowerExternalSymbol(Callee, DAG);
3285     }
3286   }
3287
3288   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3289     // From AMD64 ABI document:
3290     // For calls that may call functions that use varargs or stdargs
3291     // (prototype-less calls or calls to functions containing ellipsis (...) in
3292     // the declaration) %al is used as hidden argument to specify the number
3293     // of SSE registers used. The contents of %al do not need to match exactly
3294     // the number of registers, but must be an ubound on the number of SSE
3295     // registers used and is in the range 0 - 8 inclusive.
3296
3297     // Count the number of XMM registers allocated.
3298     static const MCPhysReg XMMArgRegs[] = {
3299       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3300       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3301     };
3302     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3303     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3304            && "SSE registers cannot be used when SSE is disabled");
3305
3306     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3307                                         DAG.getConstant(NumXMMRegs, dl,
3308                                                         MVT::i8)));
3309   }
3310
3311   if (isVarArg && IsMustTail) {
3312     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3313     for (const auto &F : Forwards) {
3314       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3315       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3316     }
3317   }
3318
3319   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3320   // don't need this because the eligibility check rejects calls that require
3321   // shuffling arguments passed in memory.
3322   if (!IsSibcall && isTailCall) {
3323     // Force all the incoming stack arguments to be loaded from the stack
3324     // before any new outgoing arguments are stored to the stack, because the
3325     // outgoing stack slots may alias the incoming argument stack slots, and
3326     // the alias isn't otherwise explicit. This is slightly more conservative
3327     // than necessary, because it means that each store effectively depends
3328     // on every argument instead of just those arguments it would clobber.
3329     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3330
3331     SmallVector<SDValue, 8> MemOpChains2;
3332     SDValue FIN;
3333     int FI = 0;
3334     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3335       CCValAssign &VA = ArgLocs[i];
3336       if (VA.isRegLoc())
3337         continue;
3338       assert(VA.isMemLoc());
3339       SDValue Arg = OutVals[i];
3340       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3341       // Skip inalloca arguments.  They don't require any work.
3342       if (Flags.isInAlloca())
3343         continue;
3344       // Create frame index.
3345       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3346       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3347       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3348       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3349
3350       if (Flags.isByVal()) {
3351         // Copy relative to framepointer.
3352         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3353         if (!StackPtr.getNode())
3354           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3355                                         getPointerTy(DAG.getDataLayout()));
3356         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3357                              StackPtr, Source);
3358
3359         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3360                                                          ArgChain,
3361                                                          Flags, DAG, dl));
3362       } else {
3363         // Store relative to framepointer.
3364         MemOpChains2.push_back(DAG.getStore(
3365             ArgChain, dl, Arg, FIN,
3366             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3367             false, false, 0));
3368       }
3369     }
3370
3371     if (!MemOpChains2.empty())
3372       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3373
3374     // Store the return address to the appropriate stack slot.
3375     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3376                                      getPointerTy(DAG.getDataLayout()),
3377                                      RegInfo->getSlotSize(), FPDiff, dl);
3378   }
3379
3380   // Build a sequence of copy-to-reg nodes chained together with token chain
3381   // and flag operands which copy the outgoing args into registers.
3382   SDValue InFlag;
3383   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3384     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3385                              RegsToPass[i].second, InFlag);
3386     InFlag = Chain.getValue(1);
3387   }
3388
3389   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3390     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3391     // In the 64-bit large code model, we have to make all calls
3392     // through a register, since the call instruction's 32-bit
3393     // pc-relative offset may not be large enough to hold the whole
3394     // address.
3395   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3396     // If the callee is a GlobalAddress node (quite common, every direct call
3397     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3398     // it.
3399     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3400
3401     // We should use extra load for direct calls to dllimported functions in
3402     // non-JIT mode.
3403     const GlobalValue *GV = G->getGlobal();
3404     if (!GV->hasDLLImportStorageClass()) {
3405       unsigned char OpFlags = 0;
3406       bool ExtraLoad = false;
3407       unsigned WrapperKind = ISD::DELETED_NODE;
3408
3409       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3410       // external symbols most go through the PLT in PIC mode.  If the symbol
3411       // has hidden or protected visibility, or if it is static or local, then
3412       // we don't need to use the PLT - we can directly call it.
3413       if (Subtarget->isTargetELF() &&
3414           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3415           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3416         OpFlags = X86II::MO_PLT;
3417       } else if (Subtarget->isPICStyleStubAny() &&
3418                  !GV->isStrongDefinitionForLinker() &&
3419                  (!Subtarget->getTargetTriple().isMacOSX() ||
3420                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3421         // PC-relative references to external symbols should go through $stub,
3422         // unless we're building with the leopard linker or later, which
3423         // automatically synthesizes these stubs.
3424         OpFlags = X86II::MO_DARWIN_STUB;
3425       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3426                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3427         // If the function is marked as non-lazy, generate an indirect call
3428         // which loads from the GOT directly. This avoids runtime overhead
3429         // at the cost of eager binding (and one extra byte of encoding).
3430         OpFlags = X86II::MO_GOTPCREL;
3431         WrapperKind = X86ISD::WrapperRIP;
3432         ExtraLoad = true;
3433       }
3434
3435       Callee = DAG.getTargetGlobalAddress(
3436           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3437
3438       // Add a wrapper if needed.
3439       if (WrapperKind != ISD::DELETED_NODE)
3440         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3441                              getPointerTy(DAG.getDataLayout()), Callee);
3442       // Add extra indirection if needed.
3443       if (ExtraLoad)
3444         Callee = DAG.getLoad(
3445             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3446             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3447             false, 0);
3448     }
3449   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3450     unsigned char OpFlags = 0;
3451
3452     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3453     // external symbols should go through the PLT.
3454     if (Subtarget->isTargetELF() &&
3455         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3456       OpFlags = X86II::MO_PLT;
3457     } else if (Subtarget->isPICStyleStubAny() &&
3458                (!Subtarget->getTargetTriple().isMacOSX() ||
3459                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3460       // PC-relative references to external symbols should go through $stub,
3461       // unless we're building with the leopard linker or later, which
3462       // automatically synthesizes these stubs.
3463       OpFlags = X86II::MO_DARWIN_STUB;
3464     }
3465
3466     Callee = DAG.getTargetExternalSymbol(
3467         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3468   } else if (Subtarget->isTarget64BitILP32() &&
3469              Callee->getValueType(0) == MVT::i32) {
3470     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3471     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3472   }
3473
3474   // Returns a chain & a flag for retval copy to use.
3475   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3476   SmallVector<SDValue, 8> Ops;
3477
3478   if (!IsSibcall && isTailCall) {
3479     Chain = DAG.getCALLSEQ_END(Chain,
3480                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3481                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3482     InFlag = Chain.getValue(1);
3483   }
3484
3485   Ops.push_back(Chain);
3486   Ops.push_back(Callee);
3487
3488   if (isTailCall)
3489     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3490
3491   // Add argument registers to the end of the list so that they are known live
3492   // into the call.
3493   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3494     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3495                                   RegsToPass[i].second.getValueType()));
3496
3497   // Add a register mask operand representing the call-preserved registers.
3498   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3499   assert(Mask && "Missing call preserved mask for calling convention");
3500
3501   // If this is an invoke in a 32-bit function using a funclet-based
3502   // personality, assume the function clobbers all registers. If an exception
3503   // is thrown, the runtime will not restore CSRs.
3504   // FIXME: Model this more precisely so that we can register allocate across
3505   // the normal edge and spill and fill across the exceptional edge.
3506   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3507     const Function *CallerFn = MF.getFunction();
3508     EHPersonality Pers =
3509         CallerFn->hasPersonalityFn()
3510             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3511             : EHPersonality::Unknown;
3512     if (isFuncletEHPersonality(Pers))
3513       Mask = RegInfo->getNoPreservedMask();
3514   }
3515
3516   Ops.push_back(DAG.getRegisterMask(Mask));
3517
3518   if (InFlag.getNode())
3519     Ops.push_back(InFlag);
3520
3521   if (isTailCall) {
3522     // We used to do:
3523     //// If this is the first return lowered for this function, add the regs
3524     //// to the liveout set for the function.
3525     // This isn't right, although it's probably harmless on x86; liveouts
3526     // should be computed from returns not tail calls.  Consider a void
3527     // function making a tail call to a function returning int.
3528     MF.getFrameInfo()->setHasTailCall();
3529     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3530   }
3531
3532   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3533   InFlag = Chain.getValue(1);
3534
3535   // Create the CALLSEQ_END node.
3536   unsigned NumBytesForCalleeToPop;
3537   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3538                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3539     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3540   else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3541            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3542            SR == StackStructReturn)
3543     // If this is a call to a struct-return function, the callee
3544     // pops the hidden struct pointer, so we have to push it back.
3545     // This is common for Darwin/X86, Linux & Mingw32 targets.
3546     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3547     NumBytesForCalleeToPop = 4;
3548   else
3549     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3550
3551   // Returns a flag for retval copy to use.
3552   if (!IsSibcall) {
3553     Chain = DAG.getCALLSEQ_END(Chain,
3554                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3555                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3556                                                      true),
3557                                InFlag, dl);
3558     InFlag = Chain.getValue(1);
3559   }
3560
3561   // Handle result values, copying them out of physregs into vregs that we
3562   // return.
3563   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3564                          Ins, dl, DAG, InVals);
3565 }
3566
3567 //===----------------------------------------------------------------------===//
3568 //                Fast Calling Convention (tail call) implementation
3569 //===----------------------------------------------------------------------===//
3570
3571 //  Like std call, callee cleans arguments, convention except that ECX is
3572 //  reserved for storing the tail called function address. Only 2 registers are
3573 //  free for argument passing (inreg). Tail call optimization is performed
3574 //  provided:
3575 //                * tailcallopt is enabled
3576 //                * caller/callee are fastcc
3577 //  On X86_64 architecture with GOT-style position independent code only local
3578 //  (within module) calls are supported at the moment.
3579 //  To keep the stack aligned according to platform abi the function
3580 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3581 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3582 //  If a tail called function callee has more arguments than the caller the
3583 //  caller needs to make sure that there is room to move the RETADDR to. This is
3584 //  achieved by reserving an area the size of the argument delta right after the
3585 //  original RETADDR, but before the saved framepointer or the spilled registers
3586 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3587 //  stack layout:
3588 //    arg1
3589 //    arg2
3590 //    RETADDR
3591 //    [ new RETADDR
3592 //      move area ]
3593 //    (possible EBP)
3594 //    ESI
3595 //    EDI
3596 //    local1 ..
3597
3598 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3599 /// requirement.
3600 unsigned
3601 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3602                                                SelectionDAG& DAG) const {
3603   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3604   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3605   unsigned StackAlignment = TFI.getStackAlignment();
3606   uint64_t AlignMask = StackAlignment - 1;
3607   int64_t Offset = StackSize;
3608   unsigned SlotSize = RegInfo->getSlotSize();
3609   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3610     // Number smaller than 12 so just add the difference.
3611     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3612   } else {
3613     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3614     Offset = ((~AlignMask) & Offset) + StackAlignment +
3615       (StackAlignment-SlotSize);
3616   }
3617   return Offset;
3618 }
3619
3620 /// Return true if the given stack call argument is already available in the
3621 /// same position (relatively) of the caller's incoming argument stack.
3622 static
3623 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3624                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3625                          const X86InstrInfo *TII) {
3626   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3627   int FI = INT_MAX;
3628   if (Arg.getOpcode() == ISD::CopyFromReg) {
3629     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3630     if (!TargetRegisterInfo::isVirtualRegister(VR))
3631       return false;
3632     MachineInstr *Def = MRI->getVRegDef(VR);
3633     if (!Def)
3634       return false;
3635     if (!Flags.isByVal()) {
3636       if (!TII->isLoadFromStackSlot(Def, FI))
3637         return false;
3638     } else {
3639       unsigned Opcode = Def->getOpcode();
3640       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3641            Opcode == X86::LEA64_32r) &&
3642           Def->getOperand(1).isFI()) {
3643         FI = Def->getOperand(1).getIndex();
3644         Bytes = Flags.getByValSize();
3645       } else
3646         return false;
3647     }
3648   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3649     if (Flags.isByVal())
3650       // ByVal argument is passed in as a pointer but it's now being
3651       // dereferenced. e.g.
3652       // define @foo(%struct.X* %A) {
3653       //   tail call @bar(%struct.X* byval %A)
3654       // }
3655       return false;
3656     SDValue Ptr = Ld->getBasePtr();
3657     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3658     if (!FINode)
3659       return false;
3660     FI = FINode->getIndex();
3661   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3662     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3663     FI = FINode->getIndex();
3664     Bytes = Flags.getByValSize();
3665   } else
3666     return false;
3667
3668   assert(FI != INT_MAX);
3669   if (!MFI->isFixedObjectIndex(FI))
3670     return false;
3671   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3672 }
3673
3674 /// Check whether the call is eligible for tail call optimization. Targets
3675 /// that want to do tail call optimization should implement this function.
3676 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3677     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3678     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3679     const SmallVectorImpl<ISD::OutputArg> &Outs,
3680     const SmallVectorImpl<SDValue> &OutVals,
3681     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3682   if (!mayTailCallThisCC(CalleeCC))
3683     return false;
3684
3685   // If -tailcallopt is specified, make fastcc functions tail-callable.
3686   MachineFunction &MF = DAG.getMachineFunction();
3687   const Function *CallerF = MF.getFunction();
3688
3689   // If the function return type is x86_fp80 and the callee return type is not,
3690   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3691   // perform a tailcall optimization here.
3692   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3693     return false;
3694
3695   CallingConv::ID CallerCC = CallerF->getCallingConv();
3696   bool CCMatch = CallerCC == CalleeCC;
3697   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3698   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3699
3700   // Win64 functions have extra shadow space for argument homing. Don't do the
3701   // sibcall if the caller and callee have mismatched expectations for this
3702   // space.
3703   if (IsCalleeWin64 != IsCallerWin64)
3704     return false;
3705
3706   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3707     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3708       return true;
3709     return false;
3710   }
3711
3712   // Look for obvious safe cases to perform tail call optimization that do not
3713   // require ABI changes. This is what gcc calls sibcall.
3714
3715   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3716   // emit a special epilogue.
3717   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3718   if (RegInfo->needsStackRealignment(MF))
3719     return false;
3720
3721   // Also avoid sibcall optimization if either caller or callee uses struct
3722   // return semantics.
3723   if (isCalleeStructRet || isCallerStructRet)
3724     return false;
3725
3726   // Do not sibcall optimize vararg calls unless all arguments are passed via
3727   // registers.
3728   if (isVarArg && !Outs.empty()) {
3729     // Optimizing for varargs on Win64 is unlikely to be safe without
3730     // additional testing.
3731     if (IsCalleeWin64 || IsCallerWin64)
3732       return false;
3733
3734     SmallVector<CCValAssign, 16> ArgLocs;
3735     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3736                    *DAG.getContext());
3737
3738     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3739     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3740       if (!ArgLocs[i].isRegLoc())
3741         return false;
3742   }
3743
3744   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3745   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3746   // this into a sibcall.
3747   bool Unused = false;
3748   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3749     if (!Ins[i].Used) {
3750       Unused = true;
3751       break;
3752     }
3753   }
3754   if (Unused) {
3755     SmallVector<CCValAssign, 16> RVLocs;
3756     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3757                    *DAG.getContext());
3758     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3759     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3760       CCValAssign &VA = RVLocs[i];
3761       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3762         return false;
3763     }
3764   }
3765
3766   // If the calling conventions do not match, then we'd better make sure the
3767   // results are returned in the same way as what the caller expects.
3768   if (!CCMatch) {
3769     SmallVector<CCValAssign, 16> RVLocs1;
3770     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3771                     *DAG.getContext());
3772     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3773
3774     SmallVector<CCValAssign, 16> RVLocs2;
3775     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3776                     *DAG.getContext());
3777     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3778
3779     if (RVLocs1.size() != RVLocs2.size())
3780       return false;
3781     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3782       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3783         return false;
3784       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3785         return false;
3786       if (RVLocs1[i].isRegLoc()) {
3787         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3788           return false;
3789       } else {
3790         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3791           return false;
3792       }
3793     }
3794   }
3795
3796   unsigned StackArgsSize = 0;
3797
3798   // If the callee takes no arguments then go on to check the results of the
3799   // call.
3800   if (!Outs.empty()) {
3801     // Check if stack adjustment is needed. For now, do not do this if any
3802     // argument is passed on the stack.
3803     SmallVector<CCValAssign, 16> ArgLocs;
3804     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3805                    *DAG.getContext());
3806
3807     // Allocate shadow area for Win64
3808     if (IsCalleeWin64)
3809       CCInfo.AllocateStack(32, 8);
3810
3811     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3812     StackArgsSize = CCInfo.getNextStackOffset();
3813
3814     if (CCInfo.getNextStackOffset()) {
3815       // Check if the arguments are already laid out in the right way as
3816       // the caller's fixed stack objects.
3817       MachineFrameInfo *MFI = MF.getFrameInfo();
3818       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3819       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3820       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3821         CCValAssign &VA = ArgLocs[i];
3822         SDValue Arg = OutVals[i];
3823         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3824         if (VA.getLocInfo() == CCValAssign::Indirect)
3825           return false;
3826         if (!VA.isRegLoc()) {
3827           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3828                                    MFI, MRI, TII))
3829             return false;
3830         }
3831       }
3832     }
3833
3834     // If the tailcall address may be in a register, then make sure it's
3835     // possible to register allocate for it. In 32-bit, the call address can
3836     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3837     // callee-saved registers are restored. These happen to be the same
3838     // registers used to pass 'inreg' arguments so watch out for those.
3839     if (!Subtarget->is64Bit() &&
3840         ((!isa<GlobalAddressSDNode>(Callee) &&
3841           !isa<ExternalSymbolSDNode>(Callee)) ||
3842          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3843       unsigned NumInRegs = 0;
3844       // In PIC we need an extra register to formulate the address computation
3845       // for the callee.
3846       unsigned MaxInRegs =
3847         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3848
3849       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3850         CCValAssign &VA = ArgLocs[i];
3851         if (!VA.isRegLoc())
3852           continue;
3853         unsigned Reg = VA.getLocReg();
3854         switch (Reg) {
3855         default: break;
3856         case X86::EAX: case X86::EDX: case X86::ECX:
3857           if (++NumInRegs == MaxInRegs)
3858             return false;
3859           break;
3860         }
3861       }
3862     }
3863   }
3864
3865   bool CalleeWillPop =
3866       X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3867                        MF.getTarget().Options.GuaranteedTailCallOpt);
3868
3869   if (unsigned BytesToPop =
3870           MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3871     // If we have bytes to pop, the callee must pop them.
3872     bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3873     if (!CalleePopMatches)
3874       return false;
3875   } else if (CalleeWillPop && StackArgsSize > 0) {
3876     // If we don't have bytes to pop, make sure the callee doesn't pop any.
3877     return false;
3878   }
3879
3880   return true;
3881 }
3882
3883 FastISel *
3884 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3885                                   const TargetLibraryInfo *libInfo) const {
3886   return X86::createFastISel(funcInfo, libInfo);
3887 }
3888
3889 //===----------------------------------------------------------------------===//
3890 //                           Other Lowering Hooks
3891 //===----------------------------------------------------------------------===//
3892
3893 static bool MayFoldLoad(SDValue Op) {
3894   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3895 }
3896
3897 static bool MayFoldIntoStore(SDValue Op) {
3898   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3899 }
3900
3901 static bool isTargetShuffle(unsigned Opcode) {
3902   switch(Opcode) {
3903   default: return false;
3904   case X86ISD::BLENDI:
3905   case X86ISD::PSHUFB:
3906   case X86ISD::PSHUFD:
3907   case X86ISD::PSHUFHW:
3908   case X86ISD::PSHUFLW:
3909   case X86ISD::SHUFP:
3910   case X86ISD::PALIGNR:
3911   case X86ISD::MOVLHPS:
3912   case X86ISD::MOVLHPD:
3913   case X86ISD::MOVHLPS:
3914   case X86ISD::MOVLPS:
3915   case X86ISD::MOVLPD:
3916   case X86ISD::MOVSHDUP:
3917   case X86ISD::MOVSLDUP:
3918   case X86ISD::MOVDDUP:
3919   case X86ISD::MOVSS:
3920   case X86ISD::MOVSD:
3921   case X86ISD::UNPCKL:
3922   case X86ISD::UNPCKH:
3923   case X86ISD::VPERMILPI:
3924   case X86ISD::VPERM2X128:
3925   case X86ISD::VPERMI:
3926   case X86ISD::VPERMV:
3927   case X86ISD::VPERMV3:
3928     return true;
3929   }
3930 }
3931
3932 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3933                                     SDValue V1, unsigned TargetMask,
3934                                     SelectionDAG &DAG) {
3935   switch(Opc) {
3936   default: llvm_unreachable("Unknown x86 shuffle node");
3937   case X86ISD::PSHUFD:
3938   case X86ISD::PSHUFHW:
3939   case X86ISD::PSHUFLW:
3940   case X86ISD::VPERMILPI:
3941   case X86ISD::VPERMI:
3942     return DAG.getNode(Opc, dl, VT, V1,
3943                        DAG.getConstant(TargetMask, dl, MVT::i8));
3944   }
3945 }
3946
3947 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3948                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3949   switch(Opc) {
3950   default: llvm_unreachable("Unknown x86 shuffle node");
3951   case X86ISD::MOVLHPS:
3952   case X86ISD::MOVLHPD:
3953   case X86ISD::MOVHLPS:
3954   case X86ISD::MOVLPS:
3955   case X86ISD::MOVLPD:
3956   case X86ISD::MOVSS:
3957   case X86ISD::MOVSD:
3958   case X86ISD::UNPCKL:
3959   case X86ISD::UNPCKH:
3960     return DAG.getNode(Opc, dl, VT, V1, V2);
3961   }
3962 }
3963
3964 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3965   MachineFunction &MF = DAG.getMachineFunction();
3966   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3967   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3968   int ReturnAddrIndex = FuncInfo->getRAIndex();
3969
3970   if (ReturnAddrIndex == 0) {
3971     // Set up a frame object for the return address.
3972     unsigned SlotSize = RegInfo->getSlotSize();
3973     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3974                                                            -(int64_t)SlotSize,
3975                                                            false);
3976     FuncInfo->setRAIndex(ReturnAddrIndex);
3977   }
3978
3979   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3980 }
3981
3982 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3983                                        bool hasSymbolicDisplacement) {
3984   // Offset should fit into 32 bit immediate field.
3985   if (!isInt<32>(Offset))
3986     return false;
3987
3988   // If we don't have a symbolic displacement - we don't have any extra
3989   // restrictions.
3990   if (!hasSymbolicDisplacement)
3991     return true;
3992
3993   // FIXME: Some tweaks might be needed for medium code model.
3994   if (M != CodeModel::Small && M != CodeModel::Kernel)
3995     return false;
3996
3997   // For small code model we assume that latest object is 16MB before end of 31
3998   // bits boundary. We may also accept pretty large negative constants knowing
3999   // that all objects are in the positive half of address space.
4000   if (M == CodeModel::Small && Offset < 16*1024*1024)
4001     return true;
4002
4003   // For kernel code model we know that all object resist in the negative half
4004   // of 32bits address space. We may not accept negative offsets, since they may
4005   // be just off and we may accept pretty large positive ones.
4006   if (M == CodeModel::Kernel && Offset >= 0)
4007     return true;
4008
4009   return false;
4010 }
4011
4012 /// Determines whether the callee is required to pop its own arguments.
4013 /// Callee pop is necessary to support tail calls.
4014 bool X86::isCalleePop(CallingConv::ID CallingConv,
4015                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4016   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4017   // can guarantee TCO.
4018   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4019     return true;
4020
4021   switch (CallingConv) {
4022   default:
4023     return false;
4024   case CallingConv::X86_StdCall:
4025   case CallingConv::X86_FastCall:
4026   case CallingConv::X86_ThisCall:
4027   case CallingConv::X86_VectorCall:
4028     return !is64Bit;
4029   }
4030 }
4031
4032 /// \brief Return true if the condition is an unsigned comparison operation.
4033 static bool isX86CCUnsigned(unsigned X86CC) {
4034   switch (X86CC) {
4035   default: llvm_unreachable("Invalid integer condition!");
4036   case X86::COND_E:     return true;
4037   case X86::COND_G:     return false;
4038   case X86::COND_GE:    return false;
4039   case X86::COND_L:     return false;
4040   case X86::COND_LE:    return false;
4041   case X86::COND_NE:    return true;
4042   case X86::COND_B:     return true;
4043   case X86::COND_A:     return true;
4044   case X86::COND_BE:    return true;
4045   case X86::COND_AE:    return true;
4046   }
4047 }
4048
4049 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
4050   switch (SetCCOpcode) {
4051   default: llvm_unreachable("Invalid integer condition!");
4052   case ISD::SETEQ:  return X86::COND_E;
4053   case ISD::SETGT:  return X86::COND_G;
4054   case ISD::SETGE:  return X86::COND_GE;
4055   case ISD::SETLT:  return X86::COND_L;
4056   case ISD::SETLE:  return X86::COND_LE;
4057   case ISD::SETNE:  return X86::COND_NE;
4058   case ISD::SETULT: return X86::COND_B;
4059   case ISD::SETUGT: return X86::COND_A;
4060   case ISD::SETULE: return X86::COND_BE;
4061   case ISD::SETUGE: return X86::COND_AE;
4062   }
4063 }
4064
4065 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4066 /// condition code, returning the condition code and the LHS/RHS of the
4067 /// comparison to make.
4068 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
4069                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
4070   if (!isFP) {
4071     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4072       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4073         // X > -1   -> X == 0, jump !sign.
4074         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4075         return X86::COND_NS;
4076       }
4077       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4078         // X < 0   -> X == 0, jump on sign.
4079         return X86::COND_S;
4080       }
4081       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
4082         // X < 1   -> X <= 0
4083         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4084         return X86::COND_LE;
4085       }
4086     }
4087
4088     return TranslateIntegerX86CC(SetCCOpcode);
4089   }
4090
4091   // First determine if it is required or is profitable to flip the operands.
4092
4093   // If LHS is a foldable load, but RHS is not, flip the condition.
4094   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4095       !ISD::isNON_EXTLoad(RHS.getNode())) {
4096     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4097     std::swap(LHS, RHS);
4098   }
4099
4100   switch (SetCCOpcode) {
4101   default: break;
4102   case ISD::SETOLT:
4103   case ISD::SETOLE:
4104   case ISD::SETUGT:
4105   case ISD::SETUGE:
4106     std::swap(LHS, RHS);
4107     break;
4108   }
4109
4110   // On a floating point condition, the flags are set as follows:
4111   // ZF  PF  CF   op
4112   //  0 | 0 | 0 | X > Y
4113   //  0 | 0 | 1 | X < Y
4114   //  1 | 0 | 0 | X == Y
4115   //  1 | 1 | 1 | unordered
4116   switch (SetCCOpcode) {
4117   default: llvm_unreachable("Condcode should be pre-legalized away");
4118   case ISD::SETUEQ:
4119   case ISD::SETEQ:   return X86::COND_E;
4120   case ISD::SETOLT:              // flipped
4121   case ISD::SETOGT:
4122   case ISD::SETGT:   return X86::COND_A;
4123   case ISD::SETOLE:              // flipped
4124   case ISD::SETOGE:
4125   case ISD::SETGE:   return X86::COND_AE;
4126   case ISD::SETUGT:              // flipped
4127   case ISD::SETULT:
4128   case ISD::SETLT:   return X86::COND_B;
4129   case ISD::SETUGE:              // flipped
4130   case ISD::SETULE:
4131   case ISD::SETLE:   return X86::COND_BE;
4132   case ISD::SETONE:
4133   case ISD::SETNE:   return X86::COND_NE;
4134   case ISD::SETUO:   return X86::COND_P;
4135   case ISD::SETO:    return X86::COND_NP;
4136   case ISD::SETOEQ:
4137   case ISD::SETUNE:  return X86::COND_INVALID;
4138   }
4139 }
4140
4141 /// Is there a floating point cmov for the specific X86 condition code?
4142 /// Current x86 isa includes the following FP cmov instructions:
4143 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4144 static bool hasFPCMov(unsigned X86CC) {
4145   switch (X86CC) {
4146   default:
4147     return false;
4148   case X86::COND_B:
4149   case X86::COND_BE:
4150   case X86::COND_E:
4151   case X86::COND_P:
4152   case X86::COND_A:
4153   case X86::COND_AE:
4154   case X86::COND_NE:
4155   case X86::COND_NP:
4156     return true;
4157   }
4158 }
4159
4160 /// Returns true if the target can instruction select the
4161 /// specified FP immediate natively. If false, the legalizer will
4162 /// materialize the FP immediate as a load from a constant pool.
4163 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4164   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4165     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4166       return true;
4167   }
4168   return false;
4169 }
4170
4171 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4172                                               ISD::LoadExtType ExtTy,
4173                                               EVT NewVT) const {
4174   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4175   // relocation target a movq or addq instruction: don't let the load shrink.
4176   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4177   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4178     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4179       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4180   return true;
4181 }
4182
4183 /// \brief Returns true if it is beneficial to convert a load of a constant
4184 /// to just the constant itself.
4185 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4186                                                           Type *Ty) const {
4187   assert(Ty->isIntegerTy());
4188
4189   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4190   if (BitSize == 0 || BitSize > 64)
4191     return false;
4192   return true;
4193 }
4194
4195 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4196                                                 unsigned Index) const {
4197   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4198     return false;
4199
4200   return (Index == 0 || Index == ResVT.getVectorNumElements());
4201 }
4202
4203 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4204   // Speculate cttz only if we can directly use TZCNT.
4205   return Subtarget->hasBMI();
4206 }
4207
4208 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4209   // Speculate ctlz only if we can directly use LZCNT.
4210   return Subtarget->hasLZCNT();
4211 }
4212
4213 /// Return true if every element in Mask, beginning
4214 /// from position Pos and ending in Pos+Size is undef.
4215 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4216   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4217     if (0 <= Mask[i])
4218       return false;
4219   return true;
4220 }
4221
4222 /// Return true if Val is undef or if its value falls within the
4223 /// specified range (L, H].
4224 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4225   return (Val < 0) || (Val >= Low && Val < Hi);
4226 }
4227
4228 /// Val is either less than zero (undef) or equal to the specified value.
4229 static bool isUndefOrEqual(int Val, int CmpVal) {
4230   return (Val < 0 || Val == CmpVal);
4231 }
4232
4233 /// Return true if every element in Mask, beginning
4234 /// from position Pos and ending in Pos+Size, falls within the specified
4235 /// sequential range (Low, Low+Size]. or is undef.
4236 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4237                                        unsigned Pos, unsigned Size, int Low) {
4238   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4239     if (!isUndefOrEqual(Mask[i], Low))
4240       return false;
4241   return true;
4242 }
4243
4244 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4245 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4246 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4247   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4248   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4249     return false;
4250
4251   // The index should be aligned on a vecWidth-bit boundary.
4252   uint64_t Index =
4253     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4254
4255   MVT VT = N->getSimpleValueType(0);
4256   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4257   bool Result = (Index * ElSize) % vecWidth == 0;
4258
4259   return Result;
4260 }
4261
4262 /// Return true if the specified INSERT_SUBVECTOR
4263 /// operand specifies a subvector insert that is suitable for input to
4264 /// insertion of 128 or 256-bit subvectors
4265 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4266   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4267   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4268     return false;
4269   // The index should be aligned on a vecWidth-bit boundary.
4270   uint64_t Index =
4271     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4272
4273   MVT VT = N->getSimpleValueType(0);
4274   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4275   bool Result = (Index * ElSize) % vecWidth == 0;
4276
4277   return Result;
4278 }
4279
4280 bool X86::isVINSERT128Index(SDNode *N) {
4281   return isVINSERTIndex(N, 128);
4282 }
4283
4284 bool X86::isVINSERT256Index(SDNode *N) {
4285   return isVINSERTIndex(N, 256);
4286 }
4287
4288 bool X86::isVEXTRACT128Index(SDNode *N) {
4289   return isVEXTRACTIndex(N, 128);
4290 }
4291
4292 bool X86::isVEXTRACT256Index(SDNode *N) {
4293   return isVEXTRACTIndex(N, 256);
4294 }
4295
4296 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4297   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4298   assert(isa<ConstantSDNode>(N->getOperand(1).getNode()) &&
4299          "Illegal extract subvector for VEXTRACT");
4300
4301   uint64_t Index =
4302     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4303
4304   MVT VecVT = N->getOperand(0).getSimpleValueType();
4305   MVT ElVT = VecVT.getVectorElementType();
4306
4307   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4308   return Index / NumElemsPerChunk;
4309 }
4310
4311 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4312   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4313   assert(isa<ConstantSDNode>(N->getOperand(2).getNode()) &&
4314          "Illegal insert subvector for VINSERT");
4315
4316   uint64_t Index =
4317     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4318
4319   MVT VecVT = N->getSimpleValueType(0);
4320   MVT ElVT = VecVT.getVectorElementType();
4321
4322   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4323   return Index / NumElemsPerChunk;
4324 }
4325
4326 /// Return the appropriate immediate to extract the specified
4327 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4328 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4329   return getExtractVEXTRACTImmediate(N, 128);
4330 }
4331
4332 /// Return the appropriate immediate to extract the specified
4333 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4334 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4335   return getExtractVEXTRACTImmediate(N, 256);
4336 }
4337
4338 /// Return the appropriate immediate to insert at the specified
4339 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4340 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4341   return getInsertVINSERTImmediate(N, 128);
4342 }
4343
4344 /// Return the appropriate immediate to insert at the specified
4345 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4346 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4347   return getInsertVINSERTImmediate(N, 256);
4348 }
4349
4350 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4351 bool X86::isZeroNode(SDValue Elt) {
4352   return isNullConstant(Elt) || isNullFPConstant(Elt);
4353 }
4354
4355 // Build a vector of constants
4356 // Use an UNDEF node if MaskElt == -1.
4357 // Spilt 64-bit constants in the 32-bit mode.
4358 static SDValue getConstVector(ArrayRef<int> Values, MVT VT,
4359                               SelectionDAG &DAG,
4360                               SDLoc dl, bool IsMask = false) {
4361
4362   SmallVector<SDValue, 32>  Ops;
4363   bool Split = false;
4364
4365   MVT ConstVecVT = VT;
4366   unsigned NumElts = VT.getVectorNumElements();
4367   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4368   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4369     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4370     Split = true;
4371   }
4372
4373   MVT EltVT = ConstVecVT.getVectorElementType();
4374   for (unsigned i = 0; i < NumElts; ++i) {
4375     bool IsUndef = Values[i] < 0 && IsMask;
4376     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4377       DAG.getConstant(Values[i], dl, EltVT);
4378     Ops.push_back(OpNode);
4379     if (Split)
4380       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4381                     DAG.getConstant(0, dl, EltVT));
4382   }
4383   SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4384   if (Split)
4385     ConstsNode = DAG.getBitcast(VT, ConstsNode);
4386   return ConstsNode;
4387 }
4388
4389 /// Returns a vector of specified type with all zero elements.
4390 static SDValue getZeroVector(MVT VT, const X86Subtarget *Subtarget,
4391                              SelectionDAG &DAG, SDLoc dl) {
4392   assert(VT.isVector() && "Expected a vector type");
4393
4394   // Always build SSE zero vectors as <4 x i32> bitcasted
4395   // to their dest type. This ensures they get CSE'd.
4396   SDValue Vec;
4397   if (VT.is128BitVector()) {  // SSE
4398     if (Subtarget->hasSSE2()) {  // SSE2
4399       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4400       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4401     } else { // SSE1
4402       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4403       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4404     }
4405   } else if (VT.is256BitVector()) { // AVX
4406     if (Subtarget->hasInt256()) { // AVX2
4407       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4408       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4409       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4410     } else {
4411       // 256-bit logic and arithmetic instructions in AVX are all
4412       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4413       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4414       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4415       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4416     }
4417   } else if (VT.is512BitVector()) { // AVX-512
4418       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4419       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4420                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4421       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4422   } else if (VT.getVectorElementType() == MVT::i1) {
4423
4424     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4425             && "Unexpected vector type");
4426     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4427             && "Unexpected vector type");
4428     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4429     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4430     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4431   } else
4432     llvm_unreachable("Unexpected vector type");
4433
4434   return DAG.getBitcast(VT, Vec);
4435 }
4436
4437 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4438                                 SelectionDAG &DAG, SDLoc dl,
4439                                 unsigned vectorWidth) {
4440   assert((vectorWidth == 128 || vectorWidth == 256) &&
4441          "Unsupported vector width");
4442   EVT VT = Vec.getValueType();
4443   EVT ElVT = VT.getVectorElementType();
4444   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4445   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4446                                   VT.getVectorNumElements()/Factor);
4447
4448   // Extract from UNDEF is UNDEF.
4449   if (Vec.getOpcode() == ISD::UNDEF)
4450     return DAG.getUNDEF(ResultVT);
4451
4452   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4453   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4454   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4455
4456   // This is the index of the first element of the vectorWidth-bit chunk
4457   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4458   IdxVal &= ~(ElemsPerChunk - 1);
4459
4460   // If the input is a buildvector just emit a smaller one.
4461   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4462     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4463                        makeArrayRef(Vec->op_begin() + IdxVal, ElemsPerChunk));
4464
4465   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4466   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4467 }
4468
4469 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4470 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4471 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4472 /// instructions or a simple subregister reference. Idx is an index in the
4473 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4474 /// lowering EXTRACT_VECTOR_ELT operations easier.
4475 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4476                                    SelectionDAG &DAG, SDLoc dl) {
4477   assert((Vec.getValueType().is256BitVector() ||
4478           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4479   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4480 }
4481
4482 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4483 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4484                                    SelectionDAG &DAG, SDLoc dl) {
4485   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4486   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4487 }
4488
4489 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4490                                unsigned IdxVal, SelectionDAG &DAG,
4491                                SDLoc dl, unsigned vectorWidth) {
4492   assert((vectorWidth == 128 || vectorWidth == 256) &&
4493          "Unsupported vector width");
4494   // Inserting UNDEF is Result
4495   if (Vec.getOpcode() == ISD::UNDEF)
4496     return Result;
4497   EVT VT = Vec.getValueType();
4498   EVT ElVT = VT.getVectorElementType();
4499   EVT ResultVT = Result.getValueType();
4500
4501   // Insert the relevant vectorWidth bits.
4502   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4503   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4504
4505   // This is the index of the first element of the vectorWidth-bit chunk
4506   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4507   IdxVal &= ~(ElemsPerChunk - 1);
4508
4509   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4510   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4511 }
4512
4513 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4514 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4515 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4516 /// simple superregister reference.  Idx is an index in the 128 bits
4517 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4518 /// lowering INSERT_VECTOR_ELT operations easier.
4519 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4520                                   SelectionDAG &DAG, SDLoc dl) {
4521   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4522
4523   // For insertion into the zero index (low half) of a 256-bit vector, it is
4524   // more efficient to generate a blend with immediate instead of an insert*128.
4525   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4526   // extend the subvector to the size of the result vector. Make sure that
4527   // we are not recursing on that node by checking for undef here.
4528   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4529       Result.getOpcode() != ISD::UNDEF) {
4530     EVT ResultVT = Result.getValueType();
4531     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4532     SDValue Undef = DAG.getUNDEF(ResultVT);
4533     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4534                                  Vec, ZeroIndex);
4535
4536     // The blend instruction, and therefore its mask, depend on the data type.
4537     MVT ScalarType = ResultVT.getVectorElementType().getSimpleVT();
4538     if (ScalarType.isFloatingPoint()) {
4539       // Choose either vblendps (float) or vblendpd (double).
4540       unsigned ScalarSize = ScalarType.getSizeInBits();
4541       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4542       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4543       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4544       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4545     }
4546
4547     const X86Subtarget &Subtarget =
4548     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4549
4550     // AVX2 is needed for 256-bit integer blend support.
4551     // Integers must be cast to 32-bit because there is only vpblendd;
4552     // vpblendw can't be used for this because it has a handicapped mask.
4553
4554     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4555     // is still more efficient than using the wrong domain vinsertf128 that
4556     // will be created by InsertSubVector().
4557     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4558
4559     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4560     Result = DAG.getBitcast(CastVT, Result);
4561     Vec256 = DAG.getBitcast(CastVT, Vec256);
4562     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4563     return DAG.getBitcast(ResultVT, Vec256);
4564   }
4565
4566   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4567 }
4568
4569 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4570                                   SelectionDAG &DAG, SDLoc dl) {
4571   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4572   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4573 }
4574
4575 /// Insert i1-subvector to i1-vector.
4576 static SDValue Insert1BitVector(SDValue Op, SelectionDAG &DAG) {
4577
4578   SDLoc dl(Op);
4579   SDValue Vec = Op.getOperand(0);
4580   SDValue SubVec = Op.getOperand(1);
4581   SDValue Idx = Op.getOperand(2);
4582
4583   if (!isa<ConstantSDNode>(Idx))
4584     return SDValue();
4585
4586   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4587   if (IdxVal == 0  && Vec.isUndef()) // the operation is legal
4588     return Op;
4589
4590   MVT OpVT = Op.getSimpleValueType();
4591   MVT SubVecVT = SubVec.getSimpleValueType();
4592   unsigned NumElems = OpVT.getVectorNumElements();
4593   unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4594
4595   assert(IdxVal + SubVecNumElems <= NumElems &&
4596          IdxVal % SubVecVT.getSizeInBits() == 0 &&
4597          "Unexpected index value in INSERT_SUBVECTOR");
4598
4599   // There are 3 possible cases:
4600   // 1. Subvector should be inserted in the lower part (IdxVal == 0)
4601   // 2. Subvector should be inserted in the upper part
4602   //    (IdxVal + SubVecNumElems == NumElems)
4603   // 3. Subvector should be inserted in the middle (for example v2i1
4604   //    to v16i1, index 2)
4605
4606   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
4607   SDValue Undef = DAG.getUNDEF(OpVT);
4608   SDValue WideSubVec =
4609     DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef, SubVec, ZeroIdx);
4610   if (Vec.isUndef())
4611     return DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4612       DAG.getConstant(IdxVal, dl, MVT::i8));
4613
4614   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
4615     unsigned ShiftLeft = NumElems - SubVecNumElems;
4616     unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4617     WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4618       DAG.getConstant(ShiftLeft, dl, MVT::i8));
4619     return ShiftRight ? DAG.getNode(X86ISD::VSRLI, dl, OpVT, WideSubVec,
4620       DAG.getConstant(ShiftRight, dl, MVT::i8)) : WideSubVec;
4621   }
4622
4623   if (IdxVal == 0) {
4624     // Zero lower bits of the Vec
4625     SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4626     Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4627     Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4628     // Merge them together
4629     return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4630   }
4631
4632   // Simple case when we put subvector in the upper part
4633   if (IdxVal + SubVecNumElems == NumElems) {
4634     // Zero upper bits of the Vec
4635     WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec,
4636                         DAG.getConstant(IdxVal, dl, MVT::i8));
4637     SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4638     Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4639     Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4640     return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4641   }
4642   // Subvector should be inserted in the middle - use shuffle
4643   SmallVector<int, 64> Mask;
4644   for (unsigned i = 0; i < NumElems; ++i)
4645     Mask.push_back(i >= IdxVal && i < IdxVal + SubVecNumElems ?
4646                     i : i + NumElems);
4647   return DAG.getVectorShuffle(OpVT, dl, WideSubVec, Vec, Mask);
4648 }
4649
4650 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4651 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4652 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4653 /// large BUILD_VECTORS.
4654 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4655                                    unsigned NumElems, SelectionDAG &DAG,
4656                                    SDLoc dl) {
4657   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4658   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4659 }
4660
4661 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4662                                    unsigned NumElems, SelectionDAG &DAG,
4663                                    SDLoc dl) {
4664   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4665   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4666 }
4667
4668 /// Returns a vector of specified type with all bits set.
4669 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4670 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4671 /// Then bitcast to their original type, ensuring they get CSE'd.
4672 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4673                              SelectionDAG &DAG, SDLoc dl) {
4674   assert(VT.isVector() && "Expected a vector type");
4675
4676   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4677   SDValue Vec;
4678   if (VT.is512BitVector()) {
4679     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4680                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4681     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4682   } else if (VT.is256BitVector()) {
4683     if (Subtarget->hasInt256()) { // AVX2
4684       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4685       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4686     } else { // AVX
4687       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4688       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4689     }
4690   } else if (VT.is128BitVector()) {
4691     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4692   } else
4693     llvm_unreachable("Unexpected vector type");
4694
4695   return DAG.getBitcast(VT, Vec);
4696 }
4697
4698 /// Returns a vector_shuffle node for an unpackl operation.
4699 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4700                           SDValue V2) {
4701   unsigned NumElems = VT.getVectorNumElements();
4702   SmallVector<int, 8> Mask;
4703   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4704     Mask.push_back(i);
4705     Mask.push_back(i + NumElems);
4706   }
4707   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4708 }
4709
4710 /// Returns a vector_shuffle node for an unpackh operation.
4711 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4712                           SDValue V2) {
4713   unsigned NumElems = VT.getVectorNumElements();
4714   SmallVector<int, 8> Mask;
4715   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4716     Mask.push_back(i + Half);
4717     Mask.push_back(i + NumElems + Half);
4718   }
4719   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4720 }
4721
4722 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4723 /// This produces a shuffle where the low element of V2 is swizzled into the
4724 /// zero/undef vector, landing at element Idx.
4725 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4726 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4727                                            bool IsZero,
4728                                            const X86Subtarget *Subtarget,
4729                                            SelectionDAG &DAG) {
4730   MVT VT = V2.getSimpleValueType();
4731   SDValue V1 = IsZero
4732     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4733   unsigned NumElems = VT.getVectorNumElements();
4734   SmallVector<int, 16> MaskVec;
4735   for (unsigned i = 0; i != NumElems; ++i)
4736     // If this is the insertion idx, put the low elt of V2 here.
4737     MaskVec.push_back(i == Idx ? NumElems : i);
4738   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4739 }
4740
4741 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4742 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4743 /// uses one source. Note that this will set IsUnary for shuffles which use a
4744 /// single input multiple times, and in those cases it will
4745 /// adjust the mask to only have indices within that single input.
4746 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4747 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4748                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4749   unsigned NumElems = VT.getVectorNumElements();
4750   SDValue ImmN;
4751
4752   IsUnary = false;
4753   bool IsFakeUnary = false;
4754   switch(N->getOpcode()) {
4755   case X86ISD::BLENDI:
4756     ImmN = N->getOperand(N->getNumOperands()-1);
4757     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4758     break;
4759   case X86ISD::SHUFP:
4760     ImmN = N->getOperand(N->getNumOperands()-1);
4761     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4762     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4763     break;
4764   case X86ISD::UNPCKH:
4765     DecodeUNPCKHMask(VT, Mask);
4766     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4767     break;
4768   case X86ISD::UNPCKL:
4769     DecodeUNPCKLMask(VT, Mask);
4770     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4771     break;
4772   case X86ISD::MOVHLPS:
4773     DecodeMOVHLPSMask(NumElems, Mask);
4774     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4775     break;
4776   case X86ISD::MOVLHPS:
4777     DecodeMOVLHPSMask(NumElems, Mask);
4778     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4779     break;
4780   case X86ISD::PALIGNR:
4781     ImmN = N->getOperand(N->getNumOperands()-1);
4782     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4783     break;
4784   case X86ISD::PSHUFD:
4785   case X86ISD::VPERMILPI:
4786     ImmN = N->getOperand(N->getNumOperands()-1);
4787     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4788     IsUnary = true;
4789     break;
4790   case X86ISD::PSHUFHW:
4791     ImmN = N->getOperand(N->getNumOperands()-1);
4792     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4793     IsUnary = true;
4794     break;
4795   case X86ISD::PSHUFLW:
4796     ImmN = N->getOperand(N->getNumOperands()-1);
4797     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4798     IsUnary = true;
4799     break;
4800   case X86ISD::PSHUFB: {
4801     IsUnary = true;
4802     SDValue MaskNode = N->getOperand(1);
4803     while (MaskNode->getOpcode() == ISD::BITCAST)
4804       MaskNode = MaskNode->getOperand(0);
4805
4806     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4807       // If we have a build-vector, then things are easy.
4808       MVT VT = MaskNode.getSimpleValueType();
4809       assert(VT.isVector() &&
4810              "Can't produce a non-vector with a build_vector!");
4811       if (!VT.isInteger())
4812         return false;
4813
4814       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4815
4816       SmallVector<uint64_t, 32> RawMask;
4817       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4818         SDValue Op = MaskNode->getOperand(i);
4819         if (Op->getOpcode() == ISD::UNDEF) {
4820           RawMask.push_back((uint64_t)SM_SentinelUndef);
4821           continue;
4822         }
4823         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4824         if (!CN)
4825           return false;
4826         APInt MaskElement = CN->getAPIntValue();
4827
4828         // We now have to decode the element which could be any integer size and
4829         // extract each byte of it.
4830         for (int j = 0; j < NumBytesPerElement; ++j) {
4831           // Note that this is x86 and so always little endian: the low byte is
4832           // the first byte of the mask.
4833           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4834           MaskElement = MaskElement.lshr(8);
4835         }
4836       }
4837       DecodePSHUFBMask(RawMask, Mask);
4838       break;
4839     }
4840
4841     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4842     if (!MaskLoad)
4843       return false;
4844
4845     SDValue Ptr = MaskLoad->getBasePtr();
4846     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4847         Ptr->getOpcode() == X86ISD::WrapperRIP)
4848       Ptr = Ptr->getOperand(0);
4849
4850     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4851     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4852       return false;
4853
4854     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4855       DecodePSHUFBMask(C, Mask);
4856       break;
4857     }
4858
4859     return false;
4860   }
4861   case X86ISD::VPERMI:
4862     ImmN = N->getOperand(N->getNumOperands()-1);
4863     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4864     IsUnary = true;
4865     break;
4866   case X86ISD::MOVSS:
4867   case X86ISD::MOVSD:
4868     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4869     break;
4870   case X86ISD::VPERM2X128:
4871     ImmN = N->getOperand(N->getNumOperands()-1);
4872     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4873     // Mask only contains negative index if an element is zero.
4874     if (std::any_of(Mask.begin(), Mask.end(),
4875                     [](int M){ return M == SM_SentinelZero; }))
4876       return false;
4877     break;
4878   case X86ISD::MOVSLDUP:
4879     DecodeMOVSLDUPMask(VT, Mask);
4880     IsUnary = true;
4881     break;
4882   case X86ISD::MOVSHDUP:
4883     DecodeMOVSHDUPMask(VT, Mask);
4884     IsUnary = true;
4885     break;
4886   case X86ISD::MOVDDUP:
4887     DecodeMOVDDUPMask(VT, Mask);
4888     IsUnary = true;
4889     break;
4890   case X86ISD::MOVLHPD:
4891   case X86ISD::MOVLPD:
4892   case X86ISD::MOVLPS:
4893     // Not yet implemented
4894     return false;
4895   case X86ISD::VPERMV: {
4896     IsUnary = true;
4897     SDValue MaskNode = N->getOperand(0);
4898     while (MaskNode->getOpcode() == ISD::BITCAST)
4899       MaskNode = MaskNode->getOperand(0);
4900
4901     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4902     SmallVector<uint64_t, 32> RawMask;
4903     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4904       // If we have a build-vector, then things are easy.
4905       assert(MaskNode.getSimpleValueType().isInteger() &&
4906              MaskNode.getSimpleValueType().getVectorNumElements() ==
4907              VT.getVectorNumElements());
4908
4909       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4910         SDValue Op = MaskNode->getOperand(i);
4911         if (Op->getOpcode() == ISD::UNDEF)
4912           RawMask.push_back((uint64_t)SM_SentinelUndef);
4913         else if (isa<ConstantSDNode>(Op)) {
4914           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4915           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4916         } else
4917           return false;
4918       }
4919       DecodeVPERMVMask(RawMask, Mask);
4920       break;
4921     }
4922     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4923       unsigned NumEltsInMask = MaskNode->getNumOperands();
4924       MaskNode = MaskNode->getOperand(0);
4925       if (auto *CN = dyn_cast<ConstantSDNode>(MaskNode)) {
4926         APInt MaskEltValue = CN->getAPIntValue();
4927         for (unsigned i = 0; i < NumEltsInMask; ++i)
4928           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4929         DecodeVPERMVMask(RawMask, Mask);
4930         break;
4931       }
4932       // It may be a scalar load
4933     }
4934
4935     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4936     if (!MaskLoad)
4937       return false;
4938
4939     SDValue Ptr = MaskLoad->getBasePtr();
4940     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4941         Ptr->getOpcode() == X86ISD::WrapperRIP)
4942       Ptr = Ptr->getOperand(0);
4943
4944     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4945     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4946       return false;
4947
4948     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4949       DecodeVPERMVMask(C, VT, Mask);
4950       break;
4951     }
4952     return false;
4953   }
4954   case X86ISD::VPERMV3: {
4955     IsUnary = false;
4956     SDValue MaskNode = N->getOperand(1);
4957     while (MaskNode->getOpcode() == ISD::BITCAST)
4958       MaskNode = MaskNode->getOperand(1);
4959
4960     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4961       // If we have a build-vector, then things are easy.
4962       assert(MaskNode.getSimpleValueType().isInteger() &&
4963              MaskNode.getSimpleValueType().getVectorNumElements() ==
4964              VT.getVectorNumElements());
4965
4966       SmallVector<uint64_t, 32> RawMask;
4967       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4968
4969       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4970         SDValue Op = MaskNode->getOperand(i);
4971         if (Op->getOpcode() == ISD::UNDEF)
4972           RawMask.push_back((uint64_t)SM_SentinelUndef);
4973         else {
4974           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4975           if (!CN)
4976             return false;
4977           APInt MaskElement = CN->getAPIntValue();
4978           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4979         }
4980       }
4981       DecodeVPERMV3Mask(RawMask, Mask);
4982       break;
4983     }
4984
4985     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4986     if (!MaskLoad)
4987       return false;
4988
4989     SDValue Ptr = MaskLoad->getBasePtr();
4990     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4991         Ptr->getOpcode() == X86ISD::WrapperRIP)
4992       Ptr = Ptr->getOperand(0);
4993
4994     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4995     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4996       return false;
4997
4998     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4999       DecodeVPERMV3Mask(C, VT, Mask);
5000       break;
5001     }
5002     return false;
5003   }
5004   default: llvm_unreachable("unknown target shuffle node");
5005   }
5006
5007   // Empty mask indicates the decode failed.
5008   if (Mask.empty())
5009     return false;
5010
5011   // If we have a fake unary shuffle, the shuffle mask is spread across two
5012   // inputs that are actually the same node. Re-map the mask to always point
5013   // into the first input.
5014   if (IsFakeUnary)
5015     for (int &M : Mask)
5016       if (M >= (int)Mask.size())
5017         M -= Mask.size();
5018
5019   return true;
5020 }
5021
5022 /// Returns the scalar element that will make up the ith
5023 /// element of the result of the vector shuffle.
5024 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5025                                    unsigned Depth) {
5026   if (Depth == 6)
5027     return SDValue();  // Limit search depth.
5028
5029   SDValue V = SDValue(N, 0);
5030   EVT VT = V.getValueType();
5031   unsigned Opcode = V.getOpcode();
5032
5033   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5034   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5035     int Elt = SV->getMaskElt(Index);
5036
5037     if (Elt < 0)
5038       return DAG.getUNDEF(VT.getVectorElementType());
5039
5040     unsigned NumElems = VT.getVectorNumElements();
5041     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5042                                          : SV->getOperand(1);
5043     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5044   }
5045
5046   // Recurse into target specific vector shuffles to find scalars.
5047   if (isTargetShuffle(Opcode)) {
5048     MVT ShufVT = V.getSimpleValueType();
5049     unsigned NumElems = ShufVT.getVectorNumElements();
5050     SmallVector<int, 16> ShuffleMask;
5051     bool IsUnary;
5052
5053     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5054       return SDValue();
5055
5056     int Elt = ShuffleMask[Index];
5057     if (Elt < 0)
5058       return DAG.getUNDEF(ShufVT.getVectorElementType());
5059
5060     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5061                                          : N->getOperand(1);
5062     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5063                                Depth+1);
5064   }
5065
5066   // Actual nodes that may contain scalar elements
5067   if (Opcode == ISD::BITCAST) {
5068     V = V.getOperand(0);
5069     EVT SrcVT = V.getValueType();
5070     unsigned NumElems = VT.getVectorNumElements();
5071
5072     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5073       return SDValue();
5074   }
5075
5076   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5077     return (Index == 0) ? V.getOperand(0)
5078                         : DAG.getUNDEF(VT.getVectorElementType());
5079
5080   if (V.getOpcode() == ISD::BUILD_VECTOR)
5081     return V.getOperand(Index);
5082
5083   return SDValue();
5084 }
5085
5086 /// Custom lower build_vector of v16i8.
5087 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5088                                        unsigned NumNonZero, unsigned NumZero,
5089                                        SelectionDAG &DAG,
5090                                        const X86Subtarget* Subtarget,
5091                                        const TargetLowering &TLI) {
5092   if (NumNonZero > 8)
5093     return SDValue();
5094
5095   SDLoc dl(Op);
5096   SDValue V;
5097   bool First = true;
5098
5099   // SSE4.1 - use PINSRB to insert each byte directly.
5100   if (Subtarget->hasSSE41()) {
5101     for (unsigned i = 0; i < 16; ++i) {
5102       bool isNonZero = (NonZeros & (1 << i)) != 0;
5103       if (isNonZero) {
5104         if (First) {
5105           if (NumZero)
5106             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
5107           else
5108             V = DAG.getUNDEF(MVT::v16i8);
5109           First = false;
5110         }
5111         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5112                         MVT::v16i8, V, Op.getOperand(i),
5113                         DAG.getIntPtrConstant(i, dl));
5114       }
5115     }
5116
5117     return V;
5118   }
5119
5120   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
5121   for (unsigned i = 0; i < 16; ++i) {
5122     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5123     if (ThisIsNonZero && First) {
5124       if (NumZero)
5125         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5126       else
5127         V = DAG.getUNDEF(MVT::v8i16);
5128       First = false;
5129     }
5130
5131     if ((i & 1) != 0) {
5132       SDValue ThisElt, LastElt;
5133       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5134       if (LastIsNonZero) {
5135         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5136                               MVT::i16, Op.getOperand(i-1));
5137       }
5138       if (ThisIsNonZero) {
5139         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5140         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5141                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
5142         if (LastIsNonZero)
5143           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5144       } else
5145         ThisElt = LastElt;
5146
5147       if (ThisElt.getNode())
5148         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5149                         DAG.getIntPtrConstant(i/2, dl));
5150     }
5151   }
5152
5153   return DAG.getBitcast(MVT::v16i8, V);
5154 }
5155
5156 /// Custom lower build_vector of v8i16.
5157 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5158                                      unsigned NumNonZero, unsigned NumZero,
5159                                      SelectionDAG &DAG,
5160                                      const X86Subtarget* Subtarget,
5161                                      const TargetLowering &TLI) {
5162   if (NumNonZero > 4)
5163     return SDValue();
5164
5165   SDLoc dl(Op);
5166   SDValue V;
5167   bool First = true;
5168   for (unsigned i = 0; i < 8; ++i) {
5169     bool isNonZero = (NonZeros & (1 << i)) != 0;
5170     if (isNonZero) {
5171       if (First) {
5172         if (NumZero)
5173           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5174         else
5175           V = DAG.getUNDEF(MVT::v8i16);
5176         First = false;
5177       }
5178       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5179                       MVT::v8i16, V, Op.getOperand(i),
5180                       DAG.getIntPtrConstant(i, dl));
5181     }
5182   }
5183
5184   return V;
5185 }
5186
5187 /// Custom lower build_vector of v4i32 or v4f32.
5188 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5189                                      const X86Subtarget *Subtarget,
5190                                      const TargetLowering &TLI) {
5191   // Find all zeroable elements.
5192   std::bitset<4> Zeroable;
5193   for (int i=0; i < 4; ++i) {
5194     SDValue Elt = Op->getOperand(i);
5195     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5196   }
5197   assert(Zeroable.size() - Zeroable.count() > 1 &&
5198          "We expect at least two non-zero elements!");
5199
5200   // We only know how to deal with build_vector nodes where elements are either
5201   // zeroable or extract_vector_elt with constant index.
5202   SDValue FirstNonZero;
5203   unsigned FirstNonZeroIdx;
5204   for (unsigned i=0; i < 4; ++i) {
5205     if (Zeroable[i])
5206       continue;
5207     SDValue Elt = Op->getOperand(i);
5208     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5209         !isa<ConstantSDNode>(Elt.getOperand(1)))
5210       return SDValue();
5211     // Make sure that this node is extracting from a 128-bit vector.
5212     MVT VT = Elt.getOperand(0).getSimpleValueType();
5213     if (!VT.is128BitVector())
5214       return SDValue();
5215     if (!FirstNonZero.getNode()) {
5216       FirstNonZero = Elt;
5217       FirstNonZeroIdx = i;
5218     }
5219   }
5220
5221   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5222   SDValue V1 = FirstNonZero.getOperand(0);
5223   MVT VT = V1.getSimpleValueType();
5224
5225   // See if this build_vector can be lowered as a blend with zero.
5226   SDValue Elt;
5227   unsigned EltMaskIdx, EltIdx;
5228   int Mask[4];
5229   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5230     if (Zeroable[EltIdx]) {
5231       // The zero vector will be on the right hand side.
5232       Mask[EltIdx] = EltIdx+4;
5233       continue;
5234     }
5235
5236     Elt = Op->getOperand(EltIdx);
5237     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5238     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5239     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5240       break;
5241     Mask[EltIdx] = EltIdx;
5242   }
5243
5244   if (EltIdx == 4) {
5245     // Let the shuffle legalizer deal with blend operations.
5246     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5247     if (V1.getSimpleValueType() != VT)
5248       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5249     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5250   }
5251
5252   // See if we can lower this build_vector to a INSERTPS.
5253   if (!Subtarget->hasSSE41())
5254     return SDValue();
5255
5256   SDValue V2 = Elt.getOperand(0);
5257   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5258     V1 = SDValue();
5259
5260   bool CanFold = true;
5261   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5262     if (Zeroable[i])
5263       continue;
5264
5265     SDValue Current = Op->getOperand(i);
5266     SDValue SrcVector = Current->getOperand(0);
5267     if (!V1.getNode())
5268       V1 = SrcVector;
5269     CanFold = SrcVector == V1 &&
5270       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5271   }
5272
5273   if (!CanFold)
5274     return SDValue();
5275
5276   assert(V1.getNode() && "Expected at least two non-zero elements!");
5277   if (V1.getSimpleValueType() != MVT::v4f32)
5278     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5279   if (V2.getSimpleValueType() != MVT::v4f32)
5280     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5281
5282   // Ok, we can emit an INSERTPS instruction.
5283   unsigned ZMask = Zeroable.to_ulong();
5284
5285   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5286   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5287   SDLoc DL(Op);
5288   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5289                                DAG.getIntPtrConstant(InsertPSMask, DL));
5290   return DAG.getBitcast(VT, Result);
5291 }
5292
5293 /// Return a vector logical shift node.
5294 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5295                          unsigned NumBits, SelectionDAG &DAG,
5296                          const TargetLowering &TLI, SDLoc dl) {
5297   assert(VT.is128BitVector() && "Unknown type for VShift");
5298   MVT ShVT = MVT::v2i64;
5299   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5300   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5301   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5302   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5303   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5304   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5305 }
5306
5307 static SDValue
5308 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5309
5310   // Check if the scalar load can be widened into a vector load. And if
5311   // the address is "base + cst" see if the cst can be "absorbed" into
5312   // the shuffle mask.
5313   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5314     SDValue Ptr = LD->getBasePtr();
5315     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5316       return SDValue();
5317     EVT PVT = LD->getValueType(0);
5318     if (PVT != MVT::i32 && PVT != MVT::f32)
5319       return SDValue();
5320
5321     int FI = -1;
5322     int64_t Offset = 0;
5323     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5324       FI = FINode->getIndex();
5325       Offset = 0;
5326     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5327                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5328       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5329       Offset = Ptr.getConstantOperandVal(1);
5330       Ptr = Ptr.getOperand(0);
5331     } else {
5332       return SDValue();
5333     }
5334
5335     // FIXME: 256-bit vector instructions don't require a strict alignment,
5336     // improve this code to support it better.
5337     unsigned RequiredAlign = VT.getSizeInBits()/8;
5338     SDValue Chain = LD->getChain();
5339     // Make sure the stack object alignment is at least 16 or 32.
5340     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5341     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5342       if (MFI->isFixedObjectIndex(FI)) {
5343         // Can't change the alignment. FIXME: It's possible to compute
5344         // the exact stack offset and reference FI + adjust offset instead.
5345         // If someone *really* cares about this. That's the way to implement it.
5346         return SDValue();
5347       } else {
5348         MFI->setObjectAlignment(FI, RequiredAlign);
5349       }
5350     }
5351
5352     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5353     // Ptr + (Offset & ~15).
5354     if (Offset < 0)
5355       return SDValue();
5356     if ((Offset % RequiredAlign) & 3)
5357       return SDValue();
5358     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5359     if (StartOffset) {
5360       SDLoc DL(Ptr);
5361       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5362                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5363     }
5364
5365     int EltNo = (Offset - StartOffset) >> 2;
5366     unsigned NumElems = VT.getVectorNumElements();
5367
5368     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5369     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5370                              LD->getPointerInfo().getWithOffset(StartOffset),
5371                              false, false, false, 0);
5372
5373     SmallVector<int, 8> Mask(NumElems, EltNo);
5374
5375     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5376   }
5377
5378   return SDValue();
5379 }
5380
5381 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5382 /// elements can be replaced by a single large load which has the same value as
5383 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5384 ///
5385 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5386 ///
5387 /// FIXME: we'd also like to handle the case where the last elements are zero
5388 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5389 /// There's even a handy isZeroNode for that purpose.
5390 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5391                                         SDLoc &DL, SelectionDAG &DAG,
5392                                         bool isAfterLegalize) {
5393   unsigned NumElems = Elts.size();
5394
5395   LoadSDNode *LDBase = nullptr;
5396   unsigned LastLoadedElt = -1U;
5397
5398   // For each element in the initializer, see if we've found a load or an undef.
5399   // If we don't find an initial load element, or later load elements are
5400   // non-consecutive, bail out.
5401   for (unsigned i = 0; i < NumElems; ++i) {
5402     SDValue Elt = Elts[i];
5403     // Look through a bitcast.
5404     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5405       Elt = Elt.getOperand(0);
5406     if (!Elt.getNode() ||
5407         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5408       return SDValue();
5409     if (!LDBase) {
5410       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5411         return SDValue();
5412       LDBase = cast<LoadSDNode>(Elt.getNode());
5413       LastLoadedElt = i;
5414       continue;
5415     }
5416     if (Elt.getOpcode() == ISD::UNDEF)
5417       continue;
5418
5419     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5420     EVT LdVT = Elt.getValueType();
5421     // Each loaded element must be the correct fractional portion of the
5422     // requested vector load.
5423     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5424       return SDValue();
5425     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5426       return SDValue();
5427     LastLoadedElt = i;
5428   }
5429
5430   // If we have found an entire vector of loads and undefs, then return a large
5431   // load of the entire vector width starting at the base pointer.  If we found
5432   // consecutive loads for the low half, generate a vzext_load node.
5433   if (LastLoadedElt == NumElems - 1) {
5434     assert(LDBase && "Did not find base load for merging consecutive loads");
5435     EVT EltVT = LDBase->getValueType(0);
5436     // Ensure that the input vector size for the merged loads matches the
5437     // cumulative size of the input elements.
5438     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5439       return SDValue();
5440
5441     if (isAfterLegalize &&
5442         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5443       return SDValue();
5444
5445     SDValue NewLd = SDValue();
5446
5447     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5448                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5449                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5450                         LDBase->getAlignment());
5451
5452     if (LDBase->hasAnyUseOfValue(1)) {
5453       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5454                                      SDValue(LDBase, 1),
5455                                      SDValue(NewLd.getNode(), 1));
5456       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5457       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5458                              SDValue(NewLd.getNode(), 1));
5459     }
5460
5461     return NewLd;
5462   }
5463
5464   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5465   //of a v4i32 / v4f32. It's probably worth generalizing.
5466   EVT EltVT = VT.getVectorElementType();
5467   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5468       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5469     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5470     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5471     SDValue ResNode =
5472         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5473                                 LDBase->getPointerInfo(),
5474                                 LDBase->getAlignment(),
5475                                 false/*isVolatile*/, true/*ReadMem*/,
5476                                 false/*WriteMem*/);
5477
5478     // Make sure the newly-created LOAD is in the same position as LDBase in
5479     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5480     // update uses of LDBase's output chain to use the TokenFactor.
5481     if (LDBase->hasAnyUseOfValue(1)) {
5482       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5483                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5484       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5485       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5486                              SDValue(ResNode.getNode(), 1));
5487     }
5488
5489     return DAG.getBitcast(VT, ResNode);
5490   }
5491   return SDValue();
5492 }
5493
5494 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5495 /// to generate a splat value for the following cases:
5496 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5497 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5498 /// a scalar load, or a constant.
5499 /// The VBROADCAST node is returned when a pattern is found,
5500 /// or SDValue() otherwise.
5501 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5502                                     SelectionDAG &DAG) {
5503   // VBROADCAST requires AVX.
5504   // TODO: Splats could be generated for non-AVX CPUs using SSE
5505   // instructions, but there's less potential gain for only 128-bit vectors.
5506   if (!Subtarget->hasAVX())
5507     return SDValue();
5508
5509   MVT VT = Op.getSimpleValueType();
5510   SDLoc dl(Op);
5511
5512   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5513          "Unsupported vector type for broadcast.");
5514
5515   SDValue Ld;
5516   bool ConstSplatVal;
5517
5518   switch (Op.getOpcode()) {
5519     default:
5520       // Unknown pattern found.
5521       return SDValue();
5522
5523     case ISD::BUILD_VECTOR: {
5524       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5525       BitVector UndefElements;
5526       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5527
5528       // We need a splat of a single value to use broadcast, and it doesn't
5529       // make any sense if the value is only in one element of the vector.
5530       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5531         return SDValue();
5532
5533       Ld = Splat;
5534       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5535                        Ld.getOpcode() == ISD::ConstantFP);
5536
5537       // Make sure that all of the users of a non-constant load are from the
5538       // BUILD_VECTOR node.
5539       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5540         return SDValue();
5541       break;
5542     }
5543
5544     case ISD::VECTOR_SHUFFLE: {
5545       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5546
5547       // Shuffles must have a splat mask where the first element is
5548       // broadcasted.
5549       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5550         return SDValue();
5551
5552       SDValue Sc = Op.getOperand(0);
5553       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5554           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5555
5556         if (!Subtarget->hasInt256())
5557           return SDValue();
5558
5559         // Use the register form of the broadcast instruction available on AVX2.
5560         if (VT.getSizeInBits() >= 256)
5561           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5562         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5563       }
5564
5565       Ld = Sc.getOperand(0);
5566       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5567                        Ld.getOpcode() == ISD::ConstantFP);
5568
5569       // The scalar_to_vector node and the suspected
5570       // load node must have exactly one user.
5571       // Constants may have multiple users.
5572
5573       // AVX-512 has register version of the broadcast
5574       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5575         Ld.getValueType().getSizeInBits() >= 32;
5576       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5577           !hasRegVer))
5578         return SDValue();
5579       break;
5580     }
5581   }
5582
5583   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5584   bool IsGE256 = (VT.getSizeInBits() >= 256);
5585
5586   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5587   // instruction to save 8 or more bytes of constant pool data.
5588   // TODO: If multiple splats are generated to load the same constant,
5589   // it may be detrimental to overall size. There needs to be a way to detect
5590   // that condition to know if this is truly a size win.
5591   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5592
5593   // Handle broadcasting a single constant scalar from the constant pool
5594   // into a vector.
5595   // On Sandybridge (no AVX2), it is still better to load a constant vector
5596   // from the constant pool and not to broadcast it from a scalar.
5597   // But override that restriction when optimizing for size.
5598   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5599   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5600     EVT CVT = Ld.getValueType();
5601     assert(!CVT.isVector() && "Must not broadcast a vector type");
5602
5603     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5604     // For size optimization, also splat v2f64 and v2i64, and for size opt
5605     // with AVX2, also splat i8 and i16.
5606     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5607     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5608         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5609       const Constant *C = nullptr;
5610       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5611         C = CI->getConstantIntValue();
5612       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5613         C = CF->getConstantFPValue();
5614
5615       assert(C && "Invalid constant type");
5616
5617       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5618       SDValue CP =
5619           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5620       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5621       Ld = DAG.getLoad(
5622           CVT, dl, DAG.getEntryNode(), CP,
5623           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5624           false, false, Alignment);
5625
5626       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5627     }
5628   }
5629
5630   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5631
5632   // Handle AVX2 in-register broadcasts.
5633   if (!IsLoad && Subtarget->hasInt256() &&
5634       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5635     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5636
5637   // The scalar source must be a normal load.
5638   if (!IsLoad)
5639     return SDValue();
5640
5641   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5642       (Subtarget->hasVLX() && ScalarSize == 64))
5643     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5644
5645   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5646   // double since there is no vbroadcastsd xmm
5647   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5648     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5649       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5650   }
5651
5652   // Unsupported broadcast.
5653   return SDValue();
5654 }
5655
5656 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5657 /// underlying vector and index.
5658 ///
5659 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5660 /// index.
5661 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5662                                          SDValue ExtIdx) {
5663   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5664   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5665     return Idx;
5666
5667   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5668   // lowered this:
5669   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5670   // to:
5671   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5672   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5673   //                           undef)
5674   //                       Constant<0>)
5675   // In this case the vector is the extract_subvector expression and the index
5676   // is 2, as specified by the shuffle.
5677   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5678   SDValue ShuffleVec = SVOp->getOperand(0);
5679   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5680   assert(ShuffleVecVT.getVectorElementType() ==
5681          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5682
5683   int ShuffleIdx = SVOp->getMaskElt(Idx);
5684   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5685     ExtractedFromVec = ShuffleVec;
5686     return ShuffleIdx;
5687   }
5688   return Idx;
5689 }
5690
5691 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5692   MVT VT = Op.getSimpleValueType();
5693
5694   // Skip if insert_vec_elt is not supported.
5695   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5696   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5697     return SDValue();
5698
5699   SDLoc DL(Op);
5700   unsigned NumElems = Op.getNumOperands();
5701
5702   SDValue VecIn1;
5703   SDValue VecIn2;
5704   SmallVector<unsigned, 4> InsertIndices;
5705   SmallVector<int, 8> Mask(NumElems, -1);
5706
5707   for (unsigned i = 0; i != NumElems; ++i) {
5708     unsigned Opc = Op.getOperand(i).getOpcode();
5709
5710     if (Opc == ISD::UNDEF)
5711       continue;
5712
5713     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5714       // Quit if more than 1 elements need inserting.
5715       if (InsertIndices.size() > 1)
5716         return SDValue();
5717
5718       InsertIndices.push_back(i);
5719       continue;
5720     }
5721
5722     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5723     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5724     // Quit if non-constant index.
5725     if (!isa<ConstantSDNode>(ExtIdx))
5726       return SDValue();
5727     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5728
5729     // Quit if extracted from vector of different type.
5730     if (ExtractedFromVec.getValueType() != VT)
5731       return SDValue();
5732
5733     if (!VecIn1.getNode())
5734       VecIn1 = ExtractedFromVec;
5735     else if (VecIn1 != ExtractedFromVec) {
5736       if (!VecIn2.getNode())
5737         VecIn2 = ExtractedFromVec;
5738       else if (VecIn2 != ExtractedFromVec)
5739         // Quit if more than 2 vectors to shuffle
5740         return SDValue();
5741     }
5742
5743     if (ExtractedFromVec == VecIn1)
5744       Mask[i] = Idx;
5745     else if (ExtractedFromVec == VecIn2)
5746       Mask[i] = Idx + NumElems;
5747   }
5748
5749   if (!VecIn1.getNode())
5750     return SDValue();
5751
5752   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5753   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5754   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5755     unsigned Idx = InsertIndices[i];
5756     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5757                      DAG.getIntPtrConstant(Idx, DL));
5758   }
5759
5760   return NV;
5761 }
5762
5763 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5764   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5765          Op.getScalarValueSizeInBits() == 1 &&
5766          "Can not convert non-constant vector");
5767   uint64_t Immediate = 0;
5768   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5769     SDValue In = Op.getOperand(idx);
5770     if (In.getOpcode() != ISD::UNDEF)
5771       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5772   }
5773   SDLoc dl(Op);
5774   MVT VT =
5775    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5776   return DAG.getConstant(Immediate, dl, VT);
5777 }
5778 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5779 SDValue
5780 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5781
5782   MVT VT = Op.getSimpleValueType();
5783   assert((VT.getVectorElementType() == MVT::i1) &&
5784          "Unexpected type in LowerBUILD_VECTORvXi1!");
5785
5786   SDLoc dl(Op);
5787   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5788     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5789     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5790     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5791   }
5792
5793   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5794     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5795     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5796     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5797   }
5798
5799   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5800     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5801     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5802       return DAG.getBitcast(VT, Imm);
5803     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5804     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5805                         DAG.getIntPtrConstant(0, dl));
5806   }
5807
5808   // Vector has one or more non-const elements
5809   uint64_t Immediate = 0;
5810   SmallVector<unsigned, 16> NonConstIdx;
5811   bool IsSplat = true;
5812   bool HasConstElts = false;
5813   int SplatIdx = -1;
5814   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5815     SDValue In = Op.getOperand(idx);
5816     if (In.getOpcode() == ISD::UNDEF)
5817       continue;
5818     if (!isa<ConstantSDNode>(In))
5819       NonConstIdx.push_back(idx);
5820     else {
5821       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5822       HasConstElts = true;
5823     }
5824     if (SplatIdx == -1)
5825       SplatIdx = idx;
5826     else if (In != Op.getOperand(SplatIdx))
5827       IsSplat = false;
5828   }
5829
5830   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5831   if (IsSplat)
5832     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5833                        DAG.getConstant(1, dl, VT),
5834                        DAG.getConstant(0, dl, VT));
5835
5836   // insert elements one by one
5837   SDValue DstVec;
5838   SDValue Imm;
5839   if (Immediate) {
5840     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5841     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5842   }
5843   else if (HasConstElts)
5844     Imm = DAG.getConstant(0, dl, VT);
5845   else
5846     Imm = DAG.getUNDEF(VT);
5847   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5848     DstVec = DAG.getBitcast(VT, Imm);
5849   else {
5850     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5851     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5852                          DAG.getIntPtrConstant(0, dl));
5853   }
5854
5855   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5856     unsigned InsertIdx = NonConstIdx[i];
5857     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5858                          Op.getOperand(InsertIdx),
5859                          DAG.getIntPtrConstant(InsertIdx, dl));
5860   }
5861   return DstVec;
5862 }
5863
5864 /// \brief Return true if \p N implements a horizontal binop and return the
5865 /// operands for the horizontal binop into V0 and V1.
5866 ///
5867 /// This is a helper function of LowerToHorizontalOp().
5868 /// This function checks that the build_vector \p N in input implements a
5869 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5870 /// operation to match.
5871 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5872 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5873 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5874 /// arithmetic sub.
5875 ///
5876 /// This function only analyzes elements of \p N whose indices are
5877 /// in range [BaseIdx, LastIdx).
5878 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5879                               SelectionDAG &DAG,
5880                               unsigned BaseIdx, unsigned LastIdx,
5881                               SDValue &V0, SDValue &V1) {
5882   EVT VT = N->getValueType(0);
5883
5884   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5885   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5886          "Invalid Vector in input!");
5887
5888   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5889   bool CanFold = true;
5890   unsigned ExpectedVExtractIdx = BaseIdx;
5891   unsigned NumElts = LastIdx - BaseIdx;
5892   V0 = DAG.getUNDEF(VT);
5893   V1 = DAG.getUNDEF(VT);
5894
5895   // Check if N implements a horizontal binop.
5896   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5897     SDValue Op = N->getOperand(i + BaseIdx);
5898
5899     // Skip UNDEFs.
5900     if (Op->getOpcode() == ISD::UNDEF) {
5901       // Update the expected vector extract index.
5902       if (i * 2 == NumElts)
5903         ExpectedVExtractIdx = BaseIdx;
5904       ExpectedVExtractIdx += 2;
5905       continue;
5906     }
5907
5908     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5909
5910     if (!CanFold)
5911       break;
5912
5913     SDValue Op0 = Op.getOperand(0);
5914     SDValue Op1 = Op.getOperand(1);
5915
5916     // Try to match the following pattern:
5917     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5918     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5919         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5920         Op0.getOperand(0) == Op1.getOperand(0) &&
5921         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5922         isa<ConstantSDNode>(Op1.getOperand(1)));
5923     if (!CanFold)
5924       break;
5925
5926     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5927     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5928
5929     if (i * 2 < NumElts) {
5930       if (V0.getOpcode() == ISD::UNDEF) {
5931         V0 = Op0.getOperand(0);
5932         if (V0.getValueType() != VT)
5933           return false;
5934       }
5935     } else {
5936       if (V1.getOpcode() == ISD::UNDEF) {
5937         V1 = Op0.getOperand(0);
5938         if (V1.getValueType() != VT)
5939           return false;
5940       }
5941       if (i * 2 == NumElts)
5942         ExpectedVExtractIdx = BaseIdx;
5943     }
5944
5945     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5946     if (I0 == ExpectedVExtractIdx)
5947       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5948     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5949       // Try to match the following dag sequence:
5950       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5951       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5952     } else
5953       CanFold = false;
5954
5955     ExpectedVExtractIdx += 2;
5956   }
5957
5958   return CanFold;
5959 }
5960
5961 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5962 /// a concat_vector.
5963 ///
5964 /// This is a helper function of LowerToHorizontalOp().
5965 /// This function expects two 256-bit vectors called V0 and V1.
5966 /// At first, each vector is split into two separate 128-bit vectors.
5967 /// Then, the resulting 128-bit vectors are used to implement two
5968 /// horizontal binary operations.
5969 ///
5970 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5971 ///
5972 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5973 /// the two new horizontal binop.
5974 /// When Mode is set, the first horizontal binop dag node would take as input
5975 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5976 /// horizontal binop dag node would take as input the lower 128-bit of V1
5977 /// and the upper 128-bit of V1.
5978 ///   Example:
5979 ///     HADD V0_LO, V0_HI
5980 ///     HADD V1_LO, V1_HI
5981 ///
5982 /// Otherwise, the first horizontal binop dag node takes as input the lower
5983 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5984 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5985 ///   Example:
5986 ///     HADD V0_LO, V1_LO
5987 ///     HADD V0_HI, V1_HI
5988 ///
5989 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5990 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5991 /// the upper 128-bits of the result.
5992 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5993                                      SDLoc DL, SelectionDAG &DAG,
5994                                      unsigned X86Opcode, bool Mode,
5995                                      bool isUndefLO, bool isUndefHI) {
5996   EVT VT = V0.getValueType();
5997   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5998          "Invalid nodes in input!");
5999
6000   unsigned NumElts = VT.getVectorNumElements();
6001   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6002   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6003   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6004   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6005   EVT NewVT = V0_LO.getValueType();
6006
6007   SDValue LO = DAG.getUNDEF(NewVT);
6008   SDValue HI = DAG.getUNDEF(NewVT);
6009
6010   if (Mode) {
6011     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6012     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6013       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6014     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6015       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6016   } else {
6017     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6018     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6019                        V1_LO->getOpcode() != ISD::UNDEF))
6020       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6021
6022     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6023                        V1_HI->getOpcode() != ISD::UNDEF))
6024       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6025   }
6026
6027   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6028 }
6029
6030 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
6031 /// node.
6032 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
6033                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6034   MVT VT = BV->getSimpleValueType(0);
6035   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
6036       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
6037     return SDValue();
6038
6039   SDLoc DL(BV);
6040   unsigned NumElts = VT.getVectorNumElements();
6041   SDValue InVec0 = DAG.getUNDEF(VT);
6042   SDValue InVec1 = DAG.getUNDEF(VT);
6043
6044   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6045           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6046
6047   // Odd-numbered elements in the input build vector are obtained from
6048   // adding two integer/float elements.
6049   // Even-numbered elements in the input build vector are obtained from
6050   // subtracting two integer/float elements.
6051   unsigned ExpectedOpcode = ISD::FSUB;
6052   unsigned NextExpectedOpcode = ISD::FADD;
6053   bool AddFound = false;
6054   bool SubFound = false;
6055
6056   for (unsigned i = 0, e = NumElts; i != e; ++i) {
6057     SDValue Op = BV->getOperand(i);
6058
6059     // Skip 'undef' values.
6060     unsigned Opcode = Op.getOpcode();
6061     if (Opcode == ISD::UNDEF) {
6062       std::swap(ExpectedOpcode, NextExpectedOpcode);
6063       continue;
6064     }
6065
6066     // Early exit if we found an unexpected opcode.
6067     if (Opcode != ExpectedOpcode)
6068       return SDValue();
6069
6070     SDValue Op0 = Op.getOperand(0);
6071     SDValue Op1 = Op.getOperand(1);
6072
6073     // Try to match the following pattern:
6074     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6075     // Early exit if we cannot match that sequence.
6076     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6077         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6078         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6079         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6080         Op0.getOperand(1) != Op1.getOperand(1))
6081       return SDValue();
6082
6083     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6084     if (I0 != i)
6085       return SDValue();
6086
6087     // We found a valid add/sub node. Update the information accordingly.
6088     if (i & 1)
6089       AddFound = true;
6090     else
6091       SubFound = true;
6092
6093     // Update InVec0 and InVec1.
6094     if (InVec0.getOpcode() == ISD::UNDEF) {
6095       InVec0 = Op0.getOperand(0);
6096       if (InVec0.getSimpleValueType() != VT)
6097         return SDValue();
6098     }
6099     if (InVec1.getOpcode() == ISD::UNDEF) {
6100       InVec1 = Op1.getOperand(0);
6101       if (InVec1.getSimpleValueType() != VT)
6102         return SDValue();
6103     }
6104
6105     // Make sure that operands in input to each add/sub node always
6106     // come from a same pair of vectors.
6107     if (InVec0 != Op0.getOperand(0)) {
6108       if (ExpectedOpcode == ISD::FSUB)
6109         return SDValue();
6110
6111       // FADD is commutable. Try to commute the operands
6112       // and then test again.
6113       std::swap(Op0, Op1);
6114       if (InVec0 != Op0.getOperand(0))
6115         return SDValue();
6116     }
6117
6118     if (InVec1 != Op1.getOperand(0))
6119       return SDValue();
6120
6121     // Update the pair of expected opcodes.
6122     std::swap(ExpectedOpcode, NextExpectedOpcode);
6123   }
6124
6125   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6126   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6127       InVec1.getOpcode() != ISD::UNDEF)
6128     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6129
6130   return SDValue();
6131 }
6132
6133 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
6134 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
6135                                    const X86Subtarget *Subtarget,
6136                                    SelectionDAG &DAG) {
6137   MVT VT = BV->getSimpleValueType(0);
6138   unsigned NumElts = VT.getVectorNumElements();
6139   unsigned NumUndefsLO = 0;
6140   unsigned NumUndefsHI = 0;
6141   unsigned Half = NumElts/2;
6142
6143   // Count the number of UNDEF operands in the build_vector in input.
6144   for (unsigned i = 0, e = Half; i != e; ++i)
6145     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6146       NumUndefsLO++;
6147
6148   for (unsigned i = Half, e = NumElts; i != e; ++i)
6149     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6150       NumUndefsHI++;
6151
6152   // Early exit if this is either a build_vector of all UNDEFs or all the
6153   // operands but one are UNDEF.
6154   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6155     return SDValue();
6156
6157   SDLoc DL(BV);
6158   SDValue InVec0, InVec1;
6159   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6160     // Try to match an SSE3 float HADD/HSUB.
6161     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6162       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6163
6164     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6165       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6166   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6167     // Try to match an SSSE3 integer HADD/HSUB.
6168     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6169       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6170
6171     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6172       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6173   }
6174
6175   if (!Subtarget->hasAVX())
6176     return SDValue();
6177
6178   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6179     // Try to match an AVX horizontal add/sub of packed single/double
6180     // precision floating point values from 256-bit vectors.
6181     SDValue InVec2, InVec3;
6182     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6183         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6184         ((InVec0.getOpcode() == ISD::UNDEF ||
6185           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6186         ((InVec1.getOpcode() == ISD::UNDEF ||
6187           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6188       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6189
6190     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6191         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6192         ((InVec0.getOpcode() == ISD::UNDEF ||
6193           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6194         ((InVec1.getOpcode() == ISD::UNDEF ||
6195           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6196       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6197   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6198     // Try to match an AVX2 horizontal add/sub of signed integers.
6199     SDValue InVec2, InVec3;
6200     unsigned X86Opcode;
6201     bool CanFold = true;
6202
6203     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6204         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6205         ((InVec0.getOpcode() == ISD::UNDEF ||
6206           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6207         ((InVec1.getOpcode() == ISD::UNDEF ||
6208           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6209       X86Opcode = X86ISD::HADD;
6210     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6211         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6212         ((InVec0.getOpcode() == ISD::UNDEF ||
6213           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6214         ((InVec1.getOpcode() == ISD::UNDEF ||
6215           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6216       X86Opcode = X86ISD::HSUB;
6217     else
6218       CanFold = false;
6219
6220     if (CanFold) {
6221       // Fold this build_vector into a single horizontal add/sub.
6222       // Do this only if the target has AVX2.
6223       if (Subtarget->hasAVX2())
6224         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6225
6226       // Do not try to expand this build_vector into a pair of horizontal
6227       // add/sub if we can emit a pair of scalar add/sub.
6228       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6229         return SDValue();
6230
6231       // Convert this build_vector into a pair of horizontal binop followed by
6232       // a concat vector.
6233       bool isUndefLO = NumUndefsLO == Half;
6234       bool isUndefHI = NumUndefsHI == Half;
6235       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6236                                    isUndefLO, isUndefHI);
6237     }
6238   }
6239
6240   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6241        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6242     unsigned X86Opcode;
6243     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6244       X86Opcode = X86ISD::HADD;
6245     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6246       X86Opcode = X86ISD::HSUB;
6247     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6248       X86Opcode = X86ISD::FHADD;
6249     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6250       X86Opcode = X86ISD::FHSUB;
6251     else
6252       return SDValue();
6253
6254     // Don't try to expand this build_vector into a pair of horizontal add/sub
6255     // if we can simply emit a pair of scalar add/sub.
6256     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6257       return SDValue();
6258
6259     // Convert this build_vector into two horizontal add/sub followed by
6260     // a concat vector.
6261     bool isUndefLO = NumUndefsLO == Half;
6262     bool isUndefHI = NumUndefsHI == Half;
6263     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6264                                  isUndefLO, isUndefHI);
6265   }
6266
6267   return SDValue();
6268 }
6269
6270 SDValue
6271 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6272   SDLoc dl(Op);
6273
6274   MVT VT = Op.getSimpleValueType();
6275   MVT ExtVT = VT.getVectorElementType();
6276   unsigned NumElems = Op.getNumOperands();
6277
6278   // Generate vectors for predicate vectors.
6279   if (VT.getVectorElementType() == MVT::i1 && Subtarget->hasAVX512())
6280     return LowerBUILD_VECTORvXi1(Op, DAG);
6281
6282   // Vectors containing all zeros can be matched by pxor and xorps later
6283   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6284     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6285     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6286     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6287       return Op;
6288
6289     return getZeroVector(VT, Subtarget, DAG, dl);
6290   }
6291
6292   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6293   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6294   // vpcmpeqd on 256-bit vectors.
6295   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6296     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6297       return Op;
6298
6299     if (!VT.is512BitVector())
6300       return getOnesVector(VT, Subtarget, DAG, dl);
6301   }
6302
6303   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6304   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6305     return AddSub;
6306   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6307     return HorizontalOp;
6308   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6309     return Broadcast;
6310
6311   unsigned EVTBits = ExtVT.getSizeInBits();
6312
6313   unsigned NumZero  = 0;
6314   unsigned NumNonZero = 0;
6315   uint64_t NonZeros = 0;
6316   bool IsAllConstants = true;
6317   SmallSet<SDValue, 8> Values;
6318   for (unsigned i = 0; i < NumElems; ++i) {
6319     SDValue Elt = Op.getOperand(i);
6320     if (Elt.getOpcode() == ISD::UNDEF)
6321       continue;
6322     Values.insert(Elt);
6323     if (Elt.getOpcode() != ISD::Constant &&
6324         Elt.getOpcode() != ISD::ConstantFP)
6325       IsAllConstants = false;
6326     if (X86::isZeroNode(Elt))
6327       NumZero++;
6328     else {
6329       assert(i < sizeof(NonZeros) * 8); // Make sure the shift is within range.
6330       NonZeros |= ((uint64_t)1 << i);
6331       NumNonZero++;
6332     }
6333   }
6334
6335   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6336   if (NumNonZero == 0)
6337     return DAG.getUNDEF(VT);
6338
6339   // Special case for single non-zero, non-undef, element.
6340   if (NumNonZero == 1) {
6341     unsigned Idx = countTrailingZeros(NonZeros);
6342     SDValue Item = Op.getOperand(Idx);
6343
6344     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6345     // the value are obviously zero, truncate the value to i32 and do the
6346     // insertion that way.  Only do this if the value is non-constant or if the
6347     // value is a constant being inserted into element 0.  It is cheaper to do
6348     // a constant pool load than it is to do a movd + shuffle.
6349     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6350         (!IsAllConstants || Idx == 0)) {
6351       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6352         // Handle SSE only.
6353         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6354         MVT VecVT = MVT::v4i32;
6355
6356         // Truncate the value (which may itself be a constant) to i32, and
6357         // convert it to a vector with movd (S2V+shuffle to zero extend).
6358         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6359         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6360         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6361                                       Item, Idx * 2, true, Subtarget, DAG));
6362       }
6363     }
6364
6365     // If we have a constant or non-constant insertion into the low element of
6366     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6367     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6368     // depending on what the source datatype is.
6369     if (Idx == 0) {
6370       if (NumZero == 0)
6371         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6372
6373       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6374           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6375         if (VT.is512BitVector()) {
6376           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6377           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6378                              Item, DAG.getIntPtrConstant(0, dl));
6379         }
6380         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6381                "Expected an SSE value type!");
6382         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6383         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6384         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6385       }
6386
6387       // We can't directly insert an i8 or i16 into a vector, so zero extend
6388       // it to i32 first.
6389       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6390         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6391         if (VT.is256BitVector()) {
6392           if (Subtarget->hasAVX()) {
6393             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6394             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6395           } else {
6396             // Without AVX, we need to extend to a 128-bit vector and then
6397             // insert into the 256-bit vector.
6398             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6399             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6400             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6401           }
6402         } else {
6403           assert(VT.is128BitVector() && "Expected an SSE value type!");
6404           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6405           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6406         }
6407         return DAG.getBitcast(VT, Item);
6408       }
6409     }
6410
6411     // Is it a vector logical left shift?
6412     if (NumElems == 2 && Idx == 1 &&
6413         X86::isZeroNode(Op.getOperand(0)) &&
6414         !X86::isZeroNode(Op.getOperand(1))) {
6415       unsigned NumBits = VT.getSizeInBits();
6416       return getVShift(true, VT,
6417                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6418                                    VT, Op.getOperand(1)),
6419                        NumBits/2, DAG, *this, dl);
6420     }
6421
6422     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6423       return SDValue();
6424
6425     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6426     // is a non-constant being inserted into an element other than the low one,
6427     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6428     // movd/movss) to move this into the low element, then shuffle it into
6429     // place.
6430     if (EVTBits == 32) {
6431       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6432       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6433     }
6434   }
6435
6436   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6437   if (Values.size() == 1) {
6438     if (EVTBits == 32) {
6439       // Instead of a shuffle like this:
6440       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6441       // Check if it's possible to issue this instead.
6442       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6443       unsigned Idx = countTrailingZeros(NonZeros);
6444       SDValue Item = Op.getOperand(Idx);
6445       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6446         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6447     }
6448     return SDValue();
6449   }
6450
6451   // A vector full of immediates; various special cases are already
6452   // handled, so this is best done with a single constant-pool load.
6453   if (IsAllConstants)
6454     return SDValue();
6455
6456   // For AVX-length vectors, see if we can use a vector load to get all of the
6457   // elements, otherwise build the individual 128-bit pieces and use
6458   // shuffles to put them in place.
6459   if (VT.is256BitVector() || VT.is512BitVector()) {
6460     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6461
6462     // Check for a build vector of consecutive loads.
6463     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6464       return LD;
6465
6466     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6467
6468     // Build both the lower and upper subvector.
6469     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6470                                 makeArrayRef(&V[0], NumElems/2));
6471     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6472                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6473
6474     // Recreate the wider vector with the lower and upper part.
6475     if (VT.is256BitVector())
6476       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6477     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6478   }
6479
6480   // Let legalizer expand 2-wide build_vectors.
6481   if (EVTBits == 64) {
6482     if (NumNonZero == 1) {
6483       // One half is zero or undef.
6484       unsigned Idx = countTrailingZeros(NonZeros);
6485       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6486                                Op.getOperand(Idx));
6487       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6488     }
6489     return SDValue();
6490   }
6491
6492   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6493   if (EVTBits == 8 && NumElems == 16)
6494     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros, NumNonZero, NumZero,
6495                                           DAG, Subtarget, *this))
6496       return V;
6497
6498   if (EVTBits == 16 && NumElems == 8)
6499     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros, NumNonZero, NumZero,
6500                                           DAG, Subtarget, *this))
6501       return V;
6502
6503   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6504   if (EVTBits == 32 && NumElems == 4)
6505     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6506       return V;
6507
6508   // If element VT is == 32 bits, turn it into a number of shuffles.
6509   SmallVector<SDValue, 8> V(NumElems);
6510   if (NumElems == 4 && NumZero > 0) {
6511     for (unsigned i = 0; i < 4; ++i) {
6512       bool isZero = !(NonZeros & (1ULL << i));
6513       if (isZero)
6514         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6515       else
6516         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6517     }
6518
6519     for (unsigned i = 0; i < 2; ++i) {
6520       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6521         default: break;
6522         case 0:
6523           V[i] = V[i*2];  // Must be a zero vector.
6524           break;
6525         case 1:
6526           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6527           break;
6528         case 2:
6529           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6530           break;
6531         case 3:
6532           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6533           break;
6534       }
6535     }
6536
6537     bool Reverse1 = (NonZeros & 0x3) == 2;
6538     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6539     int MaskVec[] = {
6540       Reverse1 ? 1 : 0,
6541       Reverse1 ? 0 : 1,
6542       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6543       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6544     };
6545     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6546   }
6547
6548   if (Values.size() > 1 && VT.is128BitVector()) {
6549     // Check for a build vector of consecutive loads.
6550     for (unsigned i = 0; i < NumElems; ++i)
6551       V[i] = Op.getOperand(i);
6552
6553     // Check for elements which are consecutive loads.
6554     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6555       return LD;
6556
6557     // Check for a build vector from mostly shuffle plus few inserting.
6558     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6559       return Sh;
6560
6561     // For SSE 4.1, use insertps to put the high elements into the low element.
6562     if (Subtarget->hasSSE41()) {
6563       SDValue Result;
6564       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6565         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6566       else
6567         Result = DAG.getUNDEF(VT);
6568
6569       for (unsigned i = 1; i < NumElems; ++i) {
6570         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6571         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6572                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6573       }
6574       return Result;
6575     }
6576
6577     // Otherwise, expand into a number of unpckl*, start by extending each of
6578     // our (non-undef) elements to the full vector width with the element in the
6579     // bottom slot of the vector (which generates no code for SSE).
6580     for (unsigned i = 0; i < NumElems; ++i) {
6581       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6582         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6583       else
6584         V[i] = DAG.getUNDEF(VT);
6585     }
6586
6587     // Next, we iteratively mix elements, e.g. for v4f32:
6588     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6589     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6590     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6591     unsigned EltStride = NumElems >> 1;
6592     while (EltStride != 0) {
6593       for (unsigned i = 0; i < EltStride; ++i) {
6594         // If V[i+EltStride] is undef and this is the first round of mixing,
6595         // then it is safe to just drop this shuffle: V[i] is already in the
6596         // right place, the one element (since it's the first round) being
6597         // inserted as undef can be dropped.  This isn't safe for successive
6598         // rounds because they will permute elements within both vectors.
6599         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6600             EltStride == NumElems/2)
6601           continue;
6602
6603         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6604       }
6605       EltStride >>= 1;
6606     }
6607     return V[0];
6608   }
6609   return SDValue();
6610 }
6611
6612 // 256-bit AVX can use the vinsertf128 instruction
6613 // to create 256-bit vectors from two other 128-bit ones.
6614 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6615   SDLoc dl(Op);
6616   MVT ResVT = Op.getSimpleValueType();
6617
6618   assert((ResVT.is256BitVector() ||
6619           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6620
6621   SDValue V1 = Op.getOperand(0);
6622   SDValue V2 = Op.getOperand(1);
6623   unsigned NumElems = ResVT.getVectorNumElements();
6624   if (ResVT.is256BitVector())
6625     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6626
6627   if (Op.getNumOperands() == 4) {
6628     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6629                                   ResVT.getVectorNumElements()/2);
6630     SDValue V3 = Op.getOperand(2);
6631     SDValue V4 = Op.getOperand(3);
6632     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6633       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6634   }
6635   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6636 }
6637
6638 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6639                                        const X86Subtarget *Subtarget,
6640                                        SelectionDAG & DAG) {
6641   SDLoc dl(Op);
6642   MVT ResVT = Op.getSimpleValueType();
6643   unsigned NumOfOperands = Op.getNumOperands();
6644
6645   assert(isPowerOf2_32(NumOfOperands) &&
6646          "Unexpected number of operands in CONCAT_VECTORS");
6647
6648   SDValue Undef = DAG.getUNDEF(ResVT);
6649   if (NumOfOperands > 2) {
6650     // Specialize the cases when all, or all but one, of the operands are undef.
6651     unsigned NumOfDefinedOps = 0;
6652     unsigned OpIdx = 0;
6653     for (unsigned i = 0; i < NumOfOperands; i++)
6654       if (!Op.getOperand(i).isUndef()) {
6655         NumOfDefinedOps++;
6656         OpIdx = i;
6657       }
6658     if (NumOfDefinedOps == 0)
6659       return Undef;
6660     if (NumOfDefinedOps == 1) {
6661       unsigned SubVecNumElts =
6662         Op.getOperand(OpIdx).getValueType().getVectorNumElements();
6663       SDValue IdxVal = DAG.getIntPtrConstant(SubVecNumElts * OpIdx, dl);
6664       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef,
6665                          Op.getOperand(OpIdx), IdxVal);
6666     }
6667
6668     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6669                                   ResVT.getVectorNumElements()/2);
6670     SmallVector<SDValue, 2> Ops;
6671     for (unsigned i = 0; i < NumOfOperands/2; i++)
6672       Ops.push_back(Op.getOperand(i));
6673     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6674     Ops.clear();
6675     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6676       Ops.push_back(Op.getOperand(i));
6677     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6678     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6679   }
6680
6681   // 2 operands
6682   SDValue V1 = Op.getOperand(0);
6683   SDValue V2 = Op.getOperand(1);
6684   unsigned NumElems = ResVT.getVectorNumElements();
6685   assert(V1.getValueType() == V2.getValueType() &&
6686          V1.getValueType().getVectorNumElements() == NumElems/2 &&
6687          "Unexpected operands in CONCAT_VECTORS");
6688
6689   if (ResVT.getSizeInBits() >= 16)
6690     return Op; // The operation is legal with KUNPCK
6691
6692   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6693   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6694   SDValue ZeroVec = getZeroVector(ResVT, Subtarget, DAG, dl);
6695   if (IsZeroV1 && IsZeroV2)
6696     return ZeroVec;
6697
6698   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6699   if (V2.isUndef())
6700     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6701   if (IsZeroV2)
6702     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V1, ZeroIdx);
6703
6704   SDValue IdxVal = DAG.getIntPtrConstant(NumElems/2, dl);
6705   if (V1.isUndef())
6706     V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, IdxVal);
6707
6708   if (IsZeroV1)
6709     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V2, IdxVal);
6710
6711   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6712   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, V1, V2, IdxVal);
6713 }
6714
6715 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6716                                    const X86Subtarget *Subtarget,
6717                                    SelectionDAG &DAG) {
6718   MVT VT = Op.getSimpleValueType();
6719   if (VT.getVectorElementType() == MVT::i1)
6720     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6721
6722   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6723          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6724           Op.getNumOperands() == 4)));
6725
6726   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6727   // from two other 128-bit ones.
6728
6729   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6730   return LowerAVXCONCAT_VECTORS(Op, DAG);
6731 }
6732
6733 //===----------------------------------------------------------------------===//
6734 // Vector shuffle lowering
6735 //
6736 // This is an experimental code path for lowering vector shuffles on x86. It is
6737 // designed to handle arbitrary vector shuffles and blends, gracefully
6738 // degrading performance as necessary. It works hard to recognize idiomatic
6739 // shuffles and lower them to optimal instruction patterns without leaving
6740 // a framework that allows reasonably efficient handling of all vector shuffle
6741 // patterns.
6742 //===----------------------------------------------------------------------===//
6743
6744 /// \brief Tiny helper function to identify a no-op mask.
6745 ///
6746 /// This is a somewhat boring predicate function. It checks whether the mask
6747 /// array input, which is assumed to be a single-input shuffle mask of the kind
6748 /// used by the X86 shuffle instructions (not a fully general
6749 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6750 /// in-place shuffle are 'no-op's.
6751 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6752   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6753     if (Mask[i] != -1 && Mask[i] != i)
6754       return false;
6755   return true;
6756 }
6757
6758 /// \brief Helper function to classify a mask as a single-input mask.
6759 ///
6760 /// This isn't a generic single-input test because in the vector shuffle
6761 /// lowering we canonicalize single inputs to be the first input operand. This
6762 /// means we can more quickly test for a single input by only checking whether
6763 /// an input from the second operand exists. We also assume that the size of
6764 /// mask corresponds to the size of the input vectors which isn't true in the
6765 /// fully general case.
6766 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6767   for (int M : Mask)
6768     if (M >= (int)Mask.size())
6769       return false;
6770   return true;
6771 }
6772
6773 /// \brief Test whether there are elements crossing 128-bit lanes in this
6774 /// shuffle mask.
6775 ///
6776 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6777 /// and we routinely test for these.
6778 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6779   int LaneSize = 128 / VT.getScalarSizeInBits();
6780   int Size = Mask.size();
6781   for (int i = 0; i < Size; ++i)
6782     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6783       return true;
6784   return false;
6785 }
6786
6787 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6788 ///
6789 /// This checks a shuffle mask to see if it is performing the same
6790 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6791 /// that it is also not lane-crossing. It may however involve a blend from the
6792 /// same lane of a second vector.
6793 ///
6794 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6795 /// non-trivial to compute in the face of undef lanes. The representation is
6796 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6797 /// entries from both V1 and V2 inputs to the wider mask.
6798 static bool
6799 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6800                                 SmallVectorImpl<int> &RepeatedMask) {
6801   int LaneSize = 128 / VT.getScalarSizeInBits();
6802   RepeatedMask.resize(LaneSize, -1);
6803   int Size = Mask.size();
6804   for (int i = 0; i < Size; ++i) {
6805     if (Mask[i] < 0)
6806       continue;
6807     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6808       // This entry crosses lanes, so there is no way to model this shuffle.
6809       return false;
6810
6811     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6812     if (RepeatedMask[i % LaneSize] == -1)
6813       // This is the first non-undef entry in this slot of a 128-bit lane.
6814       RepeatedMask[i % LaneSize] =
6815           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6816     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6817       // Found a mismatch with the repeated mask.
6818       return false;
6819   }
6820   return true;
6821 }
6822
6823 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6824 /// arguments.
6825 ///
6826 /// This is a fast way to test a shuffle mask against a fixed pattern:
6827 ///
6828 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6829 ///
6830 /// It returns true if the mask is exactly as wide as the argument list, and
6831 /// each element of the mask is either -1 (signifying undef) or the value given
6832 /// in the argument.
6833 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6834                                 ArrayRef<int> ExpectedMask) {
6835   if (Mask.size() != ExpectedMask.size())
6836     return false;
6837
6838   int Size = Mask.size();
6839
6840   // If the values are build vectors, we can look through them to find
6841   // equivalent inputs that make the shuffles equivalent.
6842   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6843   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6844
6845   for (int i = 0; i < Size; ++i)
6846     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6847       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6848       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6849       if (!MaskBV || !ExpectedBV ||
6850           MaskBV->getOperand(Mask[i] % Size) !=
6851               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6852         return false;
6853     }
6854
6855   return true;
6856 }
6857
6858 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6859 ///
6860 /// This helper function produces an 8-bit shuffle immediate corresponding to
6861 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6862 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6863 /// example.
6864 ///
6865 /// NB: We rely heavily on "undef" masks preserving the input lane.
6866 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6867                                           SelectionDAG &DAG) {
6868   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6869   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6870   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6871   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6872   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6873
6874   unsigned Imm = 0;
6875   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6876   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6877   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6878   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6879   return DAG.getConstant(Imm, DL, MVT::i8);
6880 }
6881
6882 /// \brief Compute whether each element of a shuffle is zeroable.
6883 ///
6884 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6885 /// Either it is an undef element in the shuffle mask, the element of the input
6886 /// referenced is undef, or the element of the input referenced is known to be
6887 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6888 /// as many lanes with this technique as possible to simplify the remaining
6889 /// shuffle.
6890 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6891                                                      SDValue V1, SDValue V2) {
6892   SmallBitVector Zeroable(Mask.size(), false);
6893
6894   while (V1.getOpcode() == ISD::BITCAST)
6895     V1 = V1->getOperand(0);
6896   while (V2.getOpcode() == ISD::BITCAST)
6897     V2 = V2->getOperand(0);
6898
6899   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6900   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6901
6902   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6903     int M = Mask[i];
6904     // Handle the easy cases.
6905     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6906       Zeroable[i] = true;
6907       continue;
6908     }
6909
6910     // If this is an index into a build_vector node (which has the same number
6911     // of elements), dig out the input value and use it.
6912     SDValue V = M < Size ? V1 : V2;
6913     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6914       continue;
6915
6916     SDValue Input = V.getOperand(M % Size);
6917     // The UNDEF opcode check really should be dead code here, but not quite
6918     // worth asserting on (it isn't invalid, just unexpected).
6919     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6920       Zeroable[i] = true;
6921   }
6922
6923   return Zeroable;
6924 }
6925
6926 // X86 has dedicated unpack instructions that can handle specific blend
6927 // operations: UNPCKH and UNPCKL.
6928 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6929                                            SDValue V1, SDValue V2,
6930                                            SelectionDAG &DAG) {
6931   int NumElts = VT.getVectorNumElements();
6932   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6933   SmallVector<int, 8> Unpckl;
6934   SmallVector<int, 8> Unpckh;
6935
6936   for (int i = 0; i < NumElts; ++i) {
6937     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6938     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6939     int HiPos = LoPos + NumEltsInLane / 2;
6940     Unpckl.push_back(LoPos);
6941     Unpckh.push_back(HiPos);
6942   }
6943
6944   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6945     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6946   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6947     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6948
6949   // Commute and try again.
6950   ShuffleVectorSDNode::commuteMask(Unpckl);
6951   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6952     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6953
6954   ShuffleVectorSDNode::commuteMask(Unpckh);
6955   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6956     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6957
6958   return SDValue();
6959 }
6960
6961 /// \brief Try to emit a bitmask instruction for a shuffle.
6962 ///
6963 /// This handles cases where we can model a blend exactly as a bitmask due to
6964 /// one of the inputs being zeroable.
6965 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6966                                            SDValue V2, ArrayRef<int> Mask,
6967                                            SelectionDAG &DAG) {
6968   MVT EltVT = VT.getVectorElementType();
6969   int NumEltBits = EltVT.getSizeInBits();
6970   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6971   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6972   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6973                                     IntEltVT);
6974   if (EltVT.isFloatingPoint()) {
6975     Zero = DAG.getBitcast(EltVT, Zero);
6976     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6977   }
6978   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6979   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6980   SDValue V;
6981   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6982     if (Zeroable[i])
6983       continue;
6984     if (Mask[i] % Size != i)
6985       return SDValue(); // Not a blend.
6986     if (!V)
6987       V = Mask[i] < Size ? V1 : V2;
6988     else if (V != (Mask[i] < Size ? V1 : V2))
6989       return SDValue(); // Can only let one input through the mask.
6990
6991     VMaskOps[i] = AllOnes;
6992   }
6993   if (!V)
6994     return SDValue(); // No non-zeroable elements!
6995
6996   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6997   V = DAG.getNode(VT.isFloatingPoint()
6998                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6999                   DL, VT, V, VMask);
7000   return V;
7001 }
7002
7003 /// \brief Try to emit a blend instruction for a shuffle using bit math.
7004 ///
7005 /// This is used as a fallback approach when first class blend instructions are
7006 /// unavailable. Currently it is only suitable for integer vectors, but could
7007 /// be generalized for floating point vectors if desirable.
7008 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
7009                                             SDValue V2, ArrayRef<int> Mask,
7010                                             SelectionDAG &DAG) {
7011   assert(VT.isInteger() && "Only supports integer vector types!");
7012   MVT EltVT = VT.getVectorElementType();
7013   int NumEltBits = EltVT.getSizeInBits();
7014   SDValue Zero = DAG.getConstant(0, DL, EltVT);
7015   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
7016                                     EltVT);
7017   SmallVector<SDValue, 16> MaskOps;
7018   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7019     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
7020       return SDValue(); // Shuffled input!
7021     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
7022   }
7023
7024   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
7025   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
7026   // We have to cast V2 around.
7027   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
7028   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
7029                                       DAG.getBitcast(MaskVT, V1Mask),
7030                                       DAG.getBitcast(MaskVT, V2)));
7031   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
7032 }
7033
7034 /// \brief Try to emit a blend instruction for a shuffle.
7035 ///
7036 /// This doesn't do any checks for the availability of instructions for blending
7037 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7038 /// be matched in the backend with the type given. What it does check for is
7039 /// that the shuffle mask is a blend, or convertible into a blend with zero.
7040 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7041                                          SDValue V2, ArrayRef<int> Original,
7042                                          const X86Subtarget *Subtarget,
7043                                          SelectionDAG &DAG) {
7044   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7045   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7046   SmallVector<int, 8> Mask(Original.begin(), Original.end());
7047   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7048   bool ForceV1Zero = false, ForceV2Zero = false;
7049
7050   // Attempt to generate the binary blend mask. If an input is zero then
7051   // we can use any lane.
7052   // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
7053   unsigned BlendMask = 0;
7054   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7055     int M = Mask[i];
7056     if (M < 0)
7057       continue;
7058     if (M == i)
7059       continue;
7060     if (M == i + Size) {
7061       BlendMask |= 1u << i;
7062       continue;
7063     }
7064     if (Zeroable[i]) {
7065       if (V1IsZero) {
7066         ForceV1Zero = true;
7067         Mask[i] = i;
7068         continue;
7069       }
7070       if (V2IsZero) {
7071         ForceV2Zero = true;
7072         BlendMask |= 1u << i;
7073         Mask[i] = i + Size;
7074         continue;
7075       }
7076     }
7077     return SDValue(); // Shuffled input!
7078   }
7079
7080   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
7081   if (ForceV1Zero)
7082     V1 = getZeroVector(VT, Subtarget, DAG, DL);
7083   if (ForceV2Zero)
7084     V2 = getZeroVector(VT, Subtarget, DAG, DL);
7085
7086   auto ScaleBlendMask = [](unsigned BlendMask, int Size, int Scale) {
7087     unsigned ScaledMask = 0;
7088     for (int i = 0; i != Size; ++i)
7089       if (BlendMask & (1u << i))
7090         for (int j = 0; j != Scale; ++j)
7091           ScaledMask |= 1u << (i * Scale + j);
7092     return ScaledMask;
7093   };
7094
7095   switch (VT.SimpleTy) {
7096   case MVT::v2f64:
7097   case MVT::v4f32:
7098   case MVT::v4f64:
7099   case MVT::v8f32:
7100     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7101                        DAG.getConstant(BlendMask, DL, MVT::i8));
7102
7103   case MVT::v4i64:
7104   case MVT::v8i32:
7105     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7106     // FALLTHROUGH
7107   case MVT::v2i64:
7108   case MVT::v4i32:
7109     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7110     // that instruction.
7111     if (Subtarget->hasAVX2()) {
7112       // Scale the blend by the number of 32-bit dwords per element.
7113       int Scale =  VT.getScalarSizeInBits() / 32;
7114       BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7115       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7116       V1 = DAG.getBitcast(BlendVT, V1);
7117       V2 = DAG.getBitcast(BlendVT, V2);
7118       return DAG.getBitcast(
7119           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7120                           DAG.getConstant(BlendMask, DL, MVT::i8)));
7121     }
7122     // FALLTHROUGH
7123   case MVT::v8i16: {
7124     // For integer shuffles we need to expand the mask and cast the inputs to
7125     // v8i16s prior to blending.
7126     int Scale = 8 / VT.getVectorNumElements();
7127     BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7128     V1 = DAG.getBitcast(MVT::v8i16, V1);
7129     V2 = DAG.getBitcast(MVT::v8i16, V2);
7130     return DAG.getBitcast(VT,
7131                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7132                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
7133   }
7134
7135   case MVT::v16i16: {
7136     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7137     SmallVector<int, 8> RepeatedMask;
7138     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7139       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7140       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7141       BlendMask = 0;
7142       for (int i = 0; i < 8; ++i)
7143         if (RepeatedMask[i] >= 16)
7144           BlendMask |= 1u << i;
7145       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7146                          DAG.getConstant(BlendMask, DL, MVT::i8));
7147     }
7148   }
7149     // FALLTHROUGH
7150   case MVT::v16i8:
7151   case MVT::v32i8: {
7152     assert((VT.is128BitVector() || Subtarget->hasAVX2()) &&
7153            "256-bit byte-blends require AVX2 support!");
7154
7155     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
7156     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
7157       return Masked;
7158
7159     // Scale the blend by the number of bytes per element.
7160     int Scale = VT.getScalarSizeInBits() / 8;
7161
7162     // This form of blend is always done on bytes. Compute the byte vector
7163     // type.
7164     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
7165
7166     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7167     // mix of LLVM's code generator and the x86 backend. We tell the code
7168     // generator that boolean values in the elements of an x86 vector register
7169     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7170     // mapping a select to operand #1, and 'false' mapping to operand #2. The
7171     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7172     // of the element (the remaining are ignored) and 0 in that high bit would
7173     // mean operand #1 while 1 in the high bit would mean operand #2. So while
7174     // the LLVM model for boolean values in vector elements gets the relevant
7175     // bit set, it is set backwards and over constrained relative to x86's
7176     // actual model.
7177     SmallVector<SDValue, 32> VSELECTMask;
7178     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7179       for (int j = 0; j < Scale; ++j)
7180         VSELECTMask.push_back(
7181             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7182                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7183                                           MVT::i8));
7184
7185     V1 = DAG.getBitcast(BlendVT, V1);
7186     V2 = DAG.getBitcast(BlendVT, V2);
7187     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7188                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
7189                                                       BlendVT, VSELECTMask),
7190                                           V1, V2));
7191   }
7192
7193   default:
7194     llvm_unreachable("Not a supported integer vector type!");
7195   }
7196 }
7197
7198 /// \brief Try to lower as a blend of elements from two inputs followed by
7199 /// a single-input permutation.
7200 ///
7201 /// This matches the pattern where we can blend elements from two inputs and
7202 /// then reduce the shuffle to a single-input permutation.
7203 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7204                                                    SDValue V2,
7205                                                    ArrayRef<int> Mask,
7206                                                    SelectionDAG &DAG) {
7207   // We build up the blend mask while checking whether a blend is a viable way
7208   // to reduce the shuffle.
7209   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7210   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7211
7212   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7213     if (Mask[i] < 0)
7214       continue;
7215
7216     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7217
7218     if (BlendMask[Mask[i] % Size] == -1)
7219       BlendMask[Mask[i] % Size] = Mask[i];
7220     else if (BlendMask[Mask[i] % Size] != Mask[i])
7221       return SDValue(); // Can't blend in the needed input!
7222
7223     PermuteMask[i] = Mask[i] % Size;
7224   }
7225
7226   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7227   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7228 }
7229
7230 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7231 /// blends and permutes.
7232 ///
7233 /// This matches the extremely common pattern for handling combined
7234 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7235 /// operations. It will try to pick the best arrangement of shuffles and
7236 /// blends.
7237 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7238                                                           SDValue V1,
7239                                                           SDValue V2,
7240                                                           ArrayRef<int> Mask,
7241                                                           SelectionDAG &DAG) {
7242   // Shuffle the input elements into the desired positions in V1 and V2 and
7243   // blend them together.
7244   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7245   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7246   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7247   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7248     if (Mask[i] >= 0 && Mask[i] < Size) {
7249       V1Mask[i] = Mask[i];
7250       BlendMask[i] = i;
7251     } else if (Mask[i] >= Size) {
7252       V2Mask[i] = Mask[i] - Size;
7253       BlendMask[i] = i + Size;
7254     }
7255
7256   // Try to lower with the simpler initial blend strategy unless one of the
7257   // input shuffles would be a no-op. We prefer to shuffle inputs as the
7258   // shuffle may be able to fold with a load or other benefit. However, when
7259   // we'll have to do 2x as many shuffles in order to achieve this, blending
7260   // first is a better strategy.
7261   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7262     if (SDValue BlendPerm =
7263             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7264       return BlendPerm;
7265
7266   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7267   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7268   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7269 }
7270
7271 /// \brief Try to lower a vector shuffle as a byte rotation.
7272 ///
7273 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7274 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7275 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7276 /// try to generically lower a vector shuffle through such an pattern. It
7277 /// does not check for the profitability of lowering either as PALIGNR or
7278 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7279 /// This matches shuffle vectors that look like:
7280 ///
7281 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7282 ///
7283 /// Essentially it concatenates V1 and V2, shifts right by some number of
7284 /// elements, and takes the low elements as the result. Note that while this is
7285 /// specified as a *right shift* because x86 is little-endian, it is a *left
7286 /// rotate* of the vector lanes.
7287 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7288                                               SDValue V2,
7289                                               ArrayRef<int> Mask,
7290                                               const X86Subtarget *Subtarget,
7291                                               SelectionDAG &DAG) {
7292   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7293
7294   int NumElts = Mask.size();
7295   int NumLanes = VT.getSizeInBits() / 128;
7296   int NumLaneElts = NumElts / NumLanes;
7297
7298   // We need to detect various ways of spelling a rotation:
7299   //   [11, 12, 13, 14, 15,  0,  1,  2]
7300   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7301   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7302   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7303   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7304   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7305   int Rotation = 0;
7306   SDValue Lo, Hi;
7307   for (int l = 0; l < NumElts; l += NumLaneElts) {
7308     for (int i = 0; i < NumLaneElts; ++i) {
7309       if (Mask[l + i] == -1)
7310         continue;
7311       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7312
7313       // Get the mod-Size index and lane correct it.
7314       int LaneIdx = (Mask[l + i] % NumElts) - l;
7315       // Make sure it was in this lane.
7316       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7317         return SDValue();
7318
7319       // Determine where a rotated vector would have started.
7320       int StartIdx = i - LaneIdx;
7321       if (StartIdx == 0)
7322         // The identity rotation isn't interesting, stop.
7323         return SDValue();
7324
7325       // If we found the tail of a vector the rotation must be the missing
7326       // front. If we found the head of a vector, it must be how much of the
7327       // head.
7328       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7329
7330       if (Rotation == 0)
7331         Rotation = CandidateRotation;
7332       else if (Rotation != CandidateRotation)
7333         // The rotations don't match, so we can't match this mask.
7334         return SDValue();
7335
7336       // Compute which value this mask is pointing at.
7337       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7338
7339       // Compute which of the two target values this index should be assigned
7340       // to. This reflects whether the high elements are remaining or the low
7341       // elements are remaining.
7342       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7343
7344       // Either set up this value if we've not encountered it before, or check
7345       // that it remains consistent.
7346       if (!TargetV)
7347         TargetV = MaskV;
7348       else if (TargetV != MaskV)
7349         // This may be a rotation, but it pulls from the inputs in some
7350         // unsupported interleaving.
7351         return SDValue();
7352     }
7353   }
7354
7355   // Check that we successfully analyzed the mask, and normalize the results.
7356   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7357   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7358   if (!Lo)
7359     Lo = Hi;
7360   else if (!Hi)
7361     Hi = Lo;
7362
7363   // The actual rotate instruction rotates bytes, so we need to scale the
7364   // rotation based on how many bytes are in the vector lane.
7365   int Scale = 16 / NumLaneElts;
7366
7367   // SSSE3 targets can use the palignr instruction.
7368   if (Subtarget->hasSSSE3()) {
7369     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7370     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7371     Lo = DAG.getBitcast(AlignVT, Lo);
7372     Hi = DAG.getBitcast(AlignVT, Hi);
7373
7374     return DAG.getBitcast(
7375         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7376                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7377   }
7378
7379   assert(VT.is128BitVector() &&
7380          "Rotate-based lowering only supports 128-bit lowering!");
7381   assert(Mask.size() <= 16 &&
7382          "Can shuffle at most 16 bytes in a 128-bit vector!");
7383
7384   // Default SSE2 implementation
7385   int LoByteShift = 16 - Rotation * Scale;
7386   int HiByteShift = Rotation * Scale;
7387
7388   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7389   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7390   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7391
7392   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7393                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7394   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7395                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7396   return DAG.getBitcast(VT,
7397                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7398 }
7399
7400 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7401 ///
7402 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7403 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7404 /// matches elements from one of the input vectors shuffled to the left or
7405 /// right with zeroable elements 'shifted in'. It handles both the strictly
7406 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7407 /// quad word lane.
7408 ///
7409 /// PSHL : (little-endian) left bit shift.
7410 /// [ zz, 0, zz,  2 ]
7411 /// [ -1, 4, zz, -1 ]
7412 /// PSRL : (little-endian) right bit shift.
7413 /// [  1, zz,  3, zz]
7414 /// [ -1, -1,  7, zz]
7415 /// PSLLDQ : (little-endian) left byte shift
7416 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7417 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7418 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7419 /// PSRLDQ : (little-endian) right byte shift
7420 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7421 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7422 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7423 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7424                                          SDValue V2, ArrayRef<int> Mask,
7425                                          SelectionDAG &DAG) {
7426   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7427
7428   int Size = Mask.size();
7429   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7430
7431   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7432     for (int i = 0; i < Size; i += Scale)
7433       for (int j = 0; j < Shift; ++j)
7434         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7435           return false;
7436
7437     return true;
7438   };
7439
7440   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7441     for (int i = 0; i != Size; i += Scale) {
7442       unsigned Pos = Left ? i + Shift : i;
7443       unsigned Low = Left ? i : i + Shift;
7444       unsigned Len = Scale - Shift;
7445       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7446                                       Low + (V == V1 ? 0 : Size)))
7447         return SDValue();
7448     }
7449
7450     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7451     bool ByteShift = ShiftEltBits > 64;
7452     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7453                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7454     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7455
7456     // Normalize the scale for byte shifts to still produce an i64 element
7457     // type.
7458     Scale = ByteShift ? Scale / 2 : Scale;
7459
7460     // We need to round trip through the appropriate type for the shift.
7461     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7462     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7463     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7464            "Illegal integer vector type");
7465     V = DAG.getBitcast(ShiftVT, V);
7466
7467     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7468                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7469     return DAG.getBitcast(VT, V);
7470   };
7471
7472   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7473   // keep doubling the size of the integer elements up to that. We can
7474   // then shift the elements of the integer vector by whole multiples of
7475   // their width within the elements of the larger integer vector. Test each
7476   // multiple to see if we can find a match with the moved element indices
7477   // and that the shifted in elements are all zeroable.
7478   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7479     for (int Shift = 1; Shift != Scale; ++Shift)
7480       for (bool Left : {true, false})
7481         if (CheckZeros(Shift, Scale, Left))
7482           for (SDValue V : {V1, V2})
7483             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7484               return Match;
7485
7486   // no match
7487   return SDValue();
7488 }
7489
7490 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7491 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7492                                            SDValue V2, ArrayRef<int> Mask,
7493                                            SelectionDAG &DAG) {
7494   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7495   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7496
7497   int Size = Mask.size();
7498   int HalfSize = Size / 2;
7499   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7500
7501   // Upper half must be undefined.
7502   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7503     return SDValue();
7504
7505   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7506   // Remainder of lower half result is zero and upper half is all undef.
7507   auto LowerAsEXTRQ = [&]() {
7508     // Determine the extraction length from the part of the
7509     // lower half that isn't zeroable.
7510     int Len = HalfSize;
7511     for (; Len > 0; --Len)
7512       if (!Zeroable[Len - 1])
7513         break;
7514     assert(Len > 0 && "Zeroable shuffle mask");
7515
7516     // Attempt to match first Len sequential elements from the lower half.
7517     SDValue Src;
7518     int Idx = -1;
7519     for (int i = 0; i != Len; ++i) {
7520       int M = Mask[i];
7521       if (M < 0)
7522         continue;
7523       SDValue &V = (M < Size ? V1 : V2);
7524       M = M % Size;
7525
7526       // The extracted elements must start at a valid index and all mask
7527       // elements must be in the lower half.
7528       if (i > M || M >= HalfSize)
7529         return SDValue();
7530
7531       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7532         Src = V;
7533         Idx = M - i;
7534         continue;
7535       }
7536       return SDValue();
7537     }
7538
7539     if (Idx < 0)
7540       return SDValue();
7541
7542     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7543     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7544     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7545     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7546                        DAG.getConstant(BitLen, DL, MVT::i8),
7547                        DAG.getConstant(BitIdx, DL, MVT::i8));
7548   };
7549
7550   if (SDValue ExtrQ = LowerAsEXTRQ())
7551     return ExtrQ;
7552
7553   // INSERTQ: Extract lowest Len elements from lower half of second source and
7554   // insert over first source, starting at Idx.
7555   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7556   auto LowerAsInsertQ = [&]() {
7557     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7558       SDValue Base;
7559
7560       // Attempt to match first source from mask before insertion point.
7561       if (isUndefInRange(Mask, 0, Idx)) {
7562         /* EMPTY */
7563       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7564         Base = V1;
7565       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7566         Base = V2;
7567       } else {
7568         continue;
7569       }
7570
7571       // Extend the extraction length looking to match both the insertion of
7572       // the second source and the remaining elements of the first.
7573       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7574         SDValue Insert;
7575         int Len = Hi - Idx;
7576
7577         // Match insertion.
7578         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7579           Insert = V1;
7580         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7581           Insert = V2;
7582         } else {
7583           continue;
7584         }
7585
7586         // Match the remaining elements of the lower half.
7587         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7588           /* EMPTY */
7589         } else if ((!Base || (Base == V1)) &&
7590                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7591           Base = V1;
7592         } else if ((!Base || (Base == V2)) &&
7593                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7594                                               Size + Hi)) {
7595           Base = V2;
7596         } else {
7597           continue;
7598         }
7599
7600         // We may not have a base (first source) - this can safely be undefined.
7601         if (!Base)
7602           Base = DAG.getUNDEF(VT);
7603
7604         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7605         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7606         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7607                            DAG.getConstant(BitLen, DL, MVT::i8),
7608                            DAG.getConstant(BitIdx, DL, MVT::i8));
7609       }
7610     }
7611
7612     return SDValue();
7613   };
7614
7615   if (SDValue InsertQ = LowerAsInsertQ())
7616     return InsertQ;
7617
7618   return SDValue();
7619 }
7620
7621 /// \brief Lower a vector shuffle as a zero or any extension.
7622 ///
7623 /// Given a specific number of elements, element bit width, and extension
7624 /// stride, produce either a zero or any extension based on the available
7625 /// features of the subtarget. The extended elements are consecutive and
7626 /// begin and can start from an offseted element index in the input; to
7627 /// avoid excess shuffling the offset must either being in the bottom lane
7628 /// or at the start of a higher lane. All extended elements must be from
7629 /// the same lane.
7630 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7631     SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7632     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7633   assert(Scale > 1 && "Need a scale to extend.");
7634   int EltBits = VT.getScalarSizeInBits();
7635   int NumElements = VT.getVectorNumElements();
7636   int NumEltsPerLane = 128 / EltBits;
7637   int OffsetLane = Offset / NumEltsPerLane;
7638   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7639          "Only 8, 16, and 32 bit elements can be extended.");
7640   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7641   assert(0 <= Offset && "Extension offset must be positive.");
7642   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7643          "Extension offset must be in the first lane or start an upper lane.");
7644
7645   // Check that an index is in same lane as the base offset.
7646   auto SafeOffset = [&](int Idx) {
7647     return OffsetLane == (Idx / NumEltsPerLane);
7648   };
7649
7650   // Shift along an input so that the offset base moves to the first element.
7651   auto ShuffleOffset = [&](SDValue V) {
7652     if (!Offset)
7653       return V;
7654
7655     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7656     for (int i = 0; i * Scale < NumElements; ++i) {
7657       int SrcIdx = i + Offset;
7658       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7659     }
7660     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7661   };
7662
7663   // Found a valid zext mask! Try various lowering strategies based on the
7664   // input type and available ISA extensions.
7665   if (Subtarget->hasSSE41()) {
7666     // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7667     // PUNPCK will catch this in a later shuffle match.
7668     if (Offset && Scale == 2 && VT.is128BitVector())
7669       return SDValue();
7670     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7671                                  NumElements / Scale);
7672     InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7673     return DAG.getBitcast(VT, InputV);
7674   }
7675
7676   assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
7677
7678   // For any extends we can cheat for larger element sizes and use shuffle
7679   // instructions that can fold with a load and/or copy.
7680   if (AnyExt && EltBits == 32) {
7681     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7682                          -1};
7683     return DAG.getBitcast(
7684         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7685                         DAG.getBitcast(MVT::v4i32, InputV),
7686                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7687   }
7688   if (AnyExt && EltBits == 16 && Scale > 2) {
7689     int PSHUFDMask[4] = {Offset / 2, -1,
7690                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7691     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7692                          DAG.getBitcast(MVT::v4i32, InputV),
7693                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7694     int PSHUFWMask[4] = {1, -1, -1, -1};
7695     unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7696     return DAG.getBitcast(
7697         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7698                         DAG.getBitcast(MVT::v8i16, InputV),
7699                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7700   }
7701
7702   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7703   // to 64-bits.
7704   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7705     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7706     assert(VT.is128BitVector() && "Unexpected vector width!");
7707
7708     int LoIdx = Offset * EltBits;
7709     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7710                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7711                                          DAG.getConstant(EltBits, DL, MVT::i8),
7712                                          DAG.getConstant(LoIdx, DL, MVT::i8)));
7713
7714     if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7715         !SafeOffset(Offset + 1))
7716       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7717
7718     int HiIdx = (Offset + 1) * EltBits;
7719     SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7720                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7721                                          DAG.getConstant(EltBits, DL, MVT::i8),
7722                                          DAG.getConstant(HiIdx, DL, MVT::i8)));
7723     return DAG.getNode(ISD::BITCAST, DL, VT,
7724                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7725   }
7726
7727   // If this would require more than 2 unpack instructions to expand, use
7728   // pshufb when available. We can only use more than 2 unpack instructions
7729   // when zero extending i8 elements which also makes it easier to use pshufb.
7730   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7731     assert(NumElements == 16 && "Unexpected byte vector width!");
7732     SDValue PSHUFBMask[16];
7733     for (int i = 0; i < 16; ++i) {
7734       int Idx = Offset + (i / Scale);
7735       PSHUFBMask[i] = DAG.getConstant(
7736           (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7737     }
7738     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7739     return DAG.getBitcast(VT,
7740                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7741                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7742                                                   MVT::v16i8, PSHUFBMask)));
7743   }
7744
7745   // If we are extending from an offset, ensure we start on a boundary that
7746   // we can unpack from.
7747   int AlignToUnpack = Offset % (NumElements / Scale);
7748   if (AlignToUnpack) {
7749     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7750     for (int i = AlignToUnpack; i < NumElements; ++i)
7751       ShMask[i - AlignToUnpack] = i;
7752     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7753     Offset -= AlignToUnpack;
7754   }
7755
7756   // Otherwise emit a sequence of unpacks.
7757   do {
7758     unsigned UnpackLoHi = X86ISD::UNPCKL;
7759     if (Offset >= (NumElements / 2)) {
7760       UnpackLoHi = X86ISD::UNPCKH;
7761       Offset -= (NumElements / 2);
7762     }
7763
7764     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7765     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7766                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7767     InputV = DAG.getBitcast(InputVT, InputV);
7768     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7769     Scale /= 2;
7770     EltBits *= 2;
7771     NumElements /= 2;
7772   } while (Scale > 1);
7773   return DAG.getBitcast(VT, InputV);
7774 }
7775
7776 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7777 ///
7778 /// This routine will try to do everything in its power to cleverly lower
7779 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7780 /// check for the profitability of this lowering,  it tries to aggressively
7781 /// match this pattern. It will use all of the micro-architectural details it
7782 /// can to emit an efficient lowering. It handles both blends with all-zero
7783 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7784 /// masking out later).
7785 ///
7786 /// The reason we have dedicated lowering for zext-style shuffles is that they
7787 /// are both incredibly common and often quite performance sensitive.
7788 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7789     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7790     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7791   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7792
7793   int Bits = VT.getSizeInBits();
7794   int NumLanes = Bits / 128;
7795   int NumElements = VT.getVectorNumElements();
7796   int NumEltsPerLane = NumElements / NumLanes;
7797   assert(VT.getScalarSizeInBits() <= 32 &&
7798          "Exceeds 32-bit integer zero extension limit");
7799   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7800
7801   // Define a helper function to check a particular ext-scale and lower to it if
7802   // valid.
7803   auto Lower = [&](int Scale) -> SDValue {
7804     SDValue InputV;
7805     bool AnyExt = true;
7806     int Offset = 0;
7807     int Matches = 0;
7808     for (int i = 0; i < NumElements; ++i) {
7809       int M = Mask[i];
7810       if (M == -1)
7811         continue; // Valid anywhere but doesn't tell us anything.
7812       if (i % Scale != 0) {
7813         // Each of the extended elements need to be zeroable.
7814         if (!Zeroable[i])
7815           return SDValue();
7816
7817         // We no longer are in the anyext case.
7818         AnyExt = false;
7819         continue;
7820       }
7821
7822       // Each of the base elements needs to be consecutive indices into the
7823       // same input vector.
7824       SDValue V = M < NumElements ? V1 : V2;
7825       M = M % NumElements;
7826       if (!InputV) {
7827         InputV = V;
7828         Offset = M - (i / Scale);
7829       } else if (InputV != V)
7830         return SDValue(); // Flip-flopping inputs.
7831
7832       // Offset must start in the lowest 128-bit lane or at the start of an
7833       // upper lane.
7834       // FIXME: Is it ever worth allowing a negative base offset?
7835       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7836             (Offset % NumEltsPerLane) == 0))
7837         return SDValue();
7838
7839       // If we are offsetting, all referenced entries must come from the same
7840       // lane.
7841       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7842         return SDValue();
7843
7844       if ((M % NumElements) != (Offset + (i / Scale)))
7845         return SDValue(); // Non-consecutive strided elements.
7846       Matches++;
7847     }
7848
7849     // If we fail to find an input, we have a zero-shuffle which should always
7850     // have already been handled.
7851     // FIXME: Maybe handle this here in case during blending we end up with one?
7852     if (!InputV)
7853       return SDValue();
7854
7855     // If we are offsetting, don't extend if we only match a single input, we
7856     // can always do better by using a basic PSHUF or PUNPCK.
7857     if (Offset != 0 && Matches < 2)
7858       return SDValue();
7859
7860     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7861         DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7862   };
7863
7864   // The widest scale possible for extending is to a 64-bit integer.
7865   assert(Bits % 64 == 0 &&
7866          "The number of bits in a vector must be divisible by 64 on x86!");
7867   int NumExtElements = Bits / 64;
7868
7869   // Each iteration, try extending the elements half as much, but into twice as
7870   // many elements.
7871   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7872     assert(NumElements % NumExtElements == 0 &&
7873            "The input vector size must be divisible by the extended size.");
7874     if (SDValue V = Lower(NumElements / NumExtElements))
7875       return V;
7876   }
7877
7878   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7879   if (Bits != 128)
7880     return SDValue();
7881
7882   // Returns one of the source operands if the shuffle can be reduced to a
7883   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7884   auto CanZExtLowHalf = [&]() {
7885     for (int i = NumElements / 2; i != NumElements; ++i)
7886       if (!Zeroable[i])
7887         return SDValue();
7888     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7889       return V1;
7890     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7891       return V2;
7892     return SDValue();
7893   };
7894
7895   if (SDValue V = CanZExtLowHalf()) {
7896     V = DAG.getBitcast(MVT::v2i64, V);
7897     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7898     return DAG.getBitcast(VT, V);
7899   }
7900
7901   // No viable ext lowering found.
7902   return SDValue();
7903 }
7904
7905 /// \brief Try to get a scalar value for a specific element of a vector.
7906 ///
7907 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7908 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7909                                               SelectionDAG &DAG) {
7910   MVT VT = V.getSimpleValueType();
7911   MVT EltVT = VT.getVectorElementType();
7912   while (V.getOpcode() == ISD::BITCAST)
7913     V = V.getOperand(0);
7914   // If the bitcasts shift the element size, we can't extract an equivalent
7915   // element from it.
7916   MVT NewVT = V.getSimpleValueType();
7917   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7918     return SDValue();
7919
7920   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7921       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7922     // Ensure the scalar operand is the same size as the destination.
7923     // FIXME: Add support for scalar truncation where possible.
7924     SDValue S = V.getOperand(Idx);
7925     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7926       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7927   }
7928
7929   return SDValue();
7930 }
7931
7932 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7933 ///
7934 /// This is particularly important because the set of instructions varies
7935 /// significantly based on whether the operand is a load or not.
7936 static bool isShuffleFoldableLoad(SDValue V) {
7937   while (V.getOpcode() == ISD::BITCAST)
7938     V = V.getOperand(0);
7939
7940   return ISD::isNON_EXTLoad(V.getNode());
7941 }
7942
7943 /// \brief Try to lower insertion of a single element into a zero vector.
7944 ///
7945 /// This is a common pattern that we have especially efficient patterns to lower
7946 /// across all subtarget feature sets.
7947 static SDValue lowerVectorShuffleAsElementInsertion(
7948     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7949     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7950   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7951   MVT ExtVT = VT;
7952   MVT EltVT = VT.getVectorElementType();
7953
7954   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7955                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7956                 Mask.begin();
7957   bool IsV1Zeroable = true;
7958   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7959     if (i != V2Index && !Zeroable[i]) {
7960       IsV1Zeroable = false;
7961       break;
7962     }
7963
7964   // Check for a single input from a SCALAR_TO_VECTOR node.
7965   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7966   // all the smarts here sunk into that routine. However, the current
7967   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7968   // vector shuffle lowering is dead.
7969   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7970                                                DAG);
7971   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7972     // We need to zext the scalar if it is smaller than an i32.
7973     V2S = DAG.getBitcast(EltVT, V2S);
7974     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7975       // Using zext to expand a narrow element won't work for non-zero
7976       // insertions.
7977       if (!IsV1Zeroable)
7978         return SDValue();
7979
7980       // Zero-extend directly to i32.
7981       ExtVT = MVT::v4i32;
7982       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7983     }
7984     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7985   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7986              EltVT == MVT::i16) {
7987     // Either not inserting from the low element of the input or the input
7988     // element size is too small to use VZEXT_MOVL to clear the high bits.
7989     return SDValue();
7990   }
7991
7992   if (!IsV1Zeroable) {
7993     // If V1 can't be treated as a zero vector we have fewer options to lower
7994     // this. We can't support integer vectors or non-zero targets cheaply, and
7995     // the V1 elements can't be permuted in any way.
7996     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7997     if (!VT.isFloatingPoint() || V2Index != 0)
7998       return SDValue();
7999     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
8000     V1Mask[V2Index] = -1;
8001     if (!isNoopShuffleMask(V1Mask))
8002       return SDValue();
8003     // This is essentially a special case blend operation, but if we have
8004     // general purpose blend operations, they are always faster. Bail and let
8005     // the rest of the lowering handle these as blends.
8006     if (Subtarget->hasSSE41())
8007       return SDValue();
8008
8009     // Otherwise, use MOVSD or MOVSS.
8010     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
8011            "Only two types of floating point element types to handle!");
8012     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
8013                        ExtVT, V1, V2);
8014   }
8015
8016   // This lowering only works for the low element with floating point vectors.
8017   if (VT.isFloatingPoint() && V2Index != 0)
8018     return SDValue();
8019
8020   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
8021   if (ExtVT != VT)
8022     V2 = DAG.getBitcast(VT, V2);
8023
8024   if (V2Index != 0) {
8025     // If we have 4 or fewer lanes we can cheaply shuffle the element into
8026     // the desired position. Otherwise it is more efficient to do a vector
8027     // shift left. We know that we can do a vector shift left because all
8028     // the inputs are zero.
8029     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
8030       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
8031       V2Shuffle[V2Index] = 0;
8032       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
8033     } else {
8034       V2 = DAG.getBitcast(MVT::v2i64, V2);
8035       V2 = DAG.getNode(
8036           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
8037           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
8038                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
8039                               DAG.getDataLayout(), VT)));
8040       V2 = DAG.getBitcast(VT, V2);
8041     }
8042   }
8043   return V2;
8044 }
8045
8046 /// \brief Try to lower broadcast of a single - truncated - integer element,
8047 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
8048 ///
8049 /// This assumes we have AVX2.
8050 static SDValue lowerVectorShuffleAsTruncBroadcast(SDLoc DL, MVT VT, SDValue V0,
8051                                                   int BroadcastIdx,
8052                                                   const X86Subtarget *Subtarget,
8053                                                   SelectionDAG &DAG) {
8054   assert(Subtarget->hasAVX2() &&
8055          "We can only lower integer broadcasts with AVX2!");
8056
8057   EVT EltVT = VT.getVectorElementType();
8058   EVT V0VT = V0.getValueType();
8059
8060   assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
8061   assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
8062
8063   EVT V0EltVT = V0VT.getVectorElementType();
8064   if (!V0EltVT.isInteger())
8065     return SDValue();
8066
8067   const unsigned EltSize = EltVT.getSizeInBits();
8068   const unsigned V0EltSize = V0EltVT.getSizeInBits();
8069
8070   // This is only a truncation if the original element type is larger.
8071   if (V0EltSize <= EltSize)
8072     return SDValue();
8073
8074   assert(((V0EltSize % EltSize) == 0) &&
8075          "Scalar type sizes must all be powers of 2 on x86!");
8076
8077   const unsigned V0Opc = V0.getOpcode();
8078   const unsigned Scale = V0EltSize / EltSize;
8079   const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
8080
8081   if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
8082       V0Opc != ISD::BUILD_VECTOR)
8083     return SDValue();
8084
8085   SDValue Scalar = V0.getOperand(V0BroadcastIdx);
8086
8087   // If we're extracting non-least-significant bits, shift so we can truncate.
8088   // Hopefully, we can fold away the trunc/srl/load into the broadcast.
8089   // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
8090   // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
8091   if (const int OffsetIdx = BroadcastIdx % Scale)
8092     Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
8093             DAG.getConstant(OffsetIdx * EltSize, DL, Scalar.getValueType()));
8094
8095   return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
8096                      DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
8097 }
8098
8099 /// \brief Try to lower broadcast of a single element.
8100 ///
8101 /// For convenience, this code also bundles all of the subtarget feature set
8102 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8103 /// a convenient way to factor it out.
8104 /// FIXME: This is very similar to LowerVectorBroadcast - can we merge them?
8105 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
8106                                              ArrayRef<int> Mask,
8107                                              const X86Subtarget *Subtarget,
8108                                              SelectionDAG &DAG) {
8109   if (!Subtarget->hasAVX())
8110     return SDValue();
8111   if (VT.isInteger() && !Subtarget->hasAVX2())
8112     return SDValue();
8113
8114   // Check that the mask is a broadcast.
8115   int BroadcastIdx = -1;
8116   for (int M : Mask)
8117     if (M >= 0 && BroadcastIdx == -1)
8118       BroadcastIdx = M;
8119     else if (M >= 0 && M != BroadcastIdx)
8120       return SDValue();
8121
8122   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8123                                             "a sorted mask where the broadcast "
8124                                             "comes from V1.");
8125
8126   // Go up the chain of (vector) values to find a scalar load that we can
8127   // combine with the broadcast.
8128   for (;;) {
8129     switch (V.getOpcode()) {
8130     case ISD::CONCAT_VECTORS: {
8131       int OperandSize = Mask.size() / V.getNumOperands();
8132       V = V.getOperand(BroadcastIdx / OperandSize);
8133       BroadcastIdx %= OperandSize;
8134       continue;
8135     }
8136
8137     case ISD::INSERT_SUBVECTOR: {
8138       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8139       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8140       if (!ConstantIdx)
8141         break;
8142
8143       int BeginIdx = (int)ConstantIdx->getZExtValue();
8144       int EndIdx =
8145           BeginIdx + (int)VInner.getSimpleValueType().getVectorNumElements();
8146       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8147         BroadcastIdx -= BeginIdx;
8148         V = VInner;
8149       } else {
8150         V = VOuter;
8151       }
8152       continue;
8153     }
8154     }
8155     break;
8156   }
8157
8158   // Check if this is a broadcast of a scalar. We special case lowering
8159   // for scalars so that we can more effectively fold with loads.
8160   // First, look through bitcast: if the original value has a larger element
8161   // type than the shuffle, the broadcast element is in essence truncated.
8162   // Make that explicit to ease folding.
8163   if (V.getOpcode() == ISD::BITCAST && VT.isInteger())
8164     if (SDValue TruncBroadcast = lowerVectorShuffleAsTruncBroadcast(
8165             DL, VT, V.getOperand(0), BroadcastIdx, Subtarget, DAG))
8166       return TruncBroadcast;
8167
8168   // Also check the simpler case, where we can directly reuse the scalar.
8169   if (V.getOpcode() == ISD::BUILD_VECTOR ||
8170       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8171     V = V.getOperand(BroadcastIdx);
8172
8173     // If the scalar isn't a load, we can't broadcast from it in AVX1.
8174     // Only AVX2 has register broadcasts.
8175     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8176       return SDValue();
8177   } else if (MayFoldLoad(V) && !cast<LoadSDNode>(V)->isVolatile()) {
8178     // If we are broadcasting a load that is only used by the shuffle
8179     // then we can reduce the vector load to the broadcasted scalar load.
8180     LoadSDNode *Ld = cast<LoadSDNode>(V);
8181     SDValue BaseAddr = Ld->getOperand(1);
8182     EVT AddrVT = BaseAddr.getValueType();
8183     EVT SVT = VT.getScalarType();
8184     unsigned Offset = BroadcastIdx * SVT.getStoreSize();
8185     SDValue NewAddr = DAG.getNode(
8186         ISD::ADD, DL, AddrVT, BaseAddr,
8187         DAG.getConstant(Offset, DL, AddrVT));
8188     V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
8189                     DAG.getMachineFunction().getMachineMemOperand(
8190                         Ld->getMemOperand(), Offset, SVT.getStoreSize()));
8191   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8192     // We can't broadcast from a vector register without AVX2, and we can only
8193     // broadcast from the zero-element of a vector register.
8194     return SDValue();
8195   }
8196
8197   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
8198 }
8199
8200 // Check for whether we can use INSERTPS to perform the shuffle. We only use
8201 // INSERTPS when the V1 elements are already in the correct locations
8202 // because otherwise we can just always use two SHUFPS instructions which
8203 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
8204 // perform INSERTPS if a single V1 element is out of place and all V2
8205 // elements are zeroable.
8206 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
8207                                             ArrayRef<int> Mask,
8208                                             SelectionDAG &DAG) {
8209   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8210   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8211   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8212   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8213
8214   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8215
8216   unsigned ZMask = 0;
8217   int V1DstIndex = -1;
8218   int V2DstIndex = -1;
8219   bool V1UsedInPlace = false;
8220
8221   for (int i = 0; i < 4; ++i) {
8222     // Synthesize a zero mask from the zeroable elements (includes undefs).
8223     if (Zeroable[i]) {
8224       ZMask |= 1 << i;
8225       continue;
8226     }
8227
8228     // Flag if we use any V1 inputs in place.
8229     if (i == Mask[i]) {
8230       V1UsedInPlace = true;
8231       continue;
8232     }
8233
8234     // We can only insert a single non-zeroable element.
8235     if (V1DstIndex != -1 || V2DstIndex != -1)
8236       return SDValue();
8237
8238     if (Mask[i] < 4) {
8239       // V1 input out of place for insertion.
8240       V1DstIndex = i;
8241     } else {
8242       // V2 input for insertion.
8243       V2DstIndex = i;
8244     }
8245   }
8246
8247   // Don't bother if we have no (non-zeroable) element for insertion.
8248   if (V1DstIndex == -1 && V2DstIndex == -1)
8249     return SDValue();
8250
8251   // Determine element insertion src/dst indices. The src index is from the
8252   // start of the inserted vector, not the start of the concatenated vector.
8253   unsigned V2SrcIndex = 0;
8254   if (V1DstIndex != -1) {
8255     // If we have a V1 input out of place, we use V1 as the V2 element insertion
8256     // and don't use the original V2 at all.
8257     V2SrcIndex = Mask[V1DstIndex];
8258     V2DstIndex = V1DstIndex;
8259     V2 = V1;
8260   } else {
8261     V2SrcIndex = Mask[V2DstIndex] - 4;
8262   }
8263
8264   // If no V1 inputs are used in place, then the result is created only from
8265   // the zero mask and the V2 insertion - so remove V1 dependency.
8266   if (!V1UsedInPlace)
8267     V1 = DAG.getUNDEF(MVT::v4f32);
8268
8269   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8270   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8271
8272   // Insert the V2 element into the desired position.
8273   SDLoc DL(Op);
8274   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8275                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
8276 }
8277
8278 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8279 /// UNPCK instruction.
8280 ///
8281 /// This specifically targets cases where we end up with alternating between
8282 /// the two inputs, and so can permute them into something that feeds a single
8283 /// UNPCK instruction. Note that this routine only targets integer vectors
8284 /// because for floating point vectors we have a generalized SHUFPS lowering
8285 /// strategy that handles everything that doesn't *exactly* match an unpack,
8286 /// making this clever lowering unnecessary.
8287 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8288                                                     SDValue V1, SDValue V2,
8289                                                     ArrayRef<int> Mask,
8290                                                     SelectionDAG &DAG) {
8291   assert(!VT.isFloatingPoint() &&
8292          "This routine only supports integer vectors.");
8293   assert(!isSingleInputShuffleMask(Mask) &&
8294          "This routine should only be used when blending two inputs.");
8295   assert(Mask.size() >= 2 && "Single element masks are invalid.");
8296
8297   int Size = Mask.size();
8298
8299   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8300     return M >= 0 && M % Size < Size / 2;
8301   });
8302   int NumHiInputs = std::count_if(
8303       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8304
8305   bool UnpackLo = NumLoInputs >= NumHiInputs;
8306
8307   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8308     SmallVector<int, 32> V1Mask(Mask.size(), -1);
8309     SmallVector<int, 32> V2Mask(Mask.size(), -1);
8310
8311     for (int i = 0; i < Size; ++i) {
8312       if (Mask[i] < 0)
8313         continue;
8314
8315       // Each element of the unpack contains Scale elements from this mask.
8316       int UnpackIdx = i / Scale;
8317
8318       // We only handle the case where V1 feeds the first slots of the unpack.
8319       // We rely on canonicalization to ensure this is the case.
8320       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8321         return SDValue();
8322
8323       // Setup the mask for this input. The indexing is tricky as we have to
8324       // handle the unpack stride.
8325       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8326       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8327           Mask[i] % Size;
8328     }
8329
8330     // If we will have to shuffle both inputs to use the unpack, check whether
8331     // we can just unpack first and shuffle the result. If so, skip this unpack.
8332     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8333         !isNoopShuffleMask(V2Mask))
8334       return SDValue();
8335
8336     // Shuffle the inputs into place.
8337     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8338     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8339
8340     // Cast the inputs to the type we will use to unpack them.
8341     V1 = DAG.getBitcast(UnpackVT, V1);
8342     V2 = DAG.getBitcast(UnpackVT, V2);
8343
8344     // Unpack the inputs and cast the result back to the desired type.
8345     return DAG.getBitcast(
8346         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8347                         UnpackVT, V1, V2));
8348   };
8349
8350   // We try each unpack from the largest to the smallest to try and find one
8351   // that fits this mask.
8352   int OrigNumElements = VT.getVectorNumElements();
8353   int OrigScalarSize = VT.getScalarSizeInBits();
8354   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8355     int Scale = ScalarSize / OrigScalarSize;
8356     int NumElements = OrigNumElements / Scale;
8357     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8358     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8359       return Unpack;
8360   }
8361
8362   // If none of the unpack-rooted lowerings worked (or were profitable) try an
8363   // initial unpack.
8364   if (NumLoInputs == 0 || NumHiInputs == 0) {
8365     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8366            "We have to have *some* inputs!");
8367     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8368
8369     // FIXME: We could consider the total complexity of the permute of each
8370     // possible unpacking. Or at the least we should consider how many
8371     // half-crossings are created.
8372     // FIXME: We could consider commuting the unpacks.
8373
8374     SmallVector<int, 32> PermMask;
8375     PermMask.assign(Size, -1);
8376     for (int i = 0; i < Size; ++i) {
8377       if (Mask[i] < 0)
8378         continue;
8379
8380       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8381
8382       PermMask[i] =
8383           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8384     }
8385     return DAG.getVectorShuffle(
8386         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8387                             DL, VT, V1, V2),
8388         DAG.getUNDEF(VT), PermMask);
8389   }
8390
8391   return SDValue();
8392 }
8393
8394 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8395 ///
8396 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8397 /// support for floating point shuffles but not integer shuffles. These
8398 /// instructions will incur a domain crossing penalty on some chips though so
8399 /// it is better to avoid lowering through this for integer vectors where
8400 /// possible.
8401 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8402                                        const X86Subtarget *Subtarget,
8403                                        SelectionDAG &DAG) {
8404   SDLoc DL(Op);
8405   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8406   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8407   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8408   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8409   ArrayRef<int> Mask = SVOp->getMask();
8410   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8411
8412   if (isSingleInputShuffleMask(Mask)) {
8413     // Use low duplicate instructions for masks that match their pattern.
8414     if (Subtarget->hasSSE3())
8415       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8416         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8417
8418     // Straight shuffle of a single input vector. Simulate this by using the
8419     // single input as both of the "inputs" to this instruction..
8420     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8421
8422     if (Subtarget->hasAVX()) {
8423       // If we have AVX, we can use VPERMILPS which will allow folding a load
8424       // into the shuffle.
8425       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8426                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8427     }
8428
8429     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8430                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8431   }
8432   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8433   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8434
8435   // If we have a single input, insert that into V1 if we can do so cheaply.
8436   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8437     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8438             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8439       return Insertion;
8440     // Try inverting the insertion since for v2 masks it is easy to do and we
8441     // can't reliably sort the mask one way or the other.
8442     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8443                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8444     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8445             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8446       return Insertion;
8447   }
8448
8449   // Try to use one of the special instruction patterns to handle two common
8450   // blend patterns if a zero-blend above didn't work.
8451   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8452       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8453     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8454       // We can either use a special instruction to load over the low double or
8455       // to move just the low double.
8456       return DAG.getNode(
8457           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8458           DL, MVT::v2f64, V2,
8459           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8460
8461   if (Subtarget->hasSSE41())
8462     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8463                                                   Subtarget, DAG))
8464       return Blend;
8465
8466   // Use dedicated unpack instructions for masks that match their pattern.
8467   if (SDValue V =
8468           lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8469     return V;
8470
8471   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8472   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8473                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8474 }
8475
8476 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8477 ///
8478 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8479 /// the integer unit to minimize domain crossing penalties. However, for blends
8480 /// it falls back to the floating point shuffle operation with appropriate bit
8481 /// casting.
8482 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8483                                        const X86Subtarget *Subtarget,
8484                                        SelectionDAG &DAG) {
8485   SDLoc DL(Op);
8486   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8487   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8488   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8489   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8490   ArrayRef<int> Mask = SVOp->getMask();
8491   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8492
8493   if (isSingleInputShuffleMask(Mask)) {
8494     // Check for being able to broadcast a single element.
8495     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8496                                                           Mask, Subtarget, DAG))
8497       return Broadcast;
8498
8499     // Straight shuffle of a single input vector. For everything from SSE2
8500     // onward this has a single fast instruction with no scary immediates.
8501     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8502     V1 = DAG.getBitcast(MVT::v4i32, V1);
8503     int WidenedMask[4] = {
8504         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8505         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8506     return DAG.getBitcast(
8507         MVT::v2i64,
8508         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8509                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8510   }
8511   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8512   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8513   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8514   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8515
8516   // If we have a blend of two PACKUS operations an the blend aligns with the
8517   // low and half halves, we can just merge the PACKUS operations. This is
8518   // particularly important as it lets us merge shuffles that this routine itself
8519   // creates.
8520   auto GetPackNode = [](SDValue V) {
8521     while (V.getOpcode() == ISD::BITCAST)
8522       V = V.getOperand(0);
8523
8524     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8525   };
8526   if (SDValue V1Pack = GetPackNode(V1))
8527     if (SDValue V2Pack = GetPackNode(V2))
8528       return DAG.getBitcast(MVT::v2i64,
8529                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8530                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8531                                                      : V1Pack.getOperand(1),
8532                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8533                                                      : V2Pack.getOperand(1)));
8534
8535   // Try to use shift instructions.
8536   if (SDValue Shift =
8537           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8538     return Shift;
8539
8540   // When loading a scalar and then shuffling it into a vector we can often do
8541   // the insertion cheaply.
8542   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8543           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8544     return Insertion;
8545   // Try inverting the insertion since for v2 masks it is easy to do and we
8546   // can't reliably sort the mask one way or the other.
8547   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8548   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8549           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8550     return Insertion;
8551
8552   // We have different paths for blend lowering, but they all must use the
8553   // *exact* same predicate.
8554   bool IsBlendSupported = Subtarget->hasSSE41();
8555   if (IsBlendSupported)
8556     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8557                                                   Subtarget, DAG))
8558       return Blend;
8559
8560   // Use dedicated unpack instructions for masks that match their pattern.
8561   if (SDValue V =
8562           lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8563     return V;
8564
8565   // Try to use byte rotation instructions.
8566   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8567   if (Subtarget->hasSSSE3())
8568     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8569             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8570       return Rotate;
8571
8572   // If we have direct support for blends, we should lower by decomposing into
8573   // a permute. That will be faster than the domain cross.
8574   if (IsBlendSupported)
8575     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8576                                                       Mask, DAG);
8577
8578   // We implement this with SHUFPD which is pretty lame because it will likely
8579   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8580   // However, all the alternatives are still more cycles and newer chips don't
8581   // have this problem. It would be really nice if x86 had better shuffles here.
8582   V1 = DAG.getBitcast(MVT::v2f64, V1);
8583   V2 = DAG.getBitcast(MVT::v2f64, V2);
8584   return DAG.getBitcast(MVT::v2i64,
8585                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8586 }
8587
8588 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8589 ///
8590 /// This is used to disable more specialized lowerings when the shufps lowering
8591 /// will happen to be efficient.
8592 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8593   // This routine only handles 128-bit shufps.
8594   assert(Mask.size() == 4 && "Unsupported mask size!");
8595
8596   // To lower with a single SHUFPS we need to have the low half and high half
8597   // each requiring a single input.
8598   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8599     return false;
8600   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8601     return false;
8602
8603   return true;
8604 }
8605
8606 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8607 ///
8608 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8609 /// It makes no assumptions about whether this is the *best* lowering, it simply
8610 /// uses it.
8611 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8612                                             ArrayRef<int> Mask, SDValue V1,
8613                                             SDValue V2, SelectionDAG &DAG) {
8614   SDValue LowV = V1, HighV = V2;
8615   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8616
8617   int NumV2Elements =
8618       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8619
8620   if (NumV2Elements == 1) {
8621     int V2Index =
8622         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8623         Mask.begin();
8624
8625     // Compute the index adjacent to V2Index and in the same half by toggling
8626     // the low bit.
8627     int V2AdjIndex = V2Index ^ 1;
8628
8629     if (Mask[V2AdjIndex] == -1) {
8630       // Handles all the cases where we have a single V2 element and an undef.
8631       // This will only ever happen in the high lanes because we commute the
8632       // vector otherwise.
8633       if (V2Index < 2)
8634         std::swap(LowV, HighV);
8635       NewMask[V2Index] -= 4;
8636     } else {
8637       // Handle the case where the V2 element ends up adjacent to a V1 element.
8638       // To make this work, blend them together as the first step.
8639       int V1Index = V2AdjIndex;
8640       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8641       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8642                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8643
8644       // Now proceed to reconstruct the final blend as we have the necessary
8645       // high or low half formed.
8646       if (V2Index < 2) {
8647         LowV = V2;
8648         HighV = V1;
8649       } else {
8650         HighV = V2;
8651       }
8652       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8653       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8654     }
8655   } else if (NumV2Elements == 2) {
8656     if (Mask[0] < 4 && Mask[1] < 4) {
8657       // Handle the easy case where we have V1 in the low lanes and V2 in the
8658       // high lanes.
8659       NewMask[2] -= 4;
8660       NewMask[3] -= 4;
8661     } else if (Mask[2] < 4 && Mask[3] < 4) {
8662       // We also handle the reversed case because this utility may get called
8663       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8664       // arrange things in the right direction.
8665       NewMask[0] -= 4;
8666       NewMask[1] -= 4;
8667       HighV = V1;
8668       LowV = V2;
8669     } else {
8670       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8671       // trying to place elements directly, just blend them and set up the final
8672       // shuffle to place them.
8673
8674       // The first two blend mask elements are for V1, the second two are for
8675       // V2.
8676       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8677                           Mask[2] < 4 ? Mask[2] : Mask[3],
8678                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8679                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8680       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8681                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8682
8683       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8684       // a blend.
8685       LowV = HighV = V1;
8686       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8687       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8688       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8689       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8690     }
8691   }
8692   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8693                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8694 }
8695
8696 /// \brief Lower 4-lane 32-bit floating point shuffles.
8697 ///
8698 /// Uses instructions exclusively from the floating point unit to minimize
8699 /// domain crossing penalties, as these are sufficient to implement all v4f32
8700 /// shuffles.
8701 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8702                                        const X86Subtarget *Subtarget,
8703                                        SelectionDAG &DAG) {
8704   SDLoc DL(Op);
8705   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8706   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8707   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8708   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8709   ArrayRef<int> Mask = SVOp->getMask();
8710   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8711
8712   int NumV2Elements =
8713       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8714
8715   if (NumV2Elements == 0) {
8716     // Check for being able to broadcast a single element.
8717     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8718                                                           Mask, Subtarget, DAG))
8719       return Broadcast;
8720
8721     // Use even/odd duplicate instructions for masks that match their pattern.
8722     if (Subtarget->hasSSE3()) {
8723       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8724         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8725       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8726         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8727     }
8728
8729     if (Subtarget->hasAVX()) {
8730       // If we have AVX, we can use VPERMILPS which will allow folding a load
8731       // into the shuffle.
8732       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8733                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8734     }
8735
8736     // Otherwise, use a straight shuffle of a single input vector. We pass the
8737     // input vector to both operands to simulate this with a SHUFPS.
8738     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8739                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8740   }
8741
8742   // There are special ways we can lower some single-element blends. However, we
8743   // have custom ways we can lower more complex single-element blends below that
8744   // we defer to if both this and BLENDPS fail to match, so restrict this to
8745   // when the V2 input is targeting element 0 of the mask -- that is the fast
8746   // case here.
8747   if (NumV2Elements == 1 && Mask[0] >= 4)
8748     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8749                                                          Mask, Subtarget, DAG))
8750       return V;
8751
8752   if (Subtarget->hasSSE41()) {
8753     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8754                                                   Subtarget, DAG))
8755       return Blend;
8756
8757     // Use INSERTPS if we can complete the shuffle efficiently.
8758     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8759       return V;
8760
8761     if (!isSingleSHUFPSMask(Mask))
8762       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8763               DL, MVT::v4f32, V1, V2, Mask, DAG))
8764         return BlendPerm;
8765   }
8766
8767   // Use dedicated unpack instructions for masks that match their pattern.
8768   if (SDValue V =
8769           lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8770     return V;
8771
8772   // Otherwise fall back to a SHUFPS lowering strategy.
8773   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8774 }
8775
8776 /// \brief Lower 4-lane i32 vector shuffles.
8777 ///
8778 /// We try to handle these with integer-domain shuffles where we can, but for
8779 /// blends we use the floating point domain blend instructions.
8780 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8781                                        const X86Subtarget *Subtarget,
8782                                        SelectionDAG &DAG) {
8783   SDLoc DL(Op);
8784   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8785   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8786   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8787   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8788   ArrayRef<int> Mask = SVOp->getMask();
8789   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8790
8791   // Whenever we can lower this as a zext, that instruction is strictly faster
8792   // than any alternative. It also allows us to fold memory operands into the
8793   // shuffle in many cases.
8794   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8795                                                          Mask, Subtarget, DAG))
8796     return ZExt;
8797
8798   int NumV2Elements =
8799       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8800
8801   if (NumV2Elements == 0) {
8802     // Check for being able to broadcast a single element.
8803     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8804                                                           Mask, Subtarget, DAG))
8805       return Broadcast;
8806
8807     // Straight shuffle of a single input vector. For everything from SSE2
8808     // onward this has a single fast instruction with no scary immediates.
8809     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8810     // but we aren't actually going to use the UNPCK instruction because doing
8811     // so prevents folding a load into this instruction or making a copy.
8812     const int UnpackLoMask[] = {0, 0, 1, 1};
8813     const int UnpackHiMask[] = {2, 2, 3, 3};
8814     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8815       Mask = UnpackLoMask;
8816     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8817       Mask = UnpackHiMask;
8818
8819     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8820                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8821   }
8822
8823   // Try to use shift instructions.
8824   if (SDValue Shift =
8825           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8826     return Shift;
8827
8828   // There are special ways we can lower some single-element blends.
8829   if (NumV2Elements == 1)
8830     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8831                                                          Mask, Subtarget, DAG))
8832       return V;
8833
8834   // We have different paths for blend lowering, but they all must use the
8835   // *exact* same predicate.
8836   bool IsBlendSupported = Subtarget->hasSSE41();
8837   if (IsBlendSupported)
8838     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8839                                                   Subtarget, DAG))
8840       return Blend;
8841
8842   if (SDValue Masked =
8843           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8844     return Masked;
8845
8846   // Use dedicated unpack instructions for masks that match their pattern.
8847   if (SDValue V =
8848           lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8849     return V;
8850
8851   // Try to use byte rotation instructions.
8852   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8853   if (Subtarget->hasSSSE3())
8854     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8855             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8856       return Rotate;
8857
8858   // If we have direct support for blends, we should lower by decomposing into
8859   // a permute. That will be faster than the domain cross.
8860   if (IsBlendSupported)
8861     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8862                                                       Mask, DAG);
8863
8864   // Try to lower by permuting the inputs into an unpack instruction.
8865   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8866                                                             V2, Mask, DAG))
8867     return Unpack;
8868
8869   // We implement this with SHUFPS because it can blend from two vectors.
8870   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8871   // up the inputs, bypassing domain shift penalties that we would encur if we
8872   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8873   // relevant.
8874   return DAG.getBitcast(
8875       MVT::v4i32,
8876       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8877                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8878 }
8879
8880 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8881 /// shuffle lowering, and the most complex part.
8882 ///
8883 /// The lowering strategy is to try to form pairs of input lanes which are
8884 /// targeted at the same half of the final vector, and then use a dword shuffle
8885 /// to place them onto the right half, and finally unpack the paired lanes into
8886 /// their final position.
8887 ///
8888 /// The exact breakdown of how to form these dword pairs and align them on the
8889 /// correct sides is really tricky. See the comments within the function for
8890 /// more of the details.
8891 ///
8892 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8893 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8894 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8895 /// vector, form the analogous 128-bit 8-element Mask.
8896 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8897     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8898     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8899   assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
8900   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8901
8902   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8903   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8904   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8905
8906   SmallVector<int, 4> LoInputs;
8907   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8908                [](int M) { return M >= 0; });
8909   std::sort(LoInputs.begin(), LoInputs.end());
8910   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8911   SmallVector<int, 4> HiInputs;
8912   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8913                [](int M) { return M >= 0; });
8914   std::sort(HiInputs.begin(), HiInputs.end());
8915   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8916   int NumLToL =
8917       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8918   int NumHToL = LoInputs.size() - NumLToL;
8919   int NumLToH =
8920       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8921   int NumHToH = HiInputs.size() - NumLToH;
8922   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8923   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8924   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8925   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8926
8927   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8928   // such inputs we can swap two of the dwords across the half mark and end up
8929   // with <=2 inputs to each half in each half. Once there, we can fall through
8930   // to the generic code below. For example:
8931   //
8932   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8933   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8934   //
8935   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8936   // and an existing 2-into-2 on the other half. In this case we may have to
8937   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8938   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8939   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8940   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8941   // half than the one we target for fixing) will be fixed when we re-enter this
8942   // path. We will also combine away any sequence of PSHUFD instructions that
8943   // result into a single instruction. Here is an example of the tricky case:
8944   //
8945   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8946   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8947   //
8948   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8949   //
8950   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8951   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8952   //
8953   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8954   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8955   //
8956   // The result is fine to be handled by the generic logic.
8957   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8958                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8959                           int AOffset, int BOffset) {
8960     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8961            "Must call this with A having 3 or 1 inputs from the A half.");
8962     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8963            "Must call this with B having 1 or 3 inputs from the B half.");
8964     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8965            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8966
8967     bool ThreeAInputs = AToAInputs.size() == 3;
8968
8969     // Compute the index of dword with only one word among the three inputs in
8970     // a half by taking the sum of the half with three inputs and subtracting
8971     // the sum of the actual three inputs. The difference is the remaining
8972     // slot.
8973     int ADWord, BDWord;
8974     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8975     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8976     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8977     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8978     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8979     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8980     int TripleNonInputIdx =
8981         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8982     TripleDWord = TripleNonInputIdx / 2;
8983
8984     // We use xor with one to compute the adjacent DWord to whichever one the
8985     // OneInput is in.
8986     OneInputDWord = (OneInput / 2) ^ 1;
8987
8988     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8989     // and BToA inputs. If there is also such a problem with the BToB and AToB
8990     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8991     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8992     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8993     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8994       // Compute how many inputs will be flipped by swapping these DWords. We
8995       // need
8996       // to balance this to ensure we don't form a 3-1 shuffle in the other
8997       // half.
8998       int NumFlippedAToBInputs =
8999           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
9000           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
9001       int NumFlippedBToBInputs =
9002           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
9003           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
9004       if ((NumFlippedAToBInputs == 1 &&
9005            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
9006           (NumFlippedBToBInputs == 1 &&
9007            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
9008         // We choose whether to fix the A half or B half based on whether that
9009         // half has zero flipped inputs. At zero, we may not be able to fix it
9010         // with that half. We also bias towards fixing the B half because that
9011         // will more commonly be the high half, and we have to bias one way.
9012         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
9013                                                        ArrayRef<int> Inputs) {
9014           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
9015           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
9016                                          PinnedIdx ^ 1) != Inputs.end();
9017           // Determine whether the free index is in the flipped dword or the
9018           // unflipped dword based on where the pinned index is. We use this bit
9019           // in an xor to conditionally select the adjacent dword.
9020           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
9021           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9022                                              FixFreeIdx) != Inputs.end();
9023           if (IsFixIdxInput == IsFixFreeIdxInput)
9024             FixFreeIdx += 1;
9025           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9026                                         FixFreeIdx) != Inputs.end();
9027           assert(IsFixIdxInput != IsFixFreeIdxInput &&
9028                  "We need to be changing the number of flipped inputs!");
9029           int PSHUFHalfMask[] = {0, 1, 2, 3};
9030           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
9031           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
9032                           MVT::v8i16, V,
9033                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
9034
9035           for (int &M : Mask)
9036             if (M != -1 && M == FixIdx)
9037               M = FixFreeIdx;
9038             else if (M != -1 && M == FixFreeIdx)
9039               M = FixIdx;
9040         };
9041         if (NumFlippedBToBInputs != 0) {
9042           int BPinnedIdx =
9043               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
9044           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
9045         } else {
9046           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
9047           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
9048           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
9049         }
9050       }
9051     }
9052
9053     int PSHUFDMask[] = {0, 1, 2, 3};
9054     PSHUFDMask[ADWord] = BDWord;
9055     PSHUFDMask[BDWord] = ADWord;
9056     V = DAG.getBitcast(
9057         VT,
9058         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9059                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9060
9061     // Adjust the mask to match the new locations of A and B.
9062     for (int &M : Mask)
9063       if (M != -1 && M/2 == ADWord)
9064         M = 2 * BDWord + M % 2;
9065       else if (M != -1 && M/2 == BDWord)
9066         M = 2 * ADWord + M % 2;
9067
9068     // Recurse back into this routine to re-compute state now that this isn't
9069     // a 3 and 1 problem.
9070     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
9071                                                      DAG);
9072   };
9073   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
9074     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
9075   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
9076     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
9077
9078   // At this point there are at most two inputs to the low and high halves from
9079   // each half. That means the inputs can always be grouped into dwords and
9080   // those dwords can then be moved to the correct half with a dword shuffle.
9081   // We use at most one low and one high word shuffle to collect these paired
9082   // inputs into dwords, and finally a dword shuffle to place them.
9083   int PSHUFLMask[4] = {-1, -1, -1, -1};
9084   int PSHUFHMask[4] = {-1, -1, -1, -1};
9085   int PSHUFDMask[4] = {-1, -1, -1, -1};
9086
9087   // First fix the masks for all the inputs that are staying in their
9088   // original halves. This will then dictate the targets of the cross-half
9089   // shuffles.
9090   auto fixInPlaceInputs =
9091       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
9092                     MutableArrayRef<int> SourceHalfMask,
9093                     MutableArrayRef<int> HalfMask, int HalfOffset) {
9094     if (InPlaceInputs.empty())
9095       return;
9096     if (InPlaceInputs.size() == 1) {
9097       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9098           InPlaceInputs[0] - HalfOffset;
9099       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
9100       return;
9101     }
9102     if (IncomingInputs.empty()) {
9103       // Just fix all of the in place inputs.
9104       for (int Input : InPlaceInputs) {
9105         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
9106         PSHUFDMask[Input / 2] = Input / 2;
9107       }
9108       return;
9109     }
9110
9111     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
9112     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9113         InPlaceInputs[0] - HalfOffset;
9114     // Put the second input next to the first so that they are packed into
9115     // a dword. We find the adjacent index by toggling the low bit.
9116     int AdjIndex = InPlaceInputs[0] ^ 1;
9117     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
9118     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
9119     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
9120   };
9121   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
9122   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
9123
9124   // Now gather the cross-half inputs and place them into a free dword of
9125   // their target half.
9126   // FIXME: This operation could almost certainly be simplified dramatically to
9127   // look more like the 3-1 fixing operation.
9128   auto moveInputsToRightHalf = [&PSHUFDMask](
9129       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
9130       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
9131       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
9132       int DestOffset) {
9133     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
9134       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
9135     };
9136     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
9137                                                int Word) {
9138       int LowWord = Word & ~1;
9139       int HighWord = Word | 1;
9140       return isWordClobbered(SourceHalfMask, LowWord) ||
9141              isWordClobbered(SourceHalfMask, HighWord);
9142     };
9143
9144     if (IncomingInputs.empty())
9145       return;
9146
9147     if (ExistingInputs.empty()) {
9148       // Map any dwords with inputs from them into the right half.
9149       for (int Input : IncomingInputs) {
9150         // If the source half mask maps over the inputs, turn those into
9151         // swaps and use the swapped lane.
9152         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
9153           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
9154             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
9155                 Input - SourceOffset;
9156             // We have to swap the uses in our half mask in one sweep.
9157             for (int &M : HalfMask)
9158               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
9159                 M = Input;
9160               else if (M == Input)
9161                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9162           } else {
9163             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
9164                        Input - SourceOffset &&
9165                    "Previous placement doesn't match!");
9166           }
9167           // Note that this correctly re-maps both when we do a swap and when
9168           // we observe the other side of the swap above. We rely on that to
9169           // avoid swapping the members of the input list directly.
9170           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9171         }
9172
9173         // Map the input's dword into the correct half.
9174         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
9175           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
9176         else
9177           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
9178                      Input / 2 &&
9179                  "Previous placement doesn't match!");
9180       }
9181
9182       // And just directly shift any other-half mask elements to be same-half
9183       // as we will have mirrored the dword containing the element into the
9184       // same position within that half.
9185       for (int &M : HalfMask)
9186         if (M >= SourceOffset && M < SourceOffset + 4) {
9187           M = M - SourceOffset + DestOffset;
9188           assert(M >= 0 && "This should never wrap below zero!");
9189         }
9190       return;
9191     }
9192
9193     // Ensure we have the input in a viable dword of its current half. This
9194     // is particularly tricky because the original position may be clobbered
9195     // by inputs being moved and *staying* in that half.
9196     if (IncomingInputs.size() == 1) {
9197       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9198         int InputFixed = std::find(std::begin(SourceHalfMask),
9199                                    std::end(SourceHalfMask), -1) -
9200                          std::begin(SourceHalfMask) + SourceOffset;
9201         SourceHalfMask[InputFixed - SourceOffset] =
9202             IncomingInputs[0] - SourceOffset;
9203         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
9204                      InputFixed);
9205         IncomingInputs[0] = InputFixed;
9206       }
9207     } else if (IncomingInputs.size() == 2) {
9208       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
9209           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9210         // We have two non-adjacent or clobbered inputs we need to extract from
9211         // the source half. To do this, we need to map them into some adjacent
9212         // dword slot in the source mask.
9213         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
9214                               IncomingInputs[1] - SourceOffset};
9215
9216         // If there is a free slot in the source half mask adjacent to one of
9217         // the inputs, place the other input in it. We use (Index XOR 1) to
9218         // compute an adjacent index.
9219         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
9220             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
9221           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
9222           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9223           InputsFixed[1] = InputsFixed[0] ^ 1;
9224         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
9225                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
9226           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
9227           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
9228           InputsFixed[0] = InputsFixed[1] ^ 1;
9229         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
9230                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9231           // The two inputs are in the same DWord but it is clobbered and the
9232           // adjacent DWord isn't used at all. Move both inputs to the free
9233           // slot.
9234           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9235           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9236           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9237           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9238         } else {
9239           // The only way we hit this point is if there is no clobbering
9240           // (because there are no off-half inputs to this half) and there is no
9241           // free slot adjacent to one of the inputs. In this case, we have to
9242           // swap an input with a non-input.
9243           for (int i = 0; i < 4; ++i)
9244             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9245                    "We can't handle any clobbers here!");
9246           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9247                  "Cannot have adjacent inputs here!");
9248
9249           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9250           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9251
9252           // We also have to update the final source mask in this case because
9253           // it may need to undo the above swap.
9254           for (int &M : FinalSourceHalfMask)
9255             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9256               M = InputsFixed[1] + SourceOffset;
9257             else if (M == InputsFixed[1] + SourceOffset)
9258               M = (InputsFixed[0] ^ 1) + SourceOffset;
9259
9260           InputsFixed[1] = InputsFixed[0] ^ 1;
9261         }
9262
9263         // Point everything at the fixed inputs.
9264         for (int &M : HalfMask)
9265           if (M == IncomingInputs[0])
9266             M = InputsFixed[0] + SourceOffset;
9267           else if (M == IncomingInputs[1])
9268             M = InputsFixed[1] + SourceOffset;
9269
9270         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9271         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9272       }
9273     } else {
9274       llvm_unreachable("Unhandled input size!");
9275     }
9276
9277     // Now hoist the DWord down to the right half.
9278     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9279     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9280     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9281     for (int &M : HalfMask)
9282       for (int Input : IncomingInputs)
9283         if (M == Input)
9284           M = FreeDWord * 2 + Input % 2;
9285   };
9286   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9287                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
9288   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9289                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
9290
9291   // Now enact all the shuffles we've computed to move the inputs into their
9292   // target half.
9293   if (!isNoopShuffleMask(PSHUFLMask))
9294     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9295                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9296   if (!isNoopShuffleMask(PSHUFHMask))
9297     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9298                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9299   if (!isNoopShuffleMask(PSHUFDMask))
9300     V = DAG.getBitcast(
9301         VT,
9302         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9303                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9304
9305   // At this point, each half should contain all its inputs, and we can then
9306   // just shuffle them into their final position.
9307   assert(std::count_if(LoMask.begin(), LoMask.end(),
9308                        [](int M) { return M >= 4; }) == 0 &&
9309          "Failed to lift all the high half inputs to the low mask!");
9310   assert(std::count_if(HiMask.begin(), HiMask.end(),
9311                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9312          "Failed to lift all the low half inputs to the high mask!");
9313
9314   // Do a half shuffle for the low mask.
9315   if (!isNoopShuffleMask(LoMask))
9316     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9317                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9318
9319   // Do a half shuffle with the high mask after shifting its values down.
9320   for (int &M : HiMask)
9321     if (M >= 0)
9322       M -= 4;
9323   if (!isNoopShuffleMask(HiMask))
9324     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9325                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9326
9327   return V;
9328 }
9329
9330 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9331 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9332                                           SDValue V2, ArrayRef<int> Mask,
9333                                           SelectionDAG &DAG, bool &V1InUse,
9334                                           bool &V2InUse) {
9335   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9336   SDValue V1Mask[16];
9337   SDValue V2Mask[16];
9338   V1InUse = false;
9339   V2InUse = false;
9340
9341   int Size = Mask.size();
9342   int Scale = 16 / Size;
9343   for (int i = 0; i < 16; ++i) {
9344     if (Mask[i / Scale] == -1) {
9345       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9346     } else {
9347       const int ZeroMask = 0x80;
9348       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9349                                           : ZeroMask;
9350       int V2Idx = Mask[i / Scale] < Size
9351                       ? ZeroMask
9352                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
9353       if (Zeroable[i / Scale])
9354         V1Idx = V2Idx = ZeroMask;
9355       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9356       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9357       V1InUse |= (ZeroMask != V1Idx);
9358       V2InUse |= (ZeroMask != V2Idx);
9359     }
9360   }
9361
9362   if (V1InUse)
9363     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9364                      DAG.getBitcast(MVT::v16i8, V1),
9365                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9366   if (V2InUse)
9367     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9368                      DAG.getBitcast(MVT::v16i8, V2),
9369                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9370
9371   // If we need shuffled inputs from both, blend the two.
9372   SDValue V;
9373   if (V1InUse && V2InUse)
9374     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9375   else
9376     V = V1InUse ? V1 : V2;
9377
9378   // Cast the result back to the correct type.
9379   return DAG.getBitcast(VT, V);
9380 }
9381
9382 /// \brief Generic lowering of 8-lane i16 shuffles.
9383 ///
9384 /// This handles both single-input shuffles and combined shuffle/blends with
9385 /// two inputs. The single input shuffles are immediately delegated to
9386 /// a dedicated lowering routine.
9387 ///
9388 /// The blends are lowered in one of three fundamental ways. If there are few
9389 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9390 /// of the input is significantly cheaper when lowered as an interleaving of
9391 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9392 /// halves of the inputs separately (making them have relatively few inputs)
9393 /// and then concatenate them.
9394 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9395                                        const X86Subtarget *Subtarget,
9396                                        SelectionDAG &DAG) {
9397   SDLoc DL(Op);
9398   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9399   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9400   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9401   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9402   ArrayRef<int> OrigMask = SVOp->getMask();
9403   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9404                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9405   MutableArrayRef<int> Mask(MaskStorage);
9406
9407   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9408
9409   // Whenever we can lower this as a zext, that instruction is strictly faster
9410   // than any alternative.
9411   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9412           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9413     return ZExt;
9414
9415   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9416   (void)isV1;
9417   auto isV2 = [](int M) { return M >= 8; };
9418
9419   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9420
9421   if (NumV2Inputs == 0) {
9422     // Check for being able to broadcast a single element.
9423     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9424                                                           Mask, Subtarget, DAG))
9425       return Broadcast;
9426
9427     // Try to use shift instructions.
9428     if (SDValue Shift =
9429             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9430       return Shift;
9431
9432     // Use dedicated unpack instructions for masks that match their pattern.
9433     if (SDValue V =
9434             lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9435       return V;
9436
9437     // Try to use byte rotation instructions.
9438     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9439                                                         Mask, Subtarget, DAG))
9440       return Rotate;
9441
9442     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9443                                                      Subtarget, DAG);
9444   }
9445
9446   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9447          "All single-input shuffles should be canonicalized to be V1-input "
9448          "shuffles.");
9449
9450   // Try to use shift instructions.
9451   if (SDValue Shift =
9452           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9453     return Shift;
9454
9455   // See if we can use SSE4A Extraction / Insertion.
9456   if (Subtarget->hasSSE4A())
9457     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9458       return V;
9459
9460   // There are special ways we can lower some single-element blends.
9461   if (NumV2Inputs == 1)
9462     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9463                                                          Mask, Subtarget, DAG))
9464       return V;
9465
9466   // We have different paths for blend lowering, but they all must use the
9467   // *exact* same predicate.
9468   bool IsBlendSupported = Subtarget->hasSSE41();
9469   if (IsBlendSupported)
9470     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9471                                                   Subtarget, DAG))
9472       return Blend;
9473
9474   if (SDValue Masked =
9475           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9476     return Masked;
9477
9478   // Use dedicated unpack instructions for masks that match their pattern.
9479   if (SDValue V =
9480           lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9481     return V;
9482
9483   // Try to use byte rotation instructions.
9484   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9485           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9486     return Rotate;
9487
9488   if (SDValue BitBlend =
9489           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9490     return BitBlend;
9491
9492   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9493                                                             V2, Mask, DAG))
9494     return Unpack;
9495
9496   // If we can't directly blend but can use PSHUFB, that will be better as it
9497   // can both shuffle and set up the inefficient blend.
9498   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9499     bool V1InUse, V2InUse;
9500     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9501                                       V1InUse, V2InUse);
9502   }
9503
9504   // We can always bit-blend if we have to so the fallback strategy is to
9505   // decompose into single-input permutes and blends.
9506   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9507                                                       Mask, DAG);
9508 }
9509
9510 /// \brief Check whether a compaction lowering can be done by dropping even
9511 /// elements and compute how many times even elements must be dropped.
9512 ///
9513 /// This handles shuffles which take every Nth element where N is a power of
9514 /// two. Example shuffle masks:
9515 ///
9516 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9517 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9518 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9519 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9520 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9521 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9522 ///
9523 /// Any of these lanes can of course be undef.
9524 ///
9525 /// This routine only supports N <= 3.
9526 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9527 /// for larger N.
9528 ///
9529 /// \returns N above, or the number of times even elements must be dropped if
9530 /// there is such a number. Otherwise returns zero.
9531 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9532   // Figure out whether we're looping over two inputs or just one.
9533   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9534
9535   // The modulus for the shuffle vector entries is based on whether this is
9536   // a single input or not.
9537   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9538   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9539          "We should only be called with masks with a power-of-2 size!");
9540
9541   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9542
9543   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9544   // and 2^3 simultaneously. This is because we may have ambiguity with
9545   // partially undef inputs.
9546   bool ViableForN[3] = {true, true, true};
9547
9548   for (int i = 0, e = Mask.size(); i < e; ++i) {
9549     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9550     // want.
9551     if (Mask[i] == -1)
9552       continue;
9553
9554     bool IsAnyViable = false;
9555     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9556       if (ViableForN[j]) {
9557         uint64_t N = j + 1;
9558
9559         // The shuffle mask must be equal to (i * 2^N) % M.
9560         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9561           IsAnyViable = true;
9562         else
9563           ViableForN[j] = false;
9564       }
9565     // Early exit if we exhaust the possible powers of two.
9566     if (!IsAnyViable)
9567       break;
9568   }
9569
9570   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9571     if (ViableForN[j])
9572       return j + 1;
9573
9574   // Return 0 as there is no viable power of two.
9575   return 0;
9576 }
9577
9578 /// \brief Generic lowering of v16i8 shuffles.
9579 ///
9580 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9581 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9582 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9583 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9584 /// back together.
9585 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9586                                        const X86Subtarget *Subtarget,
9587                                        SelectionDAG &DAG) {
9588   SDLoc DL(Op);
9589   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9590   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9591   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9592   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9593   ArrayRef<int> Mask = SVOp->getMask();
9594   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9595
9596   // Try to use shift instructions.
9597   if (SDValue Shift =
9598           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9599     return Shift;
9600
9601   // Try to use byte rotation instructions.
9602   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9603           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9604     return Rotate;
9605
9606   // Try to use a zext lowering.
9607   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9608           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9609     return ZExt;
9610
9611   // See if we can use SSE4A Extraction / Insertion.
9612   if (Subtarget->hasSSE4A())
9613     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9614       return V;
9615
9616   int NumV2Elements =
9617       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9618
9619   // For single-input shuffles, there are some nicer lowering tricks we can use.
9620   if (NumV2Elements == 0) {
9621     // Check for being able to broadcast a single element.
9622     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9623                                                           Mask, Subtarget, DAG))
9624       return Broadcast;
9625
9626     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9627     // Notably, this handles splat and partial-splat shuffles more efficiently.
9628     // However, it only makes sense if the pre-duplication shuffle simplifies
9629     // things significantly. Currently, this means we need to be able to
9630     // express the pre-duplication shuffle as an i16 shuffle.
9631     //
9632     // FIXME: We should check for other patterns which can be widened into an
9633     // i16 shuffle as well.
9634     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9635       for (int i = 0; i < 16; i += 2)
9636         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9637           return false;
9638
9639       return true;
9640     };
9641     auto tryToWidenViaDuplication = [&]() -> SDValue {
9642       if (!canWidenViaDuplication(Mask))
9643         return SDValue();
9644       SmallVector<int, 4> LoInputs;
9645       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9646                    [](int M) { return M >= 0 && M < 8; });
9647       std::sort(LoInputs.begin(), LoInputs.end());
9648       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9649                      LoInputs.end());
9650       SmallVector<int, 4> HiInputs;
9651       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9652                    [](int M) { return M >= 8; });
9653       std::sort(HiInputs.begin(), HiInputs.end());
9654       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9655                      HiInputs.end());
9656
9657       bool TargetLo = LoInputs.size() >= HiInputs.size();
9658       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9659       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9660
9661       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9662       SmallDenseMap<int, int, 8> LaneMap;
9663       for (int I : InPlaceInputs) {
9664         PreDupI16Shuffle[I/2] = I/2;
9665         LaneMap[I] = I;
9666       }
9667       int j = TargetLo ? 0 : 4, je = j + 4;
9668       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9669         // Check if j is already a shuffle of this input. This happens when
9670         // there are two adjacent bytes after we move the low one.
9671         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9672           // If we haven't yet mapped the input, search for a slot into which
9673           // we can map it.
9674           while (j < je && PreDupI16Shuffle[j] != -1)
9675             ++j;
9676
9677           if (j == je)
9678             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9679             return SDValue();
9680
9681           // Map this input with the i16 shuffle.
9682           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9683         }
9684
9685         // Update the lane map based on the mapping we ended up with.
9686         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9687       }
9688       V1 = DAG.getBitcast(
9689           MVT::v16i8,
9690           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9691                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9692
9693       // Unpack the bytes to form the i16s that will be shuffled into place.
9694       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9695                        MVT::v16i8, V1, V1);
9696
9697       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9698       for (int i = 0; i < 16; ++i)
9699         if (Mask[i] != -1) {
9700           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9701           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9702           if (PostDupI16Shuffle[i / 2] == -1)
9703             PostDupI16Shuffle[i / 2] = MappedMask;
9704           else
9705             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9706                    "Conflicting entrties in the original shuffle!");
9707         }
9708       return DAG.getBitcast(
9709           MVT::v16i8,
9710           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9711                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9712     };
9713     if (SDValue V = tryToWidenViaDuplication())
9714       return V;
9715   }
9716
9717   if (SDValue Masked =
9718           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9719     return Masked;
9720
9721   // Use dedicated unpack instructions for masks that match their pattern.
9722   if (SDValue V =
9723           lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9724     return V;
9725
9726   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9727   // with PSHUFB. It is important to do this before we attempt to generate any
9728   // blends but after all of the single-input lowerings. If the single input
9729   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9730   // want to preserve that and we can DAG combine any longer sequences into
9731   // a PSHUFB in the end. But once we start blending from multiple inputs,
9732   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9733   // and there are *very* few patterns that would actually be faster than the
9734   // PSHUFB approach because of its ability to zero lanes.
9735   //
9736   // FIXME: The only exceptions to the above are blends which are exact
9737   // interleavings with direct instructions supporting them. We currently don't
9738   // handle those well here.
9739   if (Subtarget->hasSSSE3()) {
9740     bool V1InUse = false;
9741     bool V2InUse = false;
9742
9743     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9744                                                 DAG, V1InUse, V2InUse);
9745
9746     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9747     // do so. This avoids using them to handle blends-with-zero which is
9748     // important as a single pshufb is significantly faster for that.
9749     if (V1InUse && V2InUse) {
9750       if (Subtarget->hasSSE41())
9751         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9752                                                       Mask, Subtarget, DAG))
9753           return Blend;
9754
9755       // We can use an unpack to do the blending rather than an or in some
9756       // cases. Even though the or may be (very minorly) more efficient, we
9757       // preference this lowering because there are common cases where part of
9758       // the complexity of the shuffles goes away when we do the final blend as
9759       // an unpack.
9760       // FIXME: It might be worth trying to detect if the unpack-feeding
9761       // shuffles will both be pshufb, in which case we shouldn't bother with
9762       // this.
9763       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9764               DL, MVT::v16i8, V1, V2, Mask, DAG))
9765         return Unpack;
9766     }
9767
9768     return PSHUFB;
9769   }
9770
9771   // There are special ways we can lower some single-element blends.
9772   if (NumV2Elements == 1)
9773     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9774                                                          Mask, Subtarget, DAG))
9775       return V;
9776
9777   if (SDValue BitBlend =
9778           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9779     return BitBlend;
9780
9781   // Check whether a compaction lowering can be done. This handles shuffles
9782   // which take every Nth element for some even N. See the helper function for
9783   // details.
9784   //
9785   // We special case these as they can be particularly efficiently handled with
9786   // the PACKUSB instruction on x86 and they show up in common patterns of
9787   // rearranging bytes to truncate wide elements.
9788   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9789     // NumEvenDrops is the power of two stride of the elements. Another way of
9790     // thinking about it is that we need to drop the even elements this many
9791     // times to get the original input.
9792     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9793
9794     // First we need to zero all the dropped bytes.
9795     assert(NumEvenDrops <= 3 &&
9796            "No support for dropping even elements more than 3 times.");
9797     // We use the mask type to pick which bytes are preserved based on how many
9798     // elements are dropped.
9799     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9800     SDValue ByteClearMask = DAG.getBitcast(
9801         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9802     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9803     if (!IsSingleInput)
9804       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9805
9806     // Now pack things back together.
9807     V1 = DAG.getBitcast(MVT::v8i16, V1);
9808     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9809     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9810     for (int i = 1; i < NumEvenDrops; ++i) {
9811       Result = DAG.getBitcast(MVT::v8i16, Result);
9812       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9813     }
9814
9815     return Result;
9816   }
9817
9818   // Handle multi-input cases by blending single-input shuffles.
9819   if (NumV2Elements > 0)
9820     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9821                                                       Mask, DAG);
9822
9823   // The fallback path for single-input shuffles widens this into two v8i16
9824   // vectors with unpacks, shuffles those, and then pulls them back together
9825   // with a pack.
9826   SDValue V = V1;
9827
9828   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9829   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9830   for (int i = 0; i < 16; ++i)
9831     if (Mask[i] >= 0)
9832       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9833
9834   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9835
9836   SDValue VLoHalf, VHiHalf;
9837   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9838   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9839   // i16s.
9840   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9841                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9842       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9843                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9844     // Use a mask to drop the high bytes.
9845     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9846     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9847                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9848
9849     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9850     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9851
9852     // Squash the masks to point directly into VLoHalf.
9853     for (int &M : LoBlendMask)
9854       if (M >= 0)
9855         M /= 2;
9856     for (int &M : HiBlendMask)
9857       if (M >= 0)
9858         M /= 2;
9859   } else {
9860     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9861     // VHiHalf so that we can blend them as i16s.
9862     VLoHalf = DAG.getBitcast(
9863         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9864     VHiHalf = DAG.getBitcast(
9865         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9866   }
9867
9868   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9869   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9870
9871   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9872 }
9873
9874 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9875 ///
9876 /// This routine breaks down the specific type of 128-bit shuffle and
9877 /// dispatches to the lowering routines accordingly.
9878 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9879                                         MVT VT, const X86Subtarget *Subtarget,
9880                                         SelectionDAG &DAG) {
9881   switch (VT.SimpleTy) {
9882   case MVT::v2i64:
9883     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9884   case MVT::v2f64:
9885     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9886   case MVT::v4i32:
9887     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9888   case MVT::v4f32:
9889     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9890   case MVT::v8i16:
9891     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9892   case MVT::v16i8:
9893     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9894
9895   default:
9896     llvm_unreachable("Unimplemented!");
9897   }
9898 }
9899
9900 /// \brief Helper function to test whether a shuffle mask could be
9901 /// simplified by widening the elements being shuffled.
9902 ///
9903 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9904 /// leaves it in an unspecified state.
9905 ///
9906 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9907 /// shuffle masks. The latter have the special property of a '-2' representing
9908 /// a zero-ed lane of a vector.
9909 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9910                                     SmallVectorImpl<int> &WidenedMask) {
9911   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9912     // If both elements are undef, its trivial.
9913     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9914       WidenedMask.push_back(SM_SentinelUndef);
9915       continue;
9916     }
9917
9918     // Check for an undef mask and a mask value properly aligned to fit with
9919     // a pair of values. If we find such a case, use the non-undef mask's value.
9920     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9921       WidenedMask.push_back(Mask[i + 1] / 2);
9922       continue;
9923     }
9924     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9925       WidenedMask.push_back(Mask[i] / 2);
9926       continue;
9927     }
9928
9929     // When zeroing, we need to spread the zeroing across both lanes to widen.
9930     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9931       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9932           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9933         WidenedMask.push_back(SM_SentinelZero);
9934         continue;
9935       }
9936       return false;
9937     }
9938
9939     // Finally check if the two mask values are adjacent and aligned with
9940     // a pair.
9941     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9942       WidenedMask.push_back(Mask[i] / 2);
9943       continue;
9944     }
9945
9946     // Otherwise we can't safely widen the elements used in this shuffle.
9947     return false;
9948   }
9949   assert(WidenedMask.size() == Mask.size() / 2 &&
9950          "Incorrect size of mask after widening the elements!");
9951
9952   return true;
9953 }
9954
9955 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9956 ///
9957 /// This routine just extracts two subvectors, shuffles them independently, and
9958 /// then concatenates them back together. This should work effectively with all
9959 /// AVX vector shuffle types.
9960 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9961                                           SDValue V2, ArrayRef<int> Mask,
9962                                           SelectionDAG &DAG) {
9963   assert(VT.getSizeInBits() >= 256 &&
9964          "Only for 256-bit or wider vector shuffles!");
9965   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9966   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9967
9968   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9969   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9970
9971   int NumElements = VT.getVectorNumElements();
9972   int SplitNumElements = NumElements / 2;
9973   MVT ScalarVT = VT.getVectorElementType();
9974   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9975
9976   // Rather than splitting build-vectors, just build two narrower build
9977   // vectors. This helps shuffling with splats and zeros.
9978   auto SplitVector = [&](SDValue V) {
9979     while (V.getOpcode() == ISD::BITCAST)
9980       V = V->getOperand(0);
9981
9982     MVT OrigVT = V.getSimpleValueType();
9983     int OrigNumElements = OrigVT.getVectorNumElements();
9984     int OrigSplitNumElements = OrigNumElements / 2;
9985     MVT OrigScalarVT = OrigVT.getVectorElementType();
9986     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9987
9988     SDValue LoV, HiV;
9989
9990     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9991     if (!BV) {
9992       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9993                         DAG.getIntPtrConstant(0, DL));
9994       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9995                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9996     } else {
9997
9998       SmallVector<SDValue, 16> LoOps, HiOps;
9999       for (int i = 0; i < OrigSplitNumElements; ++i) {
10000         LoOps.push_back(BV->getOperand(i));
10001         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
10002       }
10003       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
10004       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
10005     }
10006     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
10007                           DAG.getBitcast(SplitVT, HiV));
10008   };
10009
10010   SDValue LoV1, HiV1, LoV2, HiV2;
10011   std::tie(LoV1, HiV1) = SplitVector(V1);
10012   std::tie(LoV2, HiV2) = SplitVector(V2);
10013
10014   // Now create two 4-way blends of these half-width vectors.
10015   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
10016     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
10017     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
10018     for (int i = 0; i < SplitNumElements; ++i) {
10019       int M = HalfMask[i];
10020       if (M >= NumElements) {
10021         if (M >= NumElements + SplitNumElements)
10022           UseHiV2 = true;
10023         else
10024           UseLoV2 = true;
10025         V2BlendMask.push_back(M - NumElements);
10026         V1BlendMask.push_back(-1);
10027         BlendMask.push_back(SplitNumElements + i);
10028       } else if (M >= 0) {
10029         if (M >= SplitNumElements)
10030           UseHiV1 = true;
10031         else
10032           UseLoV1 = true;
10033         V2BlendMask.push_back(-1);
10034         V1BlendMask.push_back(M);
10035         BlendMask.push_back(i);
10036       } else {
10037         V2BlendMask.push_back(-1);
10038         V1BlendMask.push_back(-1);
10039         BlendMask.push_back(-1);
10040       }
10041     }
10042
10043     // Because the lowering happens after all combining takes place, we need to
10044     // manually combine these blend masks as much as possible so that we create
10045     // a minimal number of high-level vector shuffle nodes.
10046
10047     // First try just blending the halves of V1 or V2.
10048     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
10049       return DAG.getUNDEF(SplitVT);
10050     if (!UseLoV2 && !UseHiV2)
10051       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10052     if (!UseLoV1 && !UseHiV1)
10053       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10054
10055     SDValue V1Blend, V2Blend;
10056     if (UseLoV1 && UseHiV1) {
10057       V1Blend =
10058         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10059     } else {
10060       // We only use half of V1 so map the usage down into the final blend mask.
10061       V1Blend = UseLoV1 ? LoV1 : HiV1;
10062       for (int i = 0; i < SplitNumElements; ++i)
10063         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
10064           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
10065     }
10066     if (UseLoV2 && UseHiV2) {
10067       V2Blend =
10068         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10069     } else {
10070       // We only use half of V2 so map the usage down into the final blend mask.
10071       V2Blend = UseLoV2 ? LoV2 : HiV2;
10072       for (int i = 0; i < SplitNumElements; ++i)
10073         if (BlendMask[i] >= SplitNumElements)
10074           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
10075     }
10076     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
10077   };
10078   SDValue Lo = HalfBlend(LoMask);
10079   SDValue Hi = HalfBlend(HiMask);
10080   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
10081 }
10082
10083 /// \brief Either split a vector in halves or decompose the shuffles and the
10084 /// blend.
10085 ///
10086 /// This is provided as a good fallback for many lowerings of non-single-input
10087 /// shuffles with more than one 128-bit lane. In those cases, we want to select
10088 /// between splitting the shuffle into 128-bit components and stitching those
10089 /// back together vs. extracting the single-input shuffles and blending those
10090 /// results.
10091 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
10092                                                 SDValue V2, ArrayRef<int> Mask,
10093                                                 SelectionDAG &DAG) {
10094   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
10095                                             "lower single-input shuffles as it "
10096                                             "could then recurse on itself.");
10097   int Size = Mask.size();
10098
10099   // If this can be modeled as a broadcast of two elements followed by a blend,
10100   // prefer that lowering. This is especially important because broadcasts can
10101   // often fold with memory operands.
10102   auto DoBothBroadcast = [&] {
10103     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
10104     for (int M : Mask)
10105       if (M >= Size) {
10106         if (V2BroadcastIdx == -1)
10107           V2BroadcastIdx = M - Size;
10108         else if (M - Size != V2BroadcastIdx)
10109           return false;
10110       } else if (M >= 0) {
10111         if (V1BroadcastIdx == -1)
10112           V1BroadcastIdx = M;
10113         else if (M != V1BroadcastIdx)
10114           return false;
10115       }
10116     return true;
10117   };
10118   if (DoBothBroadcast())
10119     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
10120                                                       DAG);
10121
10122   // If the inputs all stem from a single 128-bit lane of each input, then we
10123   // split them rather than blending because the split will decompose to
10124   // unusually few instructions.
10125   int LaneCount = VT.getSizeInBits() / 128;
10126   int LaneSize = Size / LaneCount;
10127   SmallBitVector LaneInputs[2];
10128   LaneInputs[0].resize(LaneCount, false);
10129   LaneInputs[1].resize(LaneCount, false);
10130   for (int i = 0; i < Size; ++i)
10131     if (Mask[i] >= 0)
10132       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
10133   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
10134     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10135
10136   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
10137   // that the decomposed single-input shuffles don't end up here.
10138   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10139 }
10140
10141 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
10142 /// a permutation and blend of those lanes.
10143 ///
10144 /// This essentially blends the out-of-lane inputs to each lane into the lane
10145 /// from a permuted copy of the vector. This lowering strategy results in four
10146 /// instructions in the worst case for a single-input cross lane shuffle which
10147 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
10148 /// of. Special cases for each particular shuffle pattern should be handled
10149 /// prior to trying this lowering.
10150 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
10151                                                        SDValue V1, SDValue V2,
10152                                                        ArrayRef<int> Mask,
10153                                                        SelectionDAG &DAG) {
10154   // FIXME: This should probably be generalized for 512-bit vectors as well.
10155   assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
10156   int LaneSize = Mask.size() / 2;
10157
10158   // If there are only inputs from one 128-bit lane, splitting will in fact be
10159   // less expensive. The flags track whether the given lane contains an element
10160   // that crosses to another lane.
10161   bool LaneCrossing[2] = {false, false};
10162   for (int i = 0, Size = Mask.size(); i < Size; ++i)
10163     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10164       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
10165   if (!LaneCrossing[0] || !LaneCrossing[1])
10166     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10167
10168   if (isSingleInputShuffleMask(Mask)) {
10169     SmallVector<int, 32> FlippedBlendMask;
10170     for (int i = 0, Size = Mask.size(); i < Size; ++i)
10171       FlippedBlendMask.push_back(
10172           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
10173                                   ? Mask[i]
10174                                   : Mask[i] % LaneSize +
10175                                         (i / LaneSize) * LaneSize + Size));
10176
10177     // Flip the vector, and blend the results which should now be in-lane. The
10178     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
10179     // 5 for the high source. The value 3 selects the high half of source 2 and
10180     // the value 2 selects the low half of source 2. We only use source 2 to
10181     // allow folding it into a memory operand.
10182     unsigned PERMMask = 3 | 2 << 4;
10183     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
10184                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
10185     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
10186   }
10187
10188   // This now reduces to two single-input shuffles of V1 and V2 which at worst
10189   // will be handled by the above logic and a blend of the results, much like
10190   // other patterns in AVX.
10191   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10192 }
10193
10194 /// \brief Handle lowering 2-lane 128-bit shuffles.
10195 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10196                                         SDValue V2, ArrayRef<int> Mask,
10197                                         const X86Subtarget *Subtarget,
10198                                         SelectionDAG &DAG) {
10199   // TODO: If minimizing size and one of the inputs is a zero vector and the
10200   // the zero vector has only one use, we could use a VPERM2X128 to save the
10201   // instruction bytes needed to explicitly generate the zero vector.
10202
10203   // Blends are faster and handle all the non-lane-crossing cases.
10204   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10205                                                 Subtarget, DAG))
10206     return Blend;
10207
10208   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
10209   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
10210
10211   // If either input operand is a zero vector, use VPERM2X128 because its mask
10212   // allows us to replace the zero input with an implicit zero.
10213   if (!IsV1Zero && !IsV2Zero) {
10214     // Check for patterns which can be matched with a single insert of a 128-bit
10215     // subvector.
10216     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
10217     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
10218       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10219                                    VT.getVectorNumElements() / 2);
10220       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10221                                 DAG.getIntPtrConstant(0, DL));
10222       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10223                                 OnlyUsesV1 ? V1 : V2,
10224                                 DAG.getIntPtrConstant(0, DL));
10225       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10226     }
10227   }
10228
10229   // Otherwise form a 128-bit permutation. After accounting for undefs,
10230   // convert the 64-bit shuffle mask selection values into 128-bit
10231   // selection bits by dividing the indexes by 2 and shifting into positions
10232   // defined by a vperm2*128 instruction's immediate control byte.
10233
10234   // The immediate permute control byte looks like this:
10235   //    [1:0] - select 128 bits from sources for low half of destination
10236   //    [2]   - ignore
10237   //    [3]   - zero low half of destination
10238   //    [5:4] - select 128 bits from sources for high half of destination
10239   //    [6]   - ignore
10240   //    [7]   - zero high half of destination
10241
10242   int MaskLO = Mask[0];
10243   if (MaskLO == SM_SentinelUndef)
10244     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10245
10246   int MaskHI = Mask[2];
10247   if (MaskHI == SM_SentinelUndef)
10248     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10249
10250   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10251
10252   // If either input is a zero vector, replace it with an undef input.
10253   // Shuffle mask values <  4 are selecting elements of V1.
10254   // Shuffle mask values >= 4 are selecting elements of V2.
10255   // Adjust each half of the permute mask by clearing the half that was
10256   // selecting the zero vector and setting the zero mask bit.
10257   if (IsV1Zero) {
10258     V1 = DAG.getUNDEF(VT);
10259     if (MaskLO < 4)
10260       PermMask = (PermMask & 0xf0) | 0x08;
10261     if (MaskHI < 4)
10262       PermMask = (PermMask & 0x0f) | 0x80;
10263   }
10264   if (IsV2Zero) {
10265     V2 = DAG.getUNDEF(VT);
10266     if (MaskLO >= 4)
10267       PermMask = (PermMask & 0xf0) | 0x08;
10268     if (MaskHI >= 4)
10269       PermMask = (PermMask & 0x0f) | 0x80;
10270   }
10271
10272   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10273                      DAG.getConstant(PermMask, DL, MVT::i8));
10274 }
10275
10276 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10277 /// shuffling each lane.
10278 ///
10279 /// This will only succeed when the result of fixing the 128-bit lanes results
10280 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10281 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10282 /// the lane crosses early and then use simpler shuffles within each lane.
10283 ///
10284 /// FIXME: It might be worthwhile at some point to support this without
10285 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10286 /// in x86 only floating point has interesting non-repeating shuffles, and even
10287 /// those are still *marginally* more expensive.
10288 static SDValue lowerVectorShuffleByMerging128BitLanes(
10289     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10290     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10291   assert(!isSingleInputShuffleMask(Mask) &&
10292          "This is only useful with multiple inputs.");
10293
10294   int Size = Mask.size();
10295   int LaneSize = 128 / VT.getScalarSizeInBits();
10296   int NumLanes = Size / LaneSize;
10297   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10298
10299   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10300   // check whether the in-128-bit lane shuffles share a repeating pattern.
10301   SmallVector<int, 4> Lanes;
10302   Lanes.resize(NumLanes, -1);
10303   SmallVector<int, 4> InLaneMask;
10304   InLaneMask.resize(LaneSize, -1);
10305   for (int i = 0; i < Size; ++i) {
10306     if (Mask[i] < 0)
10307       continue;
10308
10309     int j = i / LaneSize;
10310
10311     if (Lanes[j] < 0) {
10312       // First entry we've seen for this lane.
10313       Lanes[j] = Mask[i] / LaneSize;
10314     } else if (Lanes[j] != Mask[i] / LaneSize) {
10315       // This doesn't match the lane selected previously!
10316       return SDValue();
10317     }
10318
10319     // Check that within each lane we have a consistent shuffle mask.
10320     int k = i % LaneSize;
10321     if (InLaneMask[k] < 0) {
10322       InLaneMask[k] = Mask[i] % LaneSize;
10323     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10324       // This doesn't fit a repeating in-lane mask.
10325       return SDValue();
10326     }
10327   }
10328
10329   // First shuffle the lanes into place.
10330   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10331                                 VT.getSizeInBits() / 64);
10332   SmallVector<int, 8> LaneMask;
10333   LaneMask.resize(NumLanes * 2, -1);
10334   for (int i = 0; i < NumLanes; ++i)
10335     if (Lanes[i] >= 0) {
10336       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10337       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10338     }
10339
10340   V1 = DAG.getBitcast(LaneVT, V1);
10341   V2 = DAG.getBitcast(LaneVT, V2);
10342   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10343
10344   // Cast it back to the type we actually want.
10345   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10346
10347   // Now do a simple shuffle that isn't lane crossing.
10348   SmallVector<int, 8> NewMask;
10349   NewMask.resize(Size, -1);
10350   for (int i = 0; i < Size; ++i)
10351     if (Mask[i] >= 0)
10352       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10353   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10354          "Must not introduce lane crosses at this point!");
10355
10356   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10357 }
10358
10359 /// Lower shuffles where an entire half of a 256-bit vector is UNDEF.
10360 /// This allows for fast cases such as subvector extraction/insertion
10361 /// or shuffling smaller vector types which can lower more efficiently.
10362 static SDValue lowerVectorShuffleWithUndefHalf(SDLoc DL, MVT VT, SDValue V1,
10363                                                SDValue V2, ArrayRef<int> Mask,
10364                                                const X86Subtarget *Subtarget,
10365                                                SelectionDAG &DAG) {
10366   assert(VT.getSizeInBits() == 256 && "Expected 256-bit vector");
10367
10368   unsigned NumElts = VT.getVectorNumElements();
10369   unsigned HalfNumElts = NumElts / 2;
10370   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(), HalfNumElts);
10371
10372   bool UndefLower = isUndefInRange(Mask, 0, HalfNumElts);
10373   bool UndefUpper = isUndefInRange(Mask, HalfNumElts, HalfNumElts);
10374   if (!UndefLower && !UndefUpper)
10375     return SDValue();
10376
10377   // Upper half is undef and lower half is whole upper subvector.
10378   // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
10379   if (UndefUpper &&
10380       isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
10381     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10382                              DAG.getIntPtrConstant(HalfNumElts, DL));
10383     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10384                        DAG.getIntPtrConstant(0, DL));
10385   }
10386
10387   // Lower half is undef and upper half is whole lower subvector.
10388   // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
10389   if (UndefLower &&
10390       isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
10391     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10392                              DAG.getIntPtrConstant(0, DL));
10393     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10394                        DAG.getIntPtrConstant(HalfNumElts, DL));
10395   }
10396
10397   // AVX2 supports efficient immediate 64-bit element cross-lane shuffles.
10398   if (UndefLower && Subtarget->hasAVX2() &&
10399       (VT == MVT::v4f64 || VT == MVT::v4i64))
10400     return SDValue();
10401
10402   // If the shuffle only uses the lower halves of the input operands,
10403   // then extract them and perform the 'half' shuffle at half width.
10404   // e.g. vector_shuffle <X, X, X, X, u, u, u, u> or <X, X, u, u>
10405   int HalfIdx1 = -1, HalfIdx2 = -1;
10406   SmallVector<int, 8> HalfMask;
10407   unsigned Offset = UndefLower ? HalfNumElts : 0;
10408   for (unsigned i = 0; i != HalfNumElts; ++i) {
10409     int M = Mask[i + Offset];
10410     if (M < 0) {
10411       HalfMask.push_back(M);
10412       continue;
10413     }
10414
10415     // Determine which of the 4 half vectors this element is from.
10416     // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
10417     int HalfIdx = M / HalfNumElts;
10418
10419     // Only shuffle using the lower halves of the inputs.
10420     // TODO: Investigate usefulness of shuffling with upper halves.
10421     if (HalfIdx != 0 && HalfIdx != 2)
10422       return SDValue();
10423
10424     // Determine the element index into its half vector source.
10425     int HalfElt = M % HalfNumElts;
10426
10427     // We can shuffle with up to 2 half vectors, set the new 'half'
10428     // shuffle mask accordingly.
10429     if (-1 == HalfIdx1 || HalfIdx1 == HalfIdx) {
10430       HalfMask.push_back(HalfElt);
10431       HalfIdx1 = HalfIdx;
10432       continue;
10433     }
10434     if (-1 == HalfIdx2 || HalfIdx2 == HalfIdx) {
10435       HalfMask.push_back(HalfElt + HalfNumElts);
10436       HalfIdx2 = HalfIdx;
10437       continue;
10438     }
10439
10440     // Too many half vectors referenced.
10441     return SDValue();
10442   }
10443   assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
10444
10445   auto GetHalfVector = [&](int HalfIdx) {
10446     if (HalfIdx < 0)
10447       return DAG.getUNDEF(HalfVT);
10448     SDValue V = (HalfIdx < 2 ? V1 : V2);
10449     HalfIdx = (HalfIdx % 2) * HalfNumElts;
10450     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
10451                        DAG.getIntPtrConstant(HalfIdx, DL));
10452   };
10453
10454   SDValue Half1 = GetHalfVector(HalfIdx1);
10455   SDValue Half2 = GetHalfVector(HalfIdx2);
10456   SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
10457   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
10458                      DAG.getIntPtrConstant(Offset, DL));
10459 }
10460
10461 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10462 /// given mask.
10463 ///
10464 /// This returns true if the elements from a particular input are already in the
10465 /// slot required by the given mask and require no permutation.
10466 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10467   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10468   int Size = Mask.size();
10469   for (int i = 0; i < Size; ++i)
10470     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10471       return false;
10472
10473   return true;
10474 }
10475
10476 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10477                                             ArrayRef<int> Mask, SDValue V1,
10478                                             SDValue V2, SelectionDAG &DAG) {
10479
10480   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
10481   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
10482   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10483   int NumElts = VT.getVectorNumElements();
10484   bool ShufpdMask = true;
10485   bool CommutableMask = true;
10486   unsigned Immediate = 0;
10487   for (int i = 0; i < NumElts; ++i) {
10488     if (Mask[i] < 0)
10489       continue;
10490     int Val = (i & 6) + NumElts * (i & 1);
10491     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10492     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10493       ShufpdMask = false;
10494     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10495       CommutableMask = false;
10496     Immediate |= (Mask[i] % 2) << i;
10497   }
10498   if (ShufpdMask)
10499     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10500                        DAG.getConstant(Immediate, DL, MVT::i8));
10501   if (CommutableMask)
10502     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10503                        DAG.getConstant(Immediate, DL, MVT::i8));
10504   return SDValue();
10505 }
10506
10507 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10508 ///
10509 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10510 /// isn't available.
10511 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10512                                        const X86Subtarget *Subtarget,
10513                                        SelectionDAG &DAG) {
10514   SDLoc DL(Op);
10515   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10516   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10517   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10518   ArrayRef<int> Mask = SVOp->getMask();
10519   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10520
10521   SmallVector<int, 4> WidenedMask;
10522   if (canWidenShuffleElements(Mask, WidenedMask))
10523     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10524                                     DAG);
10525
10526   if (isSingleInputShuffleMask(Mask)) {
10527     // Check for being able to broadcast a single element.
10528     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10529                                                           Mask, Subtarget, DAG))
10530       return Broadcast;
10531
10532     // Use low duplicate instructions for masks that match their pattern.
10533     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10534       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10535
10536     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10537       // Non-half-crossing single input shuffles can be lowerid with an
10538       // interleaved permutation.
10539       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10540                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10541       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10542                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10543     }
10544
10545     // With AVX2 we have direct support for this permutation.
10546     if (Subtarget->hasAVX2())
10547       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10548                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10549
10550     // Otherwise, fall back.
10551     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10552                                                    DAG);
10553   }
10554
10555   // Use dedicated unpack instructions for masks that match their pattern.
10556   if (SDValue V =
10557           lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10558     return V;
10559
10560   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10561                                                 Subtarget, DAG))
10562     return Blend;
10563
10564   // Check if the blend happens to exactly fit that of SHUFPD.
10565   if (SDValue Op =
10566       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10567     return Op;
10568
10569   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10570   // shuffle. However, if we have AVX2 and either inputs are already in place,
10571   // we will be able to shuffle even across lanes the other input in a single
10572   // instruction so skip this pattern.
10573   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10574                                  isShuffleMaskInputInPlace(1, Mask))))
10575     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10576             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10577       return Result;
10578
10579   // If we have AVX2 then we always want to lower with a blend because an v4 we
10580   // can fully permute the elements.
10581   if (Subtarget->hasAVX2())
10582     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10583                                                       Mask, DAG);
10584
10585   // Otherwise fall back on generic lowering.
10586   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10587 }
10588
10589 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10590 ///
10591 /// This routine is only called when we have AVX2 and thus a reasonable
10592 /// instruction set for v4i64 shuffling..
10593 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10594                                        const X86Subtarget *Subtarget,
10595                                        SelectionDAG &DAG) {
10596   SDLoc DL(Op);
10597   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10598   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10599   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10600   ArrayRef<int> Mask = SVOp->getMask();
10601   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10602   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10603
10604   SmallVector<int, 4> WidenedMask;
10605   if (canWidenShuffleElements(Mask, WidenedMask))
10606     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10607                                     DAG);
10608
10609   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10610                                                 Subtarget, DAG))
10611     return Blend;
10612
10613   // Check for being able to broadcast a single element.
10614   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10615                                                         Mask, Subtarget, DAG))
10616     return Broadcast;
10617
10618   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10619   // use lower latency instructions that will operate on both 128-bit lanes.
10620   SmallVector<int, 2> RepeatedMask;
10621   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10622     if (isSingleInputShuffleMask(Mask)) {
10623       int PSHUFDMask[] = {-1, -1, -1, -1};
10624       for (int i = 0; i < 2; ++i)
10625         if (RepeatedMask[i] >= 0) {
10626           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10627           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10628         }
10629       return DAG.getBitcast(
10630           MVT::v4i64,
10631           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10632                       DAG.getBitcast(MVT::v8i32, V1),
10633                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10634     }
10635   }
10636
10637   // AVX2 provides a direct instruction for permuting a single input across
10638   // lanes.
10639   if (isSingleInputShuffleMask(Mask))
10640     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10641                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10642
10643   // Try to use shift instructions.
10644   if (SDValue Shift =
10645           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10646     return Shift;
10647
10648   // Use dedicated unpack instructions for masks that match their pattern.
10649   if (SDValue V =
10650           lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10651     return V;
10652
10653   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10654   // shuffle. However, if we have AVX2 and either inputs are already in place,
10655   // we will be able to shuffle even across lanes the other input in a single
10656   // instruction so skip this pattern.
10657   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10658                                  isShuffleMaskInputInPlace(1, Mask))))
10659     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10660             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10661       return Result;
10662
10663   // Otherwise fall back on generic blend lowering.
10664   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10665                                                     Mask, DAG);
10666 }
10667
10668 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10669 ///
10670 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10671 /// isn't available.
10672 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10673                                        const X86Subtarget *Subtarget,
10674                                        SelectionDAG &DAG) {
10675   SDLoc DL(Op);
10676   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10677   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10678   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10679   ArrayRef<int> Mask = SVOp->getMask();
10680   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10681
10682   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10683                                                 Subtarget, DAG))
10684     return Blend;
10685
10686   // Check for being able to broadcast a single element.
10687   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10688                                                         Mask, Subtarget, DAG))
10689     return Broadcast;
10690
10691   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10692   // options to efficiently lower the shuffle.
10693   SmallVector<int, 4> RepeatedMask;
10694   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10695     assert(RepeatedMask.size() == 4 &&
10696            "Repeated masks must be half the mask width!");
10697
10698     // Use even/odd duplicate instructions for masks that match their pattern.
10699     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10700       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10701     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10702       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10703
10704     if (isSingleInputShuffleMask(Mask))
10705       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10706                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10707
10708     // Use dedicated unpack instructions for masks that match their pattern.
10709     if (SDValue V =
10710             lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10711       return V;
10712
10713     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10714     // have already handled any direct blends. We also need to squash the
10715     // repeated mask into a simulated v4f32 mask.
10716     for (int i = 0; i < 4; ++i)
10717       if (RepeatedMask[i] >= 8)
10718         RepeatedMask[i] -= 4;
10719     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10720   }
10721
10722   // If we have a single input shuffle with different shuffle patterns in the
10723   // two 128-bit lanes use the variable mask to VPERMILPS.
10724   if (isSingleInputShuffleMask(Mask)) {
10725     SDValue VPermMask[8];
10726     for (int i = 0; i < 8; ++i)
10727       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10728                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10729     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10730       return DAG.getNode(
10731           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10732           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10733
10734     if (Subtarget->hasAVX2())
10735       return DAG.getNode(
10736           X86ISD::VPERMV, DL, MVT::v8f32,
10737           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10738
10739     // Otherwise, fall back.
10740     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10741                                                    DAG);
10742   }
10743
10744   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10745   // shuffle.
10746   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10747           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10748     return Result;
10749
10750   // If we have AVX2 then we always want to lower with a blend because at v8 we
10751   // can fully permute the elements.
10752   if (Subtarget->hasAVX2())
10753     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10754                                                       Mask, DAG);
10755
10756   // Otherwise fall back on generic lowering.
10757   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10758 }
10759
10760 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10761 ///
10762 /// This routine is only called when we have AVX2 and thus a reasonable
10763 /// instruction set for v8i32 shuffling..
10764 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10765                                        const X86Subtarget *Subtarget,
10766                                        SelectionDAG &DAG) {
10767   SDLoc DL(Op);
10768   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10769   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10770   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10771   ArrayRef<int> Mask = SVOp->getMask();
10772   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10773   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10774
10775   // Whenever we can lower this as a zext, that instruction is strictly faster
10776   // than any alternative. It also allows us to fold memory operands into the
10777   // shuffle in many cases.
10778   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10779                                                          Mask, Subtarget, DAG))
10780     return ZExt;
10781
10782   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10783                                                 Subtarget, DAG))
10784     return Blend;
10785
10786   // Check for being able to broadcast a single element.
10787   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10788                                                         Mask, Subtarget, DAG))
10789     return Broadcast;
10790
10791   // If the shuffle mask is repeated in each 128-bit lane we can use more
10792   // efficient instructions that mirror the shuffles across the two 128-bit
10793   // lanes.
10794   SmallVector<int, 4> RepeatedMask;
10795   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10796     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10797     if (isSingleInputShuffleMask(Mask))
10798       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10799                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10800
10801     // Use dedicated unpack instructions for masks that match their pattern.
10802     if (SDValue V =
10803             lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10804       return V;
10805   }
10806
10807   // Try to use shift instructions.
10808   if (SDValue Shift =
10809           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10810     return Shift;
10811
10812   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10813           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10814     return Rotate;
10815
10816   // If the shuffle patterns aren't repeated but it is a single input, directly
10817   // generate a cross-lane VPERMD instruction.
10818   if (isSingleInputShuffleMask(Mask)) {
10819     SDValue VPermMask[8];
10820     for (int i = 0; i < 8; ++i)
10821       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10822                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10823     return DAG.getNode(
10824         X86ISD::VPERMV, DL, MVT::v8i32,
10825         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10826   }
10827
10828   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10829   // shuffle.
10830   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10831           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10832     return Result;
10833
10834   // Otherwise fall back on generic blend lowering.
10835   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10836                                                     Mask, DAG);
10837 }
10838
10839 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10840 ///
10841 /// This routine is only called when we have AVX2 and thus a reasonable
10842 /// instruction set for v16i16 shuffling..
10843 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10844                                         const X86Subtarget *Subtarget,
10845                                         SelectionDAG &DAG) {
10846   SDLoc DL(Op);
10847   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10848   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10849   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10850   ArrayRef<int> Mask = SVOp->getMask();
10851   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10852   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10853
10854   // Whenever we can lower this as a zext, that instruction is strictly faster
10855   // than any alternative. It also allows us to fold memory operands into the
10856   // shuffle in many cases.
10857   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10858                                                          Mask, Subtarget, DAG))
10859     return ZExt;
10860
10861   // Check for being able to broadcast a single element.
10862   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10863                                                         Mask, Subtarget, DAG))
10864     return Broadcast;
10865
10866   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10867                                                 Subtarget, DAG))
10868     return Blend;
10869
10870   // Use dedicated unpack instructions for masks that match their pattern.
10871   if (SDValue V =
10872           lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10873     return V;
10874
10875   // Try to use shift instructions.
10876   if (SDValue Shift =
10877           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10878     return Shift;
10879
10880   // Try to use byte rotation instructions.
10881   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10882           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10883     return Rotate;
10884
10885   if (isSingleInputShuffleMask(Mask)) {
10886     // There are no generalized cross-lane shuffle operations available on i16
10887     // element types.
10888     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10889       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10890                                                      Mask, DAG);
10891
10892     SmallVector<int, 8> RepeatedMask;
10893     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10894       // As this is a single-input shuffle, the repeated mask should be
10895       // a strictly valid v8i16 mask that we can pass through to the v8i16
10896       // lowering to handle even the v16 case.
10897       return lowerV8I16GeneralSingleInputVectorShuffle(
10898           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10899     }
10900
10901     SDValue PSHUFBMask[32];
10902     for (int i = 0; i < 16; ++i) {
10903       if (Mask[i] == -1) {
10904         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10905         continue;
10906       }
10907
10908       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10909       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10910       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10911       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10912     }
10913     return DAG.getBitcast(MVT::v16i16,
10914                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10915                                       DAG.getBitcast(MVT::v32i8, V1),
10916                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10917                                                   MVT::v32i8, PSHUFBMask)));
10918   }
10919
10920   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10921   // shuffle.
10922   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10923           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10924     return Result;
10925
10926   // Otherwise fall back on generic lowering.
10927   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10928 }
10929
10930 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10931 ///
10932 /// This routine is only called when we have AVX2 and thus a reasonable
10933 /// instruction set for v32i8 shuffling..
10934 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10935                                        const X86Subtarget *Subtarget,
10936                                        SelectionDAG &DAG) {
10937   SDLoc DL(Op);
10938   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10939   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10940   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10941   ArrayRef<int> Mask = SVOp->getMask();
10942   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10943   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10944
10945   // Whenever we can lower this as a zext, that instruction is strictly faster
10946   // than any alternative. It also allows us to fold memory operands into the
10947   // shuffle in many cases.
10948   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10949                                                          Mask, Subtarget, DAG))
10950     return ZExt;
10951
10952   // Check for being able to broadcast a single element.
10953   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10954                                                         Mask, Subtarget, DAG))
10955     return Broadcast;
10956
10957   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10958                                                 Subtarget, DAG))
10959     return Blend;
10960
10961   // Use dedicated unpack instructions for masks that match their pattern.
10962   if (SDValue V =
10963           lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
10964     return V;
10965
10966   // Try to use shift instructions.
10967   if (SDValue Shift =
10968           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10969     return Shift;
10970
10971   // Try to use byte rotation instructions.
10972   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10973           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10974     return Rotate;
10975
10976   if (isSingleInputShuffleMask(Mask)) {
10977     // There are no generalized cross-lane shuffle operations available on i8
10978     // element types.
10979     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10980       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10981                                                      Mask, DAG);
10982
10983     SDValue PSHUFBMask[32];
10984     for (int i = 0; i < 32; ++i)
10985       PSHUFBMask[i] =
10986           Mask[i] < 0
10987               ? DAG.getUNDEF(MVT::i8)
10988               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10989                                 MVT::i8);
10990
10991     return DAG.getNode(
10992         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10993         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10994   }
10995
10996   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10997   // shuffle.
10998   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10999           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11000     return Result;
11001
11002   // Otherwise fall back on generic lowering.
11003   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
11004 }
11005
11006 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
11007 ///
11008 /// This routine either breaks down the specific type of a 256-bit x86 vector
11009 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
11010 /// together based on the available instructions.
11011 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11012                                         MVT VT, const X86Subtarget *Subtarget,
11013                                         SelectionDAG &DAG) {
11014   SDLoc DL(Op);
11015   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11016   ArrayRef<int> Mask = SVOp->getMask();
11017
11018   // If we have a single input to the zero element, insert that into V1 if we
11019   // can do so cheaply.
11020   int NumElts = VT.getVectorNumElements();
11021   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
11022     return M >= NumElts;
11023   });
11024
11025   if (NumV2Elements == 1 && Mask[0] >= NumElts)
11026     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
11027                               DL, VT, V1, V2, Mask, Subtarget, DAG))
11028       return Insertion;
11029
11030   // Handle special cases where the lower or upper half is UNDEF.
11031   if (SDValue V =
11032           lowerVectorShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
11033     return V;
11034
11035   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
11036   // can check for those subtargets here and avoid much of the subtarget
11037   // querying in the per-vector-type lowering routines. With AVX1 we have
11038   // essentially *zero* ability to manipulate a 256-bit vector with integer
11039   // types. Since we'll use floating point types there eventually, just
11040   // immediately cast everything to a float and operate entirely in that domain.
11041   if (VT.isInteger() && !Subtarget->hasAVX2()) {
11042     int ElementBits = VT.getScalarSizeInBits();
11043     if (ElementBits < 32)
11044       // No floating point type available, decompose into 128-bit vectors.
11045       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11046
11047     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
11048                                 VT.getVectorNumElements());
11049     V1 = DAG.getBitcast(FpVT, V1);
11050     V2 = DAG.getBitcast(FpVT, V2);
11051     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
11052   }
11053
11054   switch (VT.SimpleTy) {
11055   case MVT::v4f64:
11056     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11057   case MVT::v4i64:
11058     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11059   case MVT::v8f32:
11060     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11061   case MVT::v8i32:
11062     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11063   case MVT::v16i16:
11064     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11065   case MVT::v32i8:
11066     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11067
11068   default:
11069     llvm_unreachable("Not a valid 256-bit x86 vector type!");
11070   }
11071 }
11072
11073 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
11074 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
11075                                         ArrayRef<int> Mask,
11076                                         SDValue V1, SDValue V2,
11077                                         SelectionDAG &DAG) {
11078   assert(VT.getScalarSizeInBits() == 64 &&
11079          "Unexpected element type size for 128bit shuffle.");
11080
11081   // To handle 256 bit vector requires VLX and most probably
11082   // function lowerV2X128VectorShuffle() is better solution.
11083   assert(VT.is512BitVector() && "Unexpected vector size for 128bit shuffle.");
11084
11085   SmallVector<int, 4> WidenedMask;
11086   if (!canWidenShuffleElements(Mask, WidenedMask))
11087     return SDValue();
11088
11089   // Form a 128-bit permutation.
11090   // Convert the 64-bit shuffle mask selection values into 128-bit selection
11091   // bits defined by a vshuf64x2 instruction's immediate control byte.
11092   unsigned PermMask = 0, Imm = 0;
11093   unsigned ControlBitsNum = WidenedMask.size() / 2;
11094
11095   for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
11096     if (WidenedMask[i] == SM_SentinelZero)
11097       return SDValue();
11098
11099     // Use first element in place of undef mask.
11100     Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
11101     PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
11102   }
11103
11104   return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
11105                      DAG.getConstant(PermMask, DL, MVT::i8));
11106 }
11107
11108 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
11109                                            ArrayRef<int> Mask, SDValue V1,
11110                                            SDValue V2, SelectionDAG &DAG) {
11111
11112   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
11113
11114   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
11115   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
11116
11117   SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
11118   if (isSingleInputShuffleMask(Mask))
11119     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
11120
11121   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
11122 }
11123
11124 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
11125 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11126                                        const X86Subtarget *Subtarget,
11127                                        SelectionDAG &DAG) {
11128   SDLoc DL(Op);
11129   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11130   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11131   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11132   ArrayRef<int> Mask = SVOp->getMask();
11133   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11134
11135   if (SDValue Shuf128 =
11136           lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
11137     return Shuf128;
11138
11139   if (SDValue Unpck =
11140           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
11141     return Unpck;
11142
11143   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
11144 }
11145
11146 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
11147 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11148                                         const X86Subtarget *Subtarget,
11149                                         SelectionDAG &DAG) {
11150   SDLoc DL(Op);
11151   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11152   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11153   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11154   ArrayRef<int> Mask = SVOp->getMask();
11155   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11156
11157   if (SDValue Unpck =
11158           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
11159     return Unpck;
11160
11161   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
11162 }
11163
11164 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
11165 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11166                                        const X86Subtarget *Subtarget,
11167                                        SelectionDAG &DAG) {
11168   SDLoc DL(Op);
11169   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11170   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11171   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11172   ArrayRef<int> Mask = SVOp->getMask();
11173   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11174
11175   if (SDValue Shuf128 =
11176           lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
11177     return Shuf128;
11178
11179   if (SDValue Unpck =
11180           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
11181     return Unpck;
11182
11183   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
11184 }
11185
11186 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
11187 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11188                                         const X86Subtarget *Subtarget,
11189                                         SelectionDAG &DAG) {
11190   SDLoc DL(Op);
11191   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11192   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11193   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11194   ArrayRef<int> Mask = SVOp->getMask();
11195   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11196
11197   if (SDValue Unpck =
11198           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
11199     return Unpck;
11200
11201   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
11202 }
11203
11204 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
11205 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11206                                         const X86Subtarget *Subtarget,
11207                                         SelectionDAG &DAG) {
11208   SDLoc DL(Op);
11209   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11210   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11211   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11212   ArrayRef<int> Mask = SVOp->getMask();
11213   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11214   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
11215
11216   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
11217 }
11218
11219 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
11220 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11221                                        const X86Subtarget *Subtarget,
11222                                        SelectionDAG &DAG) {
11223   SDLoc DL(Op);
11224   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11225   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11226   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11227   ArrayRef<int> Mask = SVOp->getMask();
11228   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
11229   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
11230
11231   // FIXME: Implement direct support for this type!
11232   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
11233 }
11234
11235 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
11236 ///
11237 /// This routine either breaks down the specific type of a 512-bit x86 vector
11238 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
11239 /// together based on the available instructions.
11240 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11241                                         MVT VT, const X86Subtarget *Subtarget,
11242                                         SelectionDAG &DAG) {
11243   SDLoc DL(Op);
11244   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11245   ArrayRef<int> Mask = SVOp->getMask();
11246   assert(Subtarget->hasAVX512() &&
11247          "Cannot lower 512-bit vectors w/ basic ISA!");
11248
11249   // Check for being able to broadcast a single element.
11250   if (SDValue Broadcast =
11251           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
11252     return Broadcast;
11253
11254   // Dispatch to each element type for lowering. If we don't have supprot for
11255   // specific element type shuffles at 512 bits, immediately split them and
11256   // lower them. Each lowering routine of a given type is allowed to assume that
11257   // the requisite ISA extensions for that element type are available.
11258   switch (VT.SimpleTy) {
11259   case MVT::v8f64:
11260     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11261   case MVT::v16f32:
11262     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11263   case MVT::v8i64:
11264     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11265   case MVT::v16i32:
11266     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11267   case MVT::v32i16:
11268     if (Subtarget->hasBWI())
11269       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11270     break;
11271   case MVT::v64i8:
11272     if (Subtarget->hasBWI())
11273       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11274     break;
11275
11276   default:
11277     llvm_unreachable("Not a valid 512-bit x86 vector type!");
11278   }
11279
11280   // Otherwise fall back on splitting.
11281   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11282 }
11283
11284 // Lower vXi1 vector shuffles.
11285 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
11286 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
11287 // vector, shuffle and then truncate it back.
11288 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11289                                       MVT VT, const X86Subtarget *Subtarget,
11290                                       SelectionDAG &DAG) {
11291   SDLoc DL(Op);
11292   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11293   ArrayRef<int> Mask = SVOp->getMask();
11294   assert(Subtarget->hasAVX512() &&
11295          "Cannot lower 512-bit vectors w/o basic ISA!");
11296   MVT ExtVT;
11297   switch (VT.SimpleTy) {
11298   default:
11299     llvm_unreachable("Expected a vector of i1 elements");
11300   case MVT::v2i1:
11301     ExtVT = MVT::v2i64;
11302     break;
11303   case MVT::v4i1:
11304     ExtVT = MVT::v4i32;
11305     break;
11306   case MVT::v8i1:
11307     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
11308     break;
11309   case MVT::v16i1:
11310     ExtVT = MVT::v16i32;
11311     break;
11312   case MVT::v32i1:
11313     ExtVT = MVT::v32i16;
11314     break;
11315   case MVT::v64i1:
11316     ExtVT = MVT::v64i8;
11317     break;
11318   }
11319
11320   if (ISD::isBuildVectorAllZeros(V1.getNode()))
11321     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11322   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
11323     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11324   else
11325     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
11326
11327   if (V2.isUndef())
11328     V2 = DAG.getUNDEF(ExtVT);
11329   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
11330     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11331   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
11332     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11333   else
11334     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11335   return DAG.getNode(ISD::TRUNCATE, DL, VT,
11336                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11337 }
11338 /// \brief Top-level lowering for x86 vector shuffles.
11339 ///
11340 /// This handles decomposition, canonicalization, and lowering of all x86
11341 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11342 /// above in helper routines. The canonicalization attempts to widen shuffles
11343 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11344 /// s.t. only one of the two inputs needs to be tested, etc.
11345 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11346                                   SelectionDAG &DAG) {
11347   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11348   ArrayRef<int> Mask = SVOp->getMask();
11349   SDValue V1 = Op.getOperand(0);
11350   SDValue V2 = Op.getOperand(1);
11351   MVT VT = Op.getSimpleValueType();
11352   int NumElements = VT.getVectorNumElements();
11353   SDLoc dl(Op);
11354   bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
11355
11356   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11357          "Can't lower MMX shuffles");
11358
11359   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11360   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11361   if (V1IsUndef && V2IsUndef)
11362     return DAG.getUNDEF(VT);
11363
11364   // When we create a shuffle node we put the UNDEF node to second operand,
11365   // but in some cases the first operand may be transformed to UNDEF.
11366   // In this case we should just commute the node.
11367   if (V1IsUndef)
11368     return DAG.getCommutedVectorShuffle(*SVOp);
11369
11370   // Check for non-undef masks pointing at an undef vector and make the masks
11371   // undef as well. This makes it easier to match the shuffle based solely on
11372   // the mask.
11373   if (V2IsUndef)
11374     for (int M : Mask)
11375       if (M >= NumElements) {
11376         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11377         for (int &M : NewMask)
11378           if (M >= NumElements)
11379             M = -1;
11380         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11381       }
11382
11383   // We actually see shuffles that are entirely re-arrangements of a set of
11384   // zero inputs. This mostly happens while decomposing complex shuffles into
11385   // simple ones. Directly lower these as a buildvector of zeros.
11386   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11387   if (Zeroable.all())
11388     return getZeroVector(VT, Subtarget, DAG, dl);
11389
11390   // Try to collapse shuffles into using a vector type with fewer elements but
11391   // wider element types. We cap this to not form integers or floating point
11392   // elements wider than 64 bits, but it might be interesting to form i128
11393   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11394   SmallVector<int, 16> WidenedMask;
11395   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11396       canWidenShuffleElements(Mask, WidenedMask)) {
11397     MVT NewEltVT = VT.isFloatingPoint()
11398                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11399                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11400     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11401     // Make sure that the new vector type is legal. For example, v2f64 isn't
11402     // legal on SSE1.
11403     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11404       V1 = DAG.getBitcast(NewVT, V1);
11405       V2 = DAG.getBitcast(NewVT, V2);
11406       return DAG.getBitcast(
11407           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11408     }
11409   }
11410
11411   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11412   for (int M : SVOp->getMask())
11413     if (M < 0)
11414       ++NumUndefElements;
11415     else if (M < NumElements)
11416       ++NumV1Elements;
11417     else
11418       ++NumV2Elements;
11419
11420   // Commute the shuffle as needed such that more elements come from V1 than
11421   // V2. This allows us to match the shuffle pattern strictly on how many
11422   // elements come from V1 without handling the symmetric cases.
11423   if (NumV2Elements > NumV1Elements)
11424     return DAG.getCommutedVectorShuffle(*SVOp);
11425
11426   // When the number of V1 and V2 elements are the same, try to minimize the
11427   // number of uses of V2 in the low half of the vector. When that is tied,
11428   // ensure that the sum of indices for V1 is equal to or lower than the sum
11429   // indices for V2. When those are equal, try to ensure that the number of odd
11430   // indices for V1 is lower than the number of odd indices for V2.
11431   if (NumV1Elements == NumV2Elements) {
11432     int LowV1Elements = 0, LowV2Elements = 0;
11433     for (int M : SVOp->getMask().slice(0, NumElements / 2))
11434       if (M >= NumElements)
11435         ++LowV2Elements;
11436       else if (M >= 0)
11437         ++LowV1Elements;
11438     if (LowV2Elements > LowV1Elements) {
11439       return DAG.getCommutedVectorShuffle(*SVOp);
11440     } else if (LowV2Elements == LowV1Elements) {
11441       int SumV1Indices = 0, SumV2Indices = 0;
11442       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11443         if (SVOp->getMask()[i] >= NumElements)
11444           SumV2Indices += i;
11445         else if (SVOp->getMask()[i] >= 0)
11446           SumV1Indices += i;
11447       if (SumV2Indices < SumV1Indices) {
11448         return DAG.getCommutedVectorShuffle(*SVOp);
11449       } else if (SumV2Indices == SumV1Indices) {
11450         int NumV1OddIndices = 0, NumV2OddIndices = 0;
11451         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11452           if (SVOp->getMask()[i] >= NumElements)
11453             NumV2OddIndices += i % 2;
11454           else if (SVOp->getMask()[i] >= 0)
11455             NumV1OddIndices += i % 2;
11456         if (NumV2OddIndices < NumV1OddIndices)
11457           return DAG.getCommutedVectorShuffle(*SVOp);
11458       }
11459     }
11460   }
11461
11462   // For each vector width, delegate to a specialized lowering routine.
11463   if (VT.is128BitVector())
11464     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11465
11466   if (VT.is256BitVector())
11467     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11468
11469   if (VT.is512BitVector())
11470     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11471
11472   if (Is1BitVector)
11473     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11474   llvm_unreachable("Unimplemented!");
11475 }
11476
11477 // This function assumes its argument is a BUILD_VECTOR of constants or
11478 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11479 // true.
11480 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11481                                     unsigned &MaskValue) {
11482   MaskValue = 0;
11483   unsigned NumElems = BuildVector->getNumOperands();
11484
11485   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11486   // We don't handle the >2 lanes case right now.
11487   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11488   if (NumLanes > 2)
11489     return false;
11490
11491   unsigned NumElemsInLane = NumElems / NumLanes;
11492
11493   // Blend for v16i16 should be symmetric for the both lanes.
11494   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11495     SDValue EltCond = BuildVector->getOperand(i);
11496     SDValue SndLaneEltCond =
11497         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11498
11499     int Lane1Cond = -1, Lane2Cond = -1;
11500     if (isa<ConstantSDNode>(EltCond))
11501       Lane1Cond = !isNullConstant(EltCond);
11502     if (isa<ConstantSDNode>(SndLaneEltCond))
11503       Lane2Cond = !isNullConstant(SndLaneEltCond);
11504
11505     unsigned LaneMask = 0;
11506     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11507       // Lane1Cond != 0, means we want the first argument.
11508       // Lane1Cond == 0, means we want the second argument.
11509       // The encoding of this argument is 0 for the first argument, 1
11510       // for the second. Therefore, invert the condition.
11511       LaneMask = !Lane1Cond << i;
11512     else if (Lane1Cond < 0)
11513       LaneMask = !Lane2Cond << i;
11514     else
11515       return false;
11516
11517     MaskValue |= LaneMask;
11518     if (NumLanes == 2)
11519       MaskValue |= LaneMask << NumElemsInLane;
11520   }
11521   return true;
11522 }
11523
11524 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11525 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11526                                            const X86Subtarget *Subtarget,
11527                                            SelectionDAG &DAG) {
11528   SDValue Cond = Op.getOperand(0);
11529   SDValue LHS = Op.getOperand(1);
11530   SDValue RHS = Op.getOperand(2);
11531   SDLoc dl(Op);
11532   MVT VT = Op.getSimpleValueType();
11533
11534   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11535     return SDValue();
11536   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11537
11538   // Only non-legal VSELECTs reach this lowering, convert those into generic
11539   // shuffles and re-use the shuffle lowering path for blends.
11540   SmallVector<int, 32> Mask;
11541   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11542     SDValue CondElt = CondBV->getOperand(i);
11543     Mask.push_back(
11544         isa<ConstantSDNode>(CondElt) ? i + (isNullConstant(CondElt) ? Size : 0)
11545                                      : -1);
11546   }
11547   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11548 }
11549
11550 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11551   // A vselect where all conditions and data are constants can be optimized into
11552   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11553   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11554       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11555       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11556     return SDValue();
11557
11558   // Try to lower this to a blend-style vector shuffle. This can handle all
11559   // constant condition cases.
11560   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11561     return BlendOp;
11562
11563   // Variable blends are only legal from SSE4.1 onward.
11564   if (!Subtarget->hasSSE41())
11565     return SDValue();
11566
11567   // Only some types will be legal on some subtargets. If we can emit a legal
11568   // VSELECT-matching blend, return Op, and but if we need to expand, return
11569   // a null value.
11570   switch (Op.getSimpleValueType().SimpleTy) {
11571   default:
11572     // Most of the vector types have blends past SSE4.1.
11573     return Op;
11574
11575   case MVT::v32i8:
11576     // The byte blends for AVX vectors were introduced only in AVX2.
11577     if (Subtarget->hasAVX2())
11578       return Op;
11579
11580     return SDValue();
11581
11582   case MVT::v8i16:
11583   case MVT::v16i16:
11584     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11585     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11586       return Op;
11587
11588     // FIXME: We should custom lower this by fixing the condition and using i8
11589     // blends.
11590     return SDValue();
11591   }
11592 }
11593
11594 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11595   MVT VT = Op.getSimpleValueType();
11596   SDLoc dl(Op);
11597
11598   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11599     return SDValue();
11600
11601   if (VT.getSizeInBits() == 8) {
11602     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11603                                   Op.getOperand(0), Op.getOperand(1));
11604     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11605                                   DAG.getValueType(VT));
11606     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11607   }
11608
11609   if (VT.getSizeInBits() == 16) {
11610     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11611     if (isNullConstant(Op.getOperand(1)))
11612       return DAG.getNode(
11613           ISD::TRUNCATE, dl, MVT::i16,
11614           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11615                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11616                       Op.getOperand(1)));
11617     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11618                                   Op.getOperand(0), Op.getOperand(1));
11619     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11620                                   DAG.getValueType(VT));
11621     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11622   }
11623
11624   if (VT == MVT::f32) {
11625     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11626     // the result back to FR32 register. It's only worth matching if the
11627     // result has a single use which is a store or a bitcast to i32.  And in
11628     // the case of a store, it's not worth it if the index is a constant 0,
11629     // because a MOVSSmr can be used instead, which is smaller and faster.
11630     if (!Op.hasOneUse())
11631       return SDValue();
11632     SDNode *User = *Op.getNode()->use_begin();
11633     if ((User->getOpcode() != ISD::STORE ||
11634          isNullConstant(Op.getOperand(1))) &&
11635         (User->getOpcode() != ISD::BITCAST ||
11636          User->getValueType(0) != MVT::i32))
11637       return SDValue();
11638     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11639                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11640                                   Op.getOperand(1));
11641     return DAG.getBitcast(MVT::f32, Extract);
11642   }
11643
11644   if (VT == MVT::i32 || VT == MVT::i64) {
11645     // ExtractPS/pextrq works with constant index.
11646     if (isa<ConstantSDNode>(Op.getOperand(1)))
11647       return Op;
11648   }
11649   return SDValue();
11650 }
11651
11652 /// Extract one bit from mask vector, like v16i1 or v8i1.
11653 /// AVX-512 feature.
11654 SDValue
11655 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11656   SDValue Vec = Op.getOperand(0);
11657   SDLoc dl(Vec);
11658   MVT VecVT = Vec.getSimpleValueType();
11659   SDValue Idx = Op.getOperand(1);
11660   MVT EltVT = Op.getSimpleValueType();
11661
11662   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11663   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11664          "Unexpected vector type in ExtractBitFromMaskVector");
11665
11666   // variable index can't be handled in mask registers,
11667   // extend vector to VR512
11668   if (!isa<ConstantSDNode>(Idx)) {
11669     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11670     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11671     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11672                               ExtVT.getVectorElementType(), Ext, Idx);
11673     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11674   }
11675
11676   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11677   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11678   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11679     rc = getRegClassFor(MVT::v16i1);
11680   unsigned MaxSift = rc->getSize()*8 - 1;
11681   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11682                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11683   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11684                     DAG.getConstant(MaxSift, dl, MVT::i8));
11685   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11686                        DAG.getIntPtrConstant(0, dl));
11687 }
11688
11689 SDValue
11690 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11691                                            SelectionDAG &DAG) const {
11692   SDLoc dl(Op);
11693   SDValue Vec = Op.getOperand(0);
11694   MVT VecVT = Vec.getSimpleValueType();
11695   SDValue Idx = Op.getOperand(1);
11696
11697   if (Op.getSimpleValueType() == MVT::i1)
11698     return ExtractBitFromMaskVector(Op, DAG);
11699
11700   if (!isa<ConstantSDNode>(Idx)) {
11701     if (VecVT.is512BitVector() ||
11702         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11703          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11704
11705       MVT MaskEltVT =
11706         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11707       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11708                                     MaskEltVT.getSizeInBits());
11709
11710       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11711       auto PtrVT = getPointerTy(DAG.getDataLayout());
11712       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11713                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11714                                  DAG.getConstant(0, dl, PtrVT));
11715       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11716       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11717                          DAG.getConstant(0, dl, PtrVT));
11718     }
11719     return SDValue();
11720   }
11721
11722   // If this is a 256-bit vector result, first extract the 128-bit vector and
11723   // then extract the element from the 128-bit vector.
11724   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11725
11726     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11727     // Get the 128-bit vector.
11728     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11729     MVT EltVT = VecVT.getVectorElementType();
11730
11731     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11732     assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
11733
11734     // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
11735     // this can be done with a mask.
11736     IdxVal &= ElemsPerChunk - 1;
11737     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11738                        DAG.getConstant(IdxVal, dl, MVT::i32));
11739   }
11740
11741   assert(VecVT.is128BitVector() && "Unexpected vector length");
11742
11743   if (Subtarget->hasSSE41())
11744     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11745       return Res;
11746
11747   MVT VT = Op.getSimpleValueType();
11748   // TODO: handle v16i8.
11749   if (VT.getSizeInBits() == 16) {
11750     SDValue Vec = Op.getOperand(0);
11751     if (isNullConstant(Op.getOperand(1)))
11752       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11753                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11754                                      DAG.getBitcast(MVT::v4i32, Vec),
11755                                      Op.getOperand(1)));
11756     // Transform it so it match pextrw which produces a 32-bit result.
11757     MVT EltVT = MVT::i32;
11758     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11759                                   Op.getOperand(0), Op.getOperand(1));
11760     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11761                                   DAG.getValueType(VT));
11762     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11763   }
11764
11765   if (VT.getSizeInBits() == 32) {
11766     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11767     if (Idx == 0)
11768       return Op;
11769
11770     // SHUFPS the element to the lowest double word, then movss.
11771     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11772     MVT VVT = Op.getOperand(0).getSimpleValueType();
11773     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11774                                        DAG.getUNDEF(VVT), Mask);
11775     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11776                        DAG.getIntPtrConstant(0, dl));
11777   }
11778
11779   if (VT.getSizeInBits() == 64) {
11780     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11781     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11782     //        to match extract_elt for f64.
11783     if (isNullConstant(Op.getOperand(1)))
11784       return Op;
11785
11786     // UNPCKHPD the element to the lowest double word, then movsd.
11787     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11788     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11789     int Mask[2] = { 1, -1 };
11790     MVT VVT = Op.getOperand(0).getSimpleValueType();
11791     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11792                                        DAG.getUNDEF(VVT), Mask);
11793     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11794                        DAG.getIntPtrConstant(0, dl));
11795   }
11796
11797   return SDValue();
11798 }
11799
11800 /// Insert one bit to mask vector, like v16i1 or v8i1.
11801 /// AVX-512 feature.
11802 SDValue
11803 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11804   SDLoc dl(Op);
11805   SDValue Vec = Op.getOperand(0);
11806   SDValue Elt = Op.getOperand(1);
11807   SDValue Idx = Op.getOperand(2);
11808   MVT VecVT = Vec.getSimpleValueType();
11809
11810   if (!isa<ConstantSDNode>(Idx)) {
11811     // Non constant index. Extend source and destination,
11812     // insert element and then truncate the result.
11813     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11814     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11815     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11816       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11817       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11818     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11819   }
11820
11821   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11822   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11823   if (IdxVal)
11824     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11825                            DAG.getConstant(IdxVal, dl, MVT::i8));
11826   if (Vec.getOpcode() == ISD::UNDEF)
11827     return EltInVec;
11828   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11829 }
11830
11831 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11832                                                   SelectionDAG &DAG) const {
11833   MVT VT = Op.getSimpleValueType();
11834   MVT EltVT = VT.getVectorElementType();
11835
11836   if (EltVT == MVT::i1)
11837     return InsertBitToMaskVector(Op, DAG);
11838
11839   SDLoc dl(Op);
11840   SDValue N0 = Op.getOperand(0);
11841   SDValue N1 = Op.getOperand(1);
11842   SDValue N2 = Op.getOperand(2);
11843   if (!isa<ConstantSDNode>(N2))
11844     return SDValue();
11845   auto *N2C = cast<ConstantSDNode>(N2);
11846   unsigned IdxVal = N2C->getZExtValue();
11847
11848   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11849   // into that, and then insert the subvector back into the result.
11850   if (VT.is256BitVector() || VT.is512BitVector()) {
11851     // With a 256-bit vector, we can insert into the zero element efficiently
11852     // using a blend if we have AVX or AVX2 and the right data type.
11853     if (VT.is256BitVector() && IdxVal == 0) {
11854       // TODO: It is worthwhile to cast integer to floating point and back
11855       // and incur a domain crossing penalty if that's what we'll end up
11856       // doing anyway after extracting to a 128-bit vector.
11857       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11858           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11859         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11860         N2 = DAG.getIntPtrConstant(1, dl);
11861         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11862       }
11863     }
11864
11865     // Get the desired 128-bit vector chunk.
11866     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11867
11868     // Insert the element into the desired chunk.
11869     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11870     assert(isPowerOf2_32(NumEltsIn128));
11871     // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
11872     unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
11873
11874     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11875                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11876
11877     // Insert the changed part back into the bigger vector
11878     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11879   }
11880   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11881
11882   if (Subtarget->hasSSE41()) {
11883     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11884       unsigned Opc;
11885       if (VT == MVT::v8i16) {
11886         Opc = X86ISD::PINSRW;
11887       } else {
11888         assert(VT == MVT::v16i8);
11889         Opc = X86ISD::PINSRB;
11890       }
11891
11892       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11893       // argument.
11894       if (N1.getValueType() != MVT::i32)
11895         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11896       if (N2.getValueType() != MVT::i32)
11897         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11898       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11899     }
11900
11901     if (EltVT == MVT::f32) {
11902       // Bits [7:6] of the constant are the source select. This will always be
11903       //   zero here. The DAG Combiner may combine an extract_elt index into
11904       //   these bits. For example (insert (extract, 3), 2) could be matched by
11905       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11906       // Bits [5:4] of the constant are the destination select. This is the
11907       //   value of the incoming immediate.
11908       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11909       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11910
11911       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11912       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11913         // If this is an insertion of 32-bits into the low 32-bits of
11914         // a vector, we prefer to generate a blend with immediate rather
11915         // than an insertps. Blends are simpler operations in hardware and so
11916         // will always have equal or better performance than insertps.
11917         // But if optimizing for size and there's a load folding opportunity,
11918         // generate insertps because blendps does not have a 32-bit memory
11919         // operand form.
11920         N2 = DAG.getIntPtrConstant(1, dl);
11921         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11922         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11923       }
11924       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11925       // Create this as a scalar to vector..
11926       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11927       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11928     }
11929
11930     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11931       // PINSR* works with constant index.
11932       return Op;
11933     }
11934   }
11935
11936   if (EltVT == MVT::i8)
11937     return SDValue();
11938
11939   if (EltVT.getSizeInBits() == 16) {
11940     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11941     // as its second argument.
11942     if (N1.getValueType() != MVT::i32)
11943       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11944     if (N2.getValueType() != MVT::i32)
11945       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11946     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11947   }
11948   return SDValue();
11949 }
11950
11951 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11952   SDLoc dl(Op);
11953   MVT OpVT = Op.getSimpleValueType();
11954
11955   // If this is a 256-bit vector result, first insert into a 128-bit
11956   // vector and then insert into the 256-bit vector.
11957   if (!OpVT.is128BitVector()) {
11958     // Insert into a 128-bit vector.
11959     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11960     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11961                                  OpVT.getVectorNumElements() / SizeFactor);
11962
11963     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11964
11965     // Insert the 128-bit vector.
11966     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11967   }
11968
11969   if (OpVT == MVT::v1i64 &&
11970       Op.getOperand(0).getValueType() == MVT::i64)
11971     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11972
11973   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11974   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11975   return DAG.getBitcast(
11976       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11977 }
11978
11979 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11980 // a simple subregister reference or explicit instructions to grab
11981 // upper bits of a vector.
11982 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11983                                       SelectionDAG &DAG) {
11984   SDLoc dl(Op);
11985   SDValue In =  Op.getOperand(0);
11986   SDValue Idx = Op.getOperand(1);
11987   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11988   MVT ResVT   = Op.getSimpleValueType();
11989   MVT InVT    = In.getSimpleValueType();
11990
11991   if (Subtarget->hasFp256()) {
11992     if (ResVT.is128BitVector() &&
11993         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11994         isa<ConstantSDNode>(Idx)) {
11995       return Extract128BitVector(In, IdxVal, DAG, dl);
11996     }
11997     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11998         isa<ConstantSDNode>(Idx)) {
11999       return Extract256BitVector(In, IdxVal, DAG, dl);
12000     }
12001   }
12002   return SDValue();
12003 }
12004
12005 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
12006 // simple superregister reference or explicit instructions to insert
12007 // the upper bits of a vector.
12008 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12009                                      SelectionDAG &DAG) {
12010   if (!Subtarget->hasAVX())
12011     return SDValue();
12012
12013   SDLoc dl(Op);
12014   SDValue Vec = Op.getOperand(0);
12015   SDValue SubVec = Op.getOperand(1);
12016   SDValue Idx = Op.getOperand(2);
12017
12018   if (!isa<ConstantSDNode>(Idx))
12019     return SDValue();
12020
12021   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12022   MVT OpVT = Op.getSimpleValueType();
12023   MVT SubVecVT = SubVec.getSimpleValueType();
12024
12025   // Fold two 16-byte subvector loads into one 32-byte load:
12026   // (insert_subvector (insert_subvector undef, (load addr), 0),
12027   //                   (load addr + 16), Elts/2)
12028   // --> load32 addr
12029   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
12030       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
12031       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
12032     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
12033     if (Idx2 && Idx2->getZExtValue() == 0) {
12034       SDValue SubVec2 = Vec.getOperand(1);
12035       // If needed, look through a bitcast to get to the load.
12036       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
12037         SubVec2 = SubVec2.getOperand(0);
12038
12039       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
12040         bool Fast;
12041         unsigned Alignment = FirstLd->getAlignment();
12042         unsigned AS = FirstLd->getAddressSpace();
12043         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
12044         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
12045                                     OpVT, AS, Alignment, &Fast) && Fast) {
12046           SDValue Ops[] = { SubVec2, SubVec };
12047           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
12048             return Ld;
12049         }
12050       }
12051     }
12052   }
12053
12054   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
12055       SubVecVT.is128BitVector())
12056     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
12057
12058   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
12059     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
12060
12061   if (OpVT.getVectorElementType() == MVT::i1)
12062     return Insert1BitVector(Op, DAG);
12063
12064   return SDValue();
12065 }
12066
12067 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
12068 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
12069 // one of the above mentioned nodes. It has to be wrapped because otherwise
12070 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
12071 // be used to form addressing mode. These wrapped nodes will be selected
12072 // into MOV32ri.
12073 SDValue
12074 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
12075   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
12076
12077   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12078   // global base reg.
12079   unsigned char OpFlag = 0;
12080   unsigned WrapperKind = X86ISD::Wrapper;
12081   CodeModel::Model M = DAG.getTarget().getCodeModel();
12082
12083   if (Subtarget->isPICStyleRIPRel() &&
12084       (M == CodeModel::Small || M == CodeModel::Kernel))
12085     WrapperKind = X86ISD::WrapperRIP;
12086   else if (Subtarget->isPICStyleGOT())
12087     OpFlag = X86II::MO_GOTOFF;
12088   else if (Subtarget->isPICStyleStubPIC())
12089     OpFlag = X86II::MO_PIC_BASE_OFFSET;
12090
12091   auto PtrVT = getPointerTy(DAG.getDataLayout());
12092   SDValue Result = DAG.getTargetConstantPool(
12093       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
12094   SDLoc DL(CP);
12095   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12096   // With PIC, the address is actually $g + Offset.
12097   if (OpFlag) {
12098     Result =
12099         DAG.getNode(ISD::ADD, DL, PtrVT,
12100                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12101   }
12102
12103   return Result;
12104 }
12105
12106 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
12107   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
12108
12109   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12110   // global base reg.
12111   unsigned char OpFlag = 0;
12112   unsigned WrapperKind = X86ISD::Wrapper;
12113   CodeModel::Model M = DAG.getTarget().getCodeModel();
12114
12115   if (Subtarget->isPICStyleRIPRel() &&
12116       (M == CodeModel::Small || M == CodeModel::Kernel))
12117     WrapperKind = X86ISD::WrapperRIP;
12118   else if (Subtarget->isPICStyleGOT())
12119     OpFlag = X86II::MO_GOTOFF;
12120   else if (Subtarget->isPICStyleStubPIC())
12121     OpFlag = X86II::MO_PIC_BASE_OFFSET;
12122
12123   auto PtrVT = getPointerTy(DAG.getDataLayout());
12124   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
12125   SDLoc DL(JT);
12126   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12127
12128   // With PIC, the address is actually $g + Offset.
12129   if (OpFlag)
12130     Result =
12131         DAG.getNode(ISD::ADD, DL, PtrVT,
12132                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12133
12134   return Result;
12135 }
12136
12137 SDValue
12138 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
12139   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
12140
12141   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12142   // global base reg.
12143   unsigned char OpFlag = 0;
12144   unsigned WrapperKind = X86ISD::Wrapper;
12145   CodeModel::Model M = DAG.getTarget().getCodeModel();
12146
12147   if (Subtarget->isPICStyleRIPRel() &&
12148       (M == CodeModel::Small || M == CodeModel::Kernel)) {
12149     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
12150       OpFlag = X86II::MO_GOTPCREL;
12151     WrapperKind = X86ISD::WrapperRIP;
12152   } else if (Subtarget->isPICStyleGOT()) {
12153     OpFlag = X86II::MO_GOT;
12154   } else if (Subtarget->isPICStyleStubPIC()) {
12155     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
12156   } else if (Subtarget->isPICStyleStubNoDynamic()) {
12157     OpFlag = X86II::MO_DARWIN_NONLAZY;
12158   }
12159
12160   auto PtrVT = getPointerTy(DAG.getDataLayout());
12161   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
12162
12163   SDLoc DL(Op);
12164   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12165
12166   // With PIC, the address is actually $g + Offset.
12167   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
12168       !Subtarget->is64Bit()) {
12169     Result =
12170         DAG.getNode(ISD::ADD, DL, PtrVT,
12171                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12172   }
12173
12174   // For symbols that require a load from a stub to get the address, emit the
12175   // load.
12176   if (isGlobalStubReference(OpFlag))
12177     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
12178                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12179                          false, false, false, 0);
12180
12181   return Result;
12182 }
12183
12184 SDValue
12185 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
12186   // Create the TargetBlockAddressAddress node.
12187   unsigned char OpFlags =
12188     Subtarget->ClassifyBlockAddressReference();
12189   CodeModel::Model M = DAG.getTarget().getCodeModel();
12190   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
12191   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
12192   SDLoc dl(Op);
12193   auto PtrVT = getPointerTy(DAG.getDataLayout());
12194   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
12195
12196   if (Subtarget->isPICStyleRIPRel() &&
12197       (M == CodeModel::Small || M == CodeModel::Kernel))
12198     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12199   else
12200     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12201
12202   // With PIC, the address is actually $g + Offset.
12203   if (isGlobalRelativeToPICBase(OpFlags)) {
12204     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12205                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12206   }
12207
12208   return Result;
12209 }
12210
12211 SDValue
12212 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
12213                                       int64_t Offset, SelectionDAG &DAG) const {
12214   // Create the TargetGlobalAddress node, folding in the constant
12215   // offset if it is legal.
12216   unsigned char OpFlags =
12217       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
12218   CodeModel::Model M = DAG.getTarget().getCodeModel();
12219   auto PtrVT = getPointerTy(DAG.getDataLayout());
12220   SDValue Result;
12221   if (OpFlags == X86II::MO_NO_FLAG &&
12222       X86::isOffsetSuitableForCodeModel(Offset, M)) {
12223     // A direct static reference to a global.
12224     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
12225     Offset = 0;
12226   } else {
12227     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
12228   }
12229
12230   if (Subtarget->isPICStyleRIPRel() &&
12231       (M == CodeModel::Small || M == CodeModel::Kernel))
12232     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12233   else
12234     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12235
12236   // With PIC, the address is actually $g + Offset.
12237   if (isGlobalRelativeToPICBase(OpFlags)) {
12238     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12239                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12240   }
12241
12242   // For globals that require a load from a stub to get the address, emit the
12243   // load.
12244   if (isGlobalStubReference(OpFlags))
12245     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
12246                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12247                          false, false, false, 0);
12248
12249   // If there was a non-zero offset that we didn't fold, create an explicit
12250   // addition for it.
12251   if (Offset != 0)
12252     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
12253                          DAG.getConstant(Offset, dl, PtrVT));
12254
12255   return Result;
12256 }
12257
12258 SDValue
12259 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
12260   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
12261   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
12262   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
12263 }
12264
12265 static SDValue
12266 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
12267            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
12268            unsigned char OperandFlags, bool LocalDynamic = false) {
12269   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12270   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12271   SDLoc dl(GA);
12272   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12273                                            GA->getValueType(0),
12274                                            GA->getOffset(),
12275                                            OperandFlags);
12276
12277   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12278                                            : X86ISD::TLSADDR;
12279
12280   if (InFlag) {
12281     SDValue Ops[] = { Chain,  TGA, *InFlag };
12282     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12283   } else {
12284     SDValue Ops[]  = { Chain, TGA };
12285     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12286   }
12287
12288   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12289   MFI->setAdjustsStack(true);
12290   MFI->setHasCalls(true);
12291
12292   SDValue Flag = Chain.getValue(1);
12293   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12294 }
12295
12296 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12297 static SDValue
12298 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12299                                 const EVT PtrVT) {
12300   SDValue InFlag;
12301   SDLoc dl(GA);  // ? function entry point might be better
12302   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12303                                    DAG.getNode(X86ISD::GlobalBaseReg,
12304                                                SDLoc(), PtrVT), InFlag);
12305   InFlag = Chain.getValue(1);
12306
12307   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12308 }
12309
12310 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12311 static SDValue
12312 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12313                                 const EVT PtrVT) {
12314   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12315                     X86::RAX, X86II::MO_TLSGD);
12316 }
12317
12318 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12319                                            SelectionDAG &DAG,
12320                                            const EVT PtrVT,
12321                                            bool is64Bit) {
12322   SDLoc dl(GA);
12323
12324   // Get the start address of the TLS block for this module.
12325   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12326       .getInfo<X86MachineFunctionInfo>();
12327   MFI->incNumLocalDynamicTLSAccesses();
12328
12329   SDValue Base;
12330   if (is64Bit) {
12331     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12332                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
12333   } else {
12334     SDValue InFlag;
12335     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12336         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12337     InFlag = Chain.getValue(1);
12338     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12339                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12340   }
12341
12342   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12343   // of Base.
12344
12345   // Build x@dtpoff.
12346   unsigned char OperandFlags = X86II::MO_DTPOFF;
12347   unsigned WrapperKind = X86ISD::Wrapper;
12348   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12349                                            GA->getValueType(0),
12350                                            GA->getOffset(), OperandFlags);
12351   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12352
12353   // Add x@dtpoff with the base.
12354   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12355 }
12356
12357 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12358 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12359                                    const EVT PtrVT, TLSModel::Model model,
12360                                    bool is64Bit, bool isPIC) {
12361   SDLoc dl(GA);
12362
12363   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12364   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12365                                                          is64Bit ? 257 : 256));
12366
12367   SDValue ThreadPointer =
12368       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12369                   MachinePointerInfo(Ptr), false, false, false, 0);
12370
12371   unsigned char OperandFlags = 0;
12372   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
12373   // initialexec.
12374   unsigned WrapperKind = X86ISD::Wrapper;
12375   if (model == TLSModel::LocalExec) {
12376     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12377   } else if (model == TLSModel::InitialExec) {
12378     if (is64Bit) {
12379       OperandFlags = X86II::MO_GOTTPOFF;
12380       WrapperKind = X86ISD::WrapperRIP;
12381     } else {
12382       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12383     }
12384   } else {
12385     llvm_unreachable("Unexpected model");
12386   }
12387
12388   // emit "addl x@ntpoff,%eax" (local exec)
12389   // or "addl x@indntpoff,%eax" (initial exec)
12390   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12391   SDValue TGA =
12392       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12393                                  GA->getOffset(), OperandFlags);
12394   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12395
12396   if (model == TLSModel::InitialExec) {
12397     if (isPIC && !is64Bit) {
12398       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12399                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12400                            Offset);
12401     }
12402
12403     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12404                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12405                          false, false, false, 0);
12406   }
12407
12408   // The address of the thread local variable is the add of the thread
12409   // pointer with the offset of the variable.
12410   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12411 }
12412
12413 SDValue
12414 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12415
12416   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12417
12418   // Cygwin uses emutls.
12419   // FIXME: It may be EmulatedTLS-generic also for X86-Android.
12420   if (Subtarget->isTargetWindowsCygwin())
12421     return LowerToTLSEmulatedModel(GA, DAG);
12422
12423   const GlobalValue *GV = GA->getGlobal();
12424   auto PtrVT = getPointerTy(DAG.getDataLayout());
12425
12426   if (Subtarget->isTargetELF()) {
12427     if (DAG.getTarget().Options.EmulatedTLS)
12428       return LowerToTLSEmulatedModel(GA, DAG);
12429     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12430     switch (model) {
12431       case TLSModel::GeneralDynamic:
12432         if (Subtarget->is64Bit())
12433           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12434         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12435       case TLSModel::LocalDynamic:
12436         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12437                                            Subtarget->is64Bit());
12438       case TLSModel::InitialExec:
12439       case TLSModel::LocalExec:
12440         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12441                                    DAG.getTarget().getRelocationModel() ==
12442                                        Reloc::PIC_);
12443     }
12444     llvm_unreachable("Unknown TLS model.");
12445   }
12446
12447   if (Subtarget->isTargetDarwin()) {
12448     // Darwin only has one model of TLS.  Lower to that.
12449     unsigned char OpFlag = 0;
12450     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12451                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12452
12453     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12454     // global base reg.
12455     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12456                  !Subtarget->is64Bit();
12457     if (PIC32)
12458       OpFlag = X86II::MO_TLVP_PIC_BASE;
12459     else
12460       OpFlag = X86II::MO_TLVP;
12461     SDLoc DL(Op);
12462     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12463                                                 GA->getValueType(0),
12464                                                 GA->getOffset(), OpFlag);
12465     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12466
12467     // With PIC32, the address is actually $g + Offset.
12468     if (PIC32)
12469       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12470                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12471                            Offset);
12472
12473     // Lowering the machine isd will make sure everything is in the right
12474     // location.
12475     SDValue Chain = DAG.getEntryNode();
12476     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12477     SDValue Args[] = { Chain, Offset };
12478     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12479
12480     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12481     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12482     MFI->setAdjustsStack(true);
12483
12484     // And our return value (tls address) is in the standard call return value
12485     // location.
12486     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12487     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12488   }
12489
12490   if (Subtarget->isTargetKnownWindowsMSVC() ||
12491       Subtarget->isTargetWindowsGNU()) {
12492     // Just use the implicit TLS architecture
12493     // Need to generate someting similar to:
12494     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12495     //                                  ; from TEB
12496     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12497     //   mov     rcx, qword [rdx+rcx*8]
12498     //   mov     eax, .tls$:tlsvar
12499     //   [rax+rcx] contains the address
12500     // Windows 64bit: gs:0x58
12501     // Windows 32bit: fs:__tls_array
12502
12503     SDLoc dl(GA);
12504     SDValue Chain = DAG.getEntryNode();
12505
12506     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12507     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12508     // use its literal value of 0x2C.
12509     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12510                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12511                                                              256)
12512                                         : Type::getInt32PtrTy(*DAG.getContext(),
12513                                                               257));
12514
12515     SDValue TlsArray = Subtarget->is64Bit()
12516                            ? DAG.getIntPtrConstant(0x58, dl)
12517                            : (Subtarget->isTargetWindowsGNU()
12518                                   ? DAG.getIntPtrConstant(0x2C, dl)
12519                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12520
12521     SDValue ThreadPointer =
12522         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12523                     false, false, 0);
12524
12525     SDValue res;
12526     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12527       res = ThreadPointer;
12528     } else {
12529       // Load the _tls_index variable
12530       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12531       if (Subtarget->is64Bit())
12532         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12533                              MachinePointerInfo(), MVT::i32, false, false,
12534                              false, 0);
12535       else
12536         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12537                           false, false, 0);
12538
12539       auto &DL = DAG.getDataLayout();
12540       SDValue Scale =
12541           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12542       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12543
12544       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12545     }
12546
12547     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12548                       false, 0);
12549
12550     // Get the offset of start of .tls section
12551     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12552                                              GA->getValueType(0),
12553                                              GA->getOffset(), X86II::MO_SECREL);
12554     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12555
12556     // The address of the thread local variable is the add of the thread
12557     // pointer with the offset of the variable.
12558     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12559   }
12560
12561   llvm_unreachable("TLS not implemented for this target.");
12562 }
12563
12564 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12565 /// and take a 2 x i32 value to shift plus a shift amount.
12566 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12567   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12568   MVT VT = Op.getSimpleValueType();
12569   unsigned VTBits = VT.getSizeInBits();
12570   SDLoc dl(Op);
12571   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12572   SDValue ShOpLo = Op.getOperand(0);
12573   SDValue ShOpHi = Op.getOperand(1);
12574   SDValue ShAmt  = Op.getOperand(2);
12575   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12576   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12577   // during isel.
12578   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12579                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12580   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12581                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12582                        : DAG.getConstant(0, dl, VT);
12583
12584   SDValue Tmp2, Tmp3;
12585   if (Op.getOpcode() == ISD::SHL_PARTS) {
12586     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12587     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12588   } else {
12589     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12590     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12591   }
12592
12593   // If the shift amount is larger or equal than the width of a part we can't
12594   // rely on the results of shld/shrd. Insert a test and select the appropriate
12595   // values for large shift amounts.
12596   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12597                                 DAG.getConstant(VTBits, dl, MVT::i8));
12598   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12599                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12600
12601   SDValue Hi, Lo;
12602   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12603   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12604   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12605
12606   if (Op.getOpcode() == ISD::SHL_PARTS) {
12607     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12608     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12609   } else {
12610     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12611     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12612   }
12613
12614   SDValue Ops[2] = { Lo, Hi };
12615   return DAG.getMergeValues(Ops, dl);
12616 }
12617
12618 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12619                                            SelectionDAG &DAG) const {
12620   SDValue Src = Op.getOperand(0);
12621   MVT SrcVT = Src.getSimpleValueType();
12622   MVT VT = Op.getSimpleValueType();
12623   SDLoc dl(Op);
12624
12625   if (SrcVT.isVector()) {
12626     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12627       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12628                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12629                          DAG.getUNDEF(SrcVT)));
12630     }
12631     if (SrcVT.getVectorElementType() == MVT::i1) {
12632       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12633       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12634                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12635     }
12636     return SDValue();
12637   }
12638
12639   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12640          "Unknown SINT_TO_FP to lower!");
12641
12642   // These are really Legal; return the operand so the caller accepts it as
12643   // Legal.
12644   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12645     return Op;
12646   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12647       Subtarget->is64Bit()) {
12648     return Op;
12649   }
12650
12651   unsigned Size = SrcVT.getSizeInBits()/8;
12652   MachineFunction &MF = DAG.getMachineFunction();
12653   auto PtrVT = getPointerTy(MF.getDataLayout());
12654   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12655   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12656   SDValue Chain = DAG.getStore(
12657       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12658       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12659       false, 0);
12660   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12661 }
12662
12663 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12664                                      SDValue StackSlot,
12665                                      SelectionDAG &DAG) const {
12666   // Build the FILD
12667   SDLoc DL(Op);
12668   SDVTList Tys;
12669   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12670   if (useSSE)
12671     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12672   else
12673     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12674
12675   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12676
12677   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12678   MachineMemOperand *MMO;
12679   if (FI) {
12680     int SSFI = FI->getIndex();
12681     MMO = DAG.getMachineFunction().getMachineMemOperand(
12682         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12683         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12684   } else {
12685     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12686     StackSlot = StackSlot.getOperand(1);
12687   }
12688   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12689   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12690                                            X86ISD::FILD, DL,
12691                                            Tys, Ops, SrcVT, MMO);
12692
12693   if (useSSE) {
12694     Chain = Result.getValue(1);
12695     SDValue InFlag = Result.getValue(2);
12696
12697     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12698     // shouldn't be necessary except that RFP cannot be live across
12699     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12700     MachineFunction &MF = DAG.getMachineFunction();
12701     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12702     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12703     auto PtrVT = getPointerTy(MF.getDataLayout());
12704     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12705     Tys = DAG.getVTList(MVT::Other);
12706     SDValue Ops[] = {
12707       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12708     };
12709     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12710         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12711         MachineMemOperand::MOStore, SSFISize, SSFISize);
12712
12713     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12714                                     Ops, Op.getValueType(), MMO);
12715     Result = DAG.getLoad(
12716         Op.getValueType(), DL, Chain, StackSlot,
12717         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12718         false, false, false, 0);
12719   }
12720
12721   return Result;
12722 }
12723
12724 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12725 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12726                                                SelectionDAG &DAG) const {
12727   // This algorithm is not obvious. Here it is what we're trying to output:
12728   /*
12729      movq       %rax,  %xmm0
12730      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12731      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12732      #ifdef __SSE3__
12733        haddpd   %xmm0, %xmm0
12734      #else
12735        pshufd   $0x4e, %xmm0, %xmm1
12736        addpd    %xmm1, %xmm0
12737      #endif
12738   */
12739
12740   SDLoc dl(Op);
12741   LLVMContext *Context = DAG.getContext();
12742
12743   // Build some magic constants.
12744   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12745   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12746   auto PtrVT = getPointerTy(DAG.getDataLayout());
12747   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12748
12749   SmallVector<Constant*,2> CV1;
12750   CV1.push_back(
12751     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12752                                       APInt(64, 0x4330000000000000ULL))));
12753   CV1.push_back(
12754     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12755                                       APInt(64, 0x4530000000000000ULL))));
12756   Constant *C1 = ConstantVector::get(CV1);
12757   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12758
12759   // Load the 64-bit value into an XMM register.
12760   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12761                             Op.getOperand(0));
12762   SDValue CLod0 =
12763       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12764                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12765                   false, false, false, 16);
12766   SDValue Unpck1 =
12767       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12768
12769   SDValue CLod1 =
12770       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12771                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12772                   false, false, false, 16);
12773   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12774   // TODO: Are there any fast-math-flags to propagate here?
12775   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12776   SDValue Result;
12777
12778   if (Subtarget->hasSSE3()) {
12779     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12780     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12781   } else {
12782     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12783     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12784                                            S2F, 0x4E, DAG);
12785     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12786                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12787   }
12788
12789   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12790                      DAG.getIntPtrConstant(0, dl));
12791 }
12792
12793 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12794 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12795                                                SelectionDAG &DAG) const {
12796   SDLoc dl(Op);
12797   // FP constant to bias correct the final result.
12798   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12799                                    MVT::f64);
12800
12801   // Load the 32-bit value into an XMM register.
12802   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12803                              Op.getOperand(0));
12804
12805   // Zero out the upper parts of the register.
12806   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12807
12808   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12809                      DAG.getBitcast(MVT::v2f64, Load),
12810                      DAG.getIntPtrConstant(0, dl));
12811
12812   // Or the load with the bias.
12813   SDValue Or = DAG.getNode(
12814       ISD::OR, dl, MVT::v2i64,
12815       DAG.getBitcast(MVT::v2i64,
12816                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12817       DAG.getBitcast(MVT::v2i64,
12818                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12819   Or =
12820       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12821                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12822
12823   // Subtract the bias.
12824   // TODO: Are there any fast-math-flags to propagate here?
12825   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12826
12827   // Handle final rounding.
12828   MVT DestVT = Op.getSimpleValueType();
12829
12830   if (DestVT.bitsLT(MVT::f64))
12831     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12832                        DAG.getIntPtrConstant(0, dl));
12833   if (DestVT.bitsGT(MVT::f64))
12834     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12835
12836   // Handle final rounding.
12837   return Sub;
12838 }
12839
12840 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12841                                      const X86Subtarget &Subtarget) {
12842   // The algorithm is the following:
12843   // #ifdef __SSE4_1__
12844   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12845   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12846   //                                 (uint4) 0x53000000, 0xaa);
12847   // #else
12848   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12849   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12850   // #endif
12851   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12852   //     return (float4) lo + fhi;
12853
12854   // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12855   // reassociate the two FADDs, and if we do that, the algorithm fails
12856   // spectacularly (PR24512).
12857   // FIXME: If we ever have some kind of Machine FMF, this should be marked
12858   // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12859   // there's also the MachineCombiner reassociations happening on Machine IR.
12860   if (DAG.getTarget().Options.UnsafeFPMath)
12861     return SDValue();
12862
12863   SDLoc DL(Op);
12864   SDValue V = Op->getOperand(0);
12865   MVT VecIntVT = V.getSimpleValueType();
12866   bool Is128 = VecIntVT == MVT::v4i32;
12867   MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12868   // If we convert to something else than the supported type, e.g., to v4f64,
12869   // abort early.
12870   if (VecFloatVT != Op->getSimpleValueType(0))
12871     return SDValue();
12872
12873   unsigned NumElts = VecIntVT.getVectorNumElements();
12874   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12875          "Unsupported custom type");
12876   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12877
12878   // In the #idef/#else code, we have in common:
12879   // - The vector of constants:
12880   // -- 0x4b000000
12881   // -- 0x53000000
12882   // - A shift:
12883   // -- v >> 16
12884
12885   // Create the splat vector for 0x4b000000.
12886   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12887   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12888                            CstLow, CstLow, CstLow, CstLow};
12889   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12890                                   makeArrayRef(&CstLowArray[0], NumElts));
12891   // Create the splat vector for 0x53000000.
12892   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12893   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12894                             CstHigh, CstHigh, CstHigh, CstHigh};
12895   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12896                                    makeArrayRef(&CstHighArray[0], NumElts));
12897
12898   // Create the right shift.
12899   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12900   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12901                              CstShift, CstShift, CstShift, CstShift};
12902   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12903                                     makeArrayRef(&CstShiftArray[0], NumElts));
12904   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12905
12906   SDValue Low, High;
12907   if (Subtarget.hasSSE41()) {
12908     MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12909     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12910     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12911     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12912     // Low will be bitcasted right away, so do not bother bitcasting back to its
12913     // original type.
12914     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12915                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12916     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12917     //                                 (uint4) 0x53000000, 0xaa);
12918     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12919     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12920     // High will be bitcasted right away, so do not bother bitcasting back to
12921     // its original type.
12922     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12923                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12924   } else {
12925     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12926     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12927                                      CstMask, CstMask, CstMask);
12928     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12929     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12930     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12931
12932     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12933     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12934   }
12935
12936   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12937   SDValue CstFAdd = DAG.getConstantFP(
12938       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12939   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12940                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12941   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12942                                    makeArrayRef(&CstFAddArray[0], NumElts));
12943
12944   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12945   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12946   // TODO: Are there any fast-math-flags to propagate here?
12947   SDValue FHigh =
12948       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12949   //     return (float4) lo + fhi;
12950   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12951   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12952 }
12953
12954 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12955                                                SelectionDAG &DAG) const {
12956   SDValue N0 = Op.getOperand(0);
12957   MVT SVT = N0.getSimpleValueType();
12958   SDLoc dl(Op);
12959
12960   switch (SVT.SimpleTy) {
12961   default:
12962     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12963   case MVT::v4i8:
12964   case MVT::v4i16:
12965   case MVT::v8i8:
12966   case MVT::v8i16: {
12967     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12968     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12969                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12970   }
12971   case MVT::v4i32:
12972   case MVT::v8i32:
12973     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12974   case MVT::v16i8:
12975   case MVT::v16i16:
12976     assert(Subtarget->hasAVX512());
12977     return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12978                        DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12979   }
12980 }
12981
12982 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12983                                            SelectionDAG &DAG) const {
12984   SDValue N0 = Op.getOperand(0);
12985   SDLoc dl(Op);
12986   auto PtrVT = getPointerTy(DAG.getDataLayout());
12987
12988   if (Op.getSimpleValueType().isVector())
12989     return lowerUINT_TO_FP_vec(Op, DAG);
12990
12991   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12992   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12993   // the optimization here.
12994   if (DAG.SignBitIsZero(N0))
12995     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12996
12997   MVT SrcVT = N0.getSimpleValueType();
12998   MVT DstVT = Op.getSimpleValueType();
12999
13000   if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
13001       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
13002     // Conversions from unsigned i32 to f32/f64 are legal,
13003     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
13004     return Op;
13005   }
13006
13007   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
13008     return LowerUINT_TO_FP_i64(Op, DAG);
13009   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
13010     return LowerUINT_TO_FP_i32(Op, DAG);
13011   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
13012     return SDValue();
13013
13014   // Make a 64-bit buffer, and use it to build an FILD.
13015   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
13016   if (SrcVT == MVT::i32) {
13017     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
13018     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
13019     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13020                                   StackSlot, MachinePointerInfo(),
13021                                   false, false, 0);
13022     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
13023                                   OffsetSlot, MachinePointerInfo(),
13024                                   false, false, 0);
13025     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
13026     return Fild;
13027   }
13028
13029   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
13030   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13031                                StackSlot, MachinePointerInfo(),
13032                                false, false, 0);
13033   // For i64 source, we need to add the appropriate power of 2 if the input
13034   // was negative.  This is the same as the optimization in
13035   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
13036   // we must be careful to do the computation in x87 extended precision, not
13037   // in SSE. (The generic code can't know it's OK to do this, or how to.)
13038   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
13039   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
13040       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
13041       MachineMemOperand::MOLoad, 8, 8);
13042
13043   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
13044   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
13045   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
13046                                          MVT::i64, MMO);
13047
13048   APInt FF(32, 0x5F800000ULL);
13049
13050   // Check whether the sign bit is set.
13051   SDValue SignSet = DAG.getSetCC(
13052       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
13053       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
13054
13055   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
13056   SDValue FudgePtr = DAG.getConstantPool(
13057       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
13058
13059   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
13060   SDValue Zero = DAG.getIntPtrConstant(0, dl);
13061   SDValue Four = DAG.getIntPtrConstant(4, dl);
13062   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
13063                                Zero, Four);
13064   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
13065
13066   // Load the value out, extending it from f32 to f80.
13067   // FIXME: Avoid the extend by constructing the right constant pool?
13068   SDValue Fudge = DAG.getExtLoad(
13069       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
13070       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
13071       false, false, false, 4);
13072   // Extend everything to 80 bits to force it to be done on x87.
13073   // TODO: Are there any fast-math-flags to propagate here?
13074   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
13075   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
13076                      DAG.getIntPtrConstant(0, dl));
13077 }
13078
13079 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
13080 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
13081 // just return an <SDValue(), SDValue()> pair.
13082 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
13083 // to i16, i32 or i64, and we lower it to a legal sequence.
13084 // If lowered to the final integer result we return a <result, SDValue()> pair.
13085 // Otherwise we lower it to a sequence ending with a FIST, return a
13086 // <FIST, StackSlot> pair, and the caller is responsible for loading
13087 // the final integer result from StackSlot.
13088 std::pair<SDValue,SDValue>
13089 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
13090                                    bool IsSigned, bool IsReplace) const {
13091   SDLoc DL(Op);
13092
13093   EVT DstTy = Op.getValueType();
13094   EVT TheVT = Op.getOperand(0).getValueType();
13095   auto PtrVT = getPointerTy(DAG.getDataLayout());
13096
13097   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
13098     // f16 must be promoted before using the lowering in this routine.
13099     // fp128 does not use this lowering.
13100     return std::make_pair(SDValue(), SDValue());
13101   }
13102
13103   // If using FIST to compute an unsigned i64, we'll need some fixup
13104   // to handle values above the maximum signed i64.  A FIST is always
13105   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
13106   bool UnsignedFixup = !IsSigned &&
13107                        DstTy == MVT::i64 &&
13108                        (!Subtarget->is64Bit() ||
13109                         !isScalarFPTypeInSSEReg(TheVT));
13110
13111   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
13112     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
13113     // The low 32 bits of the fist result will have the correct uint32 result.
13114     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
13115     DstTy = MVT::i64;
13116   }
13117
13118   assert(DstTy.getSimpleVT() <= MVT::i64 &&
13119          DstTy.getSimpleVT() >= MVT::i16 &&
13120          "Unknown FP_TO_INT to lower!");
13121
13122   // These are really Legal.
13123   if (DstTy == MVT::i32 &&
13124       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13125     return std::make_pair(SDValue(), SDValue());
13126   if (Subtarget->is64Bit() &&
13127       DstTy == MVT::i64 &&
13128       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13129     return std::make_pair(SDValue(), SDValue());
13130
13131   // We lower FP->int64 into FISTP64 followed by a load from a temporary
13132   // stack slot.
13133   MachineFunction &MF = DAG.getMachineFunction();
13134   unsigned MemSize = DstTy.getSizeInBits()/8;
13135   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13136   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13137
13138   unsigned Opc;
13139   switch (DstTy.getSimpleVT().SimpleTy) {
13140   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
13141   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
13142   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
13143   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
13144   }
13145
13146   SDValue Chain = DAG.getEntryNode();
13147   SDValue Value = Op.getOperand(0);
13148   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
13149
13150   if (UnsignedFixup) {
13151     //
13152     // Conversion to unsigned i64 is implemented with a select,
13153     // depending on whether the source value fits in the range
13154     // of a signed i64.  Let Thresh be the FP equivalent of
13155     // 0x8000000000000000ULL.
13156     //
13157     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
13158     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
13159     //  Fist-to-mem64 FistSrc
13160     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
13161     //  to XOR'ing the high 32 bits with Adjust.
13162     //
13163     // Being a power of 2, Thresh is exactly representable in all FP formats.
13164     // For X87 we'd like to use the smallest FP type for this constant, but
13165     // for DAG type consistency we have to match the FP operand type.
13166
13167     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
13168     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
13169     bool LosesInfo = false;
13170     if (TheVT == MVT::f64)
13171       // The rounding mode is irrelevant as the conversion should be exact.
13172       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
13173                               &LosesInfo);
13174     else if (TheVT == MVT::f80)
13175       Status = Thresh.convert(APFloat::x87DoubleExtended,
13176                               APFloat::rmNearestTiesToEven, &LosesInfo);
13177
13178     assert(Status == APFloat::opOK && !LosesInfo &&
13179            "FP conversion should have been exact");
13180
13181     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
13182
13183     SDValue Cmp = DAG.getSetCC(DL,
13184                                getSetCCResultType(DAG.getDataLayout(),
13185                                                   *DAG.getContext(), TheVT),
13186                                Value, ThreshVal, ISD::SETLT);
13187     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
13188                            DAG.getConstant(0, DL, MVT::i32),
13189                            DAG.getConstant(0x80000000, DL, MVT::i32));
13190     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
13191     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
13192                                               *DAG.getContext(), TheVT),
13193                        Value, ThreshVal, ISD::SETLT);
13194     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
13195   }
13196
13197   // FIXME This causes a redundant load/store if the SSE-class value is already
13198   // in memory, such as if it is on the callstack.
13199   if (isScalarFPTypeInSSEReg(TheVT)) {
13200     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
13201     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
13202                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
13203                          false, 0);
13204     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
13205     SDValue Ops[] = {
13206       Chain, StackSlot, DAG.getValueType(TheVT)
13207     };
13208
13209     MachineMemOperand *MMO =
13210         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13211                                 MachineMemOperand::MOLoad, MemSize, MemSize);
13212     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
13213     Chain = Value.getValue(1);
13214     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13215     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13216   }
13217
13218   MachineMemOperand *MMO =
13219       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13220                               MachineMemOperand::MOStore, MemSize, MemSize);
13221
13222   if (UnsignedFixup) {
13223
13224     // Insert the FIST, load its result as two i32's,
13225     // and XOR the high i32 with Adjust.
13226
13227     SDValue FistOps[] = { Chain, Value, StackSlot };
13228     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13229                                            FistOps, DstTy, MMO);
13230
13231     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
13232                                 MachinePointerInfo(),
13233                                 false, false, false, 0);
13234     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
13235                                    DAG.getConstant(4, DL, PtrVT));
13236
13237     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
13238                                  MachinePointerInfo(),
13239                                  false, false, false, 0);
13240     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
13241
13242     if (Subtarget->is64Bit()) {
13243       // Join High32 and Low32 into a 64-bit result.
13244       // (High32 << 32) | Low32
13245       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
13246       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
13247       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
13248                            DAG.getConstant(32, DL, MVT::i8));
13249       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
13250       return std::make_pair(Result, SDValue());
13251     }
13252
13253     SDValue ResultOps[] = { Low32, High32 };
13254
13255     SDValue pair = IsReplace
13256       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
13257       : DAG.getMergeValues(ResultOps, DL);
13258     return std::make_pair(pair, SDValue());
13259   } else {
13260     // Build the FP_TO_INT*_IN_MEM
13261     SDValue Ops[] = { Chain, Value, StackSlot };
13262     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13263                                            Ops, DstTy, MMO);
13264     return std::make_pair(FIST, StackSlot);
13265   }
13266 }
13267
13268 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
13269                               const X86Subtarget *Subtarget) {
13270   MVT VT = Op->getSimpleValueType(0);
13271   SDValue In = Op->getOperand(0);
13272   MVT InVT = In.getSimpleValueType();
13273   SDLoc dl(Op);
13274
13275   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13276     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
13277
13278   // Optimize vectors in AVX mode:
13279   //
13280   //   v8i16 -> v8i32
13281   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
13282   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
13283   //   Concat upper and lower parts.
13284   //
13285   //   v4i32 -> v4i64
13286   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
13287   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
13288   //   Concat upper and lower parts.
13289   //
13290
13291   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13292       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13293       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13294     return SDValue();
13295
13296   if (Subtarget->hasInt256())
13297     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13298
13299   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13300   SDValue Undef = DAG.getUNDEF(InVT);
13301   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13302   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13303   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13304
13305   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13306                              VT.getVectorNumElements()/2);
13307
13308   OpLo = DAG.getBitcast(HVT, OpLo);
13309   OpHi = DAG.getBitcast(HVT, OpHi);
13310
13311   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13312 }
13313
13314 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13315                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13316   MVT VT = Op->getSimpleValueType(0);
13317   SDValue In = Op->getOperand(0);
13318   MVT InVT = In.getSimpleValueType();
13319   SDLoc DL(Op);
13320   unsigned int NumElts = VT.getVectorNumElements();
13321   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13322     return SDValue();
13323
13324   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13325     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13326
13327   assert(InVT.getVectorElementType() == MVT::i1);
13328   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13329   SDValue One =
13330    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13331   SDValue Zero =
13332    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13333
13334   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13335   if (VT.is512BitVector())
13336     return V;
13337   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13338 }
13339
13340 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13341                                SelectionDAG &DAG) {
13342   if (Subtarget->hasFp256())
13343     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13344       return Res;
13345
13346   return SDValue();
13347 }
13348
13349 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13350                                 SelectionDAG &DAG) {
13351   SDLoc DL(Op);
13352   MVT VT = Op.getSimpleValueType();
13353   SDValue In = Op.getOperand(0);
13354   MVT SVT = In.getSimpleValueType();
13355
13356   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13357     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13358
13359   if (Subtarget->hasFp256())
13360     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13361       return Res;
13362
13363   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13364          VT.getVectorNumElements() != SVT.getVectorNumElements());
13365   return SDValue();
13366 }
13367
13368 static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
13369                                   const X86Subtarget *Subtarget) {
13370
13371   SDLoc DL(Op);
13372   MVT VT = Op.getSimpleValueType();
13373   SDValue In = Op.getOperand(0);
13374   MVT InVT = In.getSimpleValueType();
13375
13376   assert(VT.getVectorElementType() == MVT::i1 && "Unexected vector type.");
13377
13378   // Shift LSB to MSB and use VPMOVB2M - SKX.
13379   unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
13380   if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13381          Subtarget->hasBWI()) ||     // legal, will go to VPMOVB2M, VPMOVW2M
13382       ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13383              InVT.getScalarSizeInBits() <= 16 && Subtarget->hasBWI() &&
13384              Subtarget->hasVLX())) { // legal, will go to VPMOVB2M, VPMOVW2M
13385     // Shift packed bytes not supported natively, bitcast to dword
13386     MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
13387     SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, ExtVT,
13388                                      DAG.getBitcast(ExtVT, In),
13389                                      DAG.getConstant(ShiftInx, DL, ExtVT));
13390     ShiftNode = DAG.getBitcast(InVT, ShiftNode);
13391     return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13392   }
13393   if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13394          Subtarget->hasDQI()) ||  // legal, will go to VPMOVD2M, VPMOVQ2M
13395       ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13396          InVT.getScalarSizeInBits() >= 32 && Subtarget->hasDQI() &&
13397          Subtarget->hasVLX())) {  // legal, will go to VPMOVD2M, VPMOVQ2M
13398
13399     SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13400                                      DAG.getConstant(ShiftInx, DL, InVT));
13401     return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13402   }
13403
13404   // Shift LSB to MSB, extend if necessary and use TESTM.
13405   unsigned NumElts = InVT.getVectorNumElements();
13406   if (InVT.getSizeInBits() < 512 &&
13407       (InVT.getScalarType() == MVT::i8 || InVT.getScalarType() == MVT::i16 ||
13408        !Subtarget->hasVLX())) {
13409     assert((NumElts == 8 || NumElts == 16) && "Unexected vector type.");
13410
13411     // TESTD/Q should be used (if BW supported we use CVT2MASK above),
13412     // so vector should be extended to packed dword/qword.
13413     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(512/NumElts), NumElts);
13414     In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13415     InVT = ExtVT;
13416     ShiftInx = InVT.getScalarSizeInBits() - 1;
13417   }
13418
13419   SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13420                                    DAG.getConstant(ShiftInx, DL, InVT));
13421   return DAG.getNode(X86ISD::TESTM, DL, VT, ShiftNode, ShiftNode);
13422 }
13423
13424 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13425   SDLoc DL(Op);
13426   MVT VT = Op.getSimpleValueType();
13427   SDValue In = Op.getOperand(0);
13428   MVT InVT = In.getSimpleValueType();
13429
13430   if (VT == MVT::i1) {
13431     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13432            "Invalid scalar TRUNCATE operation");
13433     if (InVT.getSizeInBits() >= 32)
13434       return SDValue();
13435     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13436     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13437   }
13438   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13439          "Invalid TRUNCATE operation");
13440
13441   if (VT.getVectorElementType() == MVT::i1)
13442     return LowerTruncateVecI1(Op, DAG, Subtarget);
13443
13444   // vpmovqb/w/d, vpmovdb/w, vpmovwb
13445   if (Subtarget->hasAVX512()) {
13446     // word to byte only under BWI
13447     if (InVT == MVT::v16i16 && !Subtarget->hasBWI()) // v16i16 -> v16i8
13448       return DAG.getNode(X86ISD::VTRUNC, DL, VT,
13449                          DAG.getNode(X86ISD::VSEXT, DL, MVT::v16i32, In));
13450     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13451   }
13452   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13453     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13454     if (Subtarget->hasInt256()) {
13455       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13456       In = DAG.getBitcast(MVT::v8i32, In);
13457       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13458                                 ShufMask);
13459       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13460                          DAG.getIntPtrConstant(0, DL));
13461     }
13462
13463     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13464                                DAG.getIntPtrConstant(0, DL));
13465     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13466                                DAG.getIntPtrConstant(2, DL));
13467     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13468     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13469     static const int ShufMask[] = {0, 2, 4, 6};
13470     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13471   }
13472
13473   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13474     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13475     if (Subtarget->hasInt256()) {
13476       In = DAG.getBitcast(MVT::v32i8, In);
13477
13478       SmallVector<SDValue,32> pshufbMask;
13479       for (unsigned i = 0; i < 2; ++i) {
13480         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13481         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13482         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13483         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13484         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13485         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13486         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13487         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13488         for (unsigned j = 0; j < 8; ++j)
13489           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13490       }
13491       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13492       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13493       In = DAG.getBitcast(MVT::v4i64, In);
13494
13495       static const int ShufMask[] = {0,  2,  -1,  -1};
13496       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13497                                 &ShufMask[0]);
13498       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13499                        DAG.getIntPtrConstant(0, DL));
13500       return DAG.getBitcast(VT, In);
13501     }
13502
13503     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13504                                DAG.getIntPtrConstant(0, DL));
13505
13506     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13507                                DAG.getIntPtrConstant(4, DL));
13508
13509     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13510     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13511
13512     // The PSHUFB mask:
13513     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13514                                    -1, -1, -1, -1, -1, -1, -1, -1};
13515
13516     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13517     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13518     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13519
13520     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13521     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13522
13523     // The MOVLHPS Mask:
13524     static const int ShufMask2[] = {0, 1, 4, 5};
13525     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13526     return DAG.getBitcast(MVT::v8i16, res);
13527   }
13528
13529   // Handle truncation of V256 to V128 using shuffles.
13530   if (!VT.is128BitVector() || !InVT.is256BitVector())
13531     return SDValue();
13532
13533   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13534
13535   unsigned NumElems = VT.getVectorNumElements();
13536   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13537
13538   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13539   // Prepare truncation shuffle mask
13540   for (unsigned i = 0; i != NumElems; ++i)
13541     MaskVec[i] = i * 2;
13542   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13543                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13544   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13545                      DAG.getIntPtrConstant(0, DL));
13546 }
13547
13548 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13549                                            SelectionDAG &DAG) const {
13550   assert(!Op.getSimpleValueType().isVector());
13551
13552   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13553     /*IsSigned=*/ true, /*IsReplace=*/ false);
13554   SDValue FIST = Vals.first, StackSlot = Vals.second;
13555   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13556   if (!FIST.getNode())
13557     return Op;
13558
13559   if (StackSlot.getNode())
13560     // Load the result.
13561     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13562                        FIST, StackSlot, MachinePointerInfo(),
13563                        false, false, false, 0);
13564
13565   // The node is the result.
13566   return FIST;
13567 }
13568
13569 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13570                                            SelectionDAG &DAG) const {
13571   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13572     /*IsSigned=*/ false, /*IsReplace=*/ false);
13573   SDValue FIST = Vals.first, StackSlot = Vals.second;
13574   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13575   if (!FIST.getNode())
13576     return Op;
13577
13578   if (StackSlot.getNode())
13579     // Load the result.
13580     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13581                        FIST, StackSlot, MachinePointerInfo(),
13582                        false, false, false, 0);
13583
13584   // The node is the result.
13585   return FIST;
13586 }
13587
13588 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13589   SDLoc DL(Op);
13590   MVT VT = Op.getSimpleValueType();
13591   SDValue In = Op.getOperand(0);
13592   MVT SVT = In.getSimpleValueType();
13593
13594   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13595
13596   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13597                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13598                                  In, DAG.getUNDEF(SVT)));
13599 }
13600
13601 /// The only differences between FABS and FNEG are the mask and the logic op.
13602 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13603 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13604   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13605          "Wrong opcode for lowering FABS or FNEG.");
13606
13607   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13608
13609   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13610   // into an FNABS. We'll lower the FABS after that if it is still in use.
13611   if (IsFABS)
13612     for (SDNode *User : Op->uses())
13613       if (User->getOpcode() == ISD::FNEG)
13614         return Op;
13615
13616   SDLoc dl(Op);
13617   MVT VT = Op.getSimpleValueType();
13618
13619   bool IsF128 = (VT == MVT::f128);
13620
13621   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13622   // decide if we should generate a 16-byte constant mask when we only need 4 or
13623   // 8 bytes for the scalar case.
13624
13625   MVT LogicVT;
13626   MVT EltVT;
13627   unsigned NumElts;
13628
13629   if (VT.isVector()) {
13630     LogicVT = VT;
13631     EltVT = VT.getVectorElementType();
13632     NumElts = VT.getVectorNumElements();
13633   } else if (IsF128) {
13634     // SSE instructions are used for optimized f128 logical operations.
13635     LogicVT = MVT::f128;
13636     EltVT = VT;
13637     NumElts = 1;
13638   } else {
13639     // There are no scalar bitwise logical SSE/AVX instructions, so we
13640     // generate a 16-byte vector constant and logic op even for the scalar case.
13641     // Using a 16-byte mask allows folding the load of the mask with
13642     // the logic op, so it can save (~4 bytes) on code size.
13643     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13644     EltVT = VT;
13645     NumElts = (VT == MVT::f64) ? 2 : 4;
13646   }
13647
13648   unsigned EltBits = EltVT.getSizeInBits();
13649   LLVMContext *Context = DAG.getContext();
13650   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13651   APInt MaskElt =
13652     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13653   Constant *C = ConstantInt::get(*Context, MaskElt);
13654   C = ConstantVector::getSplat(NumElts, C);
13655   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13656   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13657   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13658   SDValue Mask =
13659       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13660                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13661                   false, false, false, Alignment);
13662
13663   SDValue Op0 = Op.getOperand(0);
13664   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13665   unsigned LogicOp =
13666     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13667   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13668
13669   if (VT.isVector() || IsF128)
13670     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13671
13672   // For the scalar case extend to a 128-bit vector, perform the logic op,
13673   // and extract the scalar result back out.
13674   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13675   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13676   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13677                      DAG.getIntPtrConstant(0, dl));
13678 }
13679
13680 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13681   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13682   LLVMContext *Context = DAG.getContext();
13683   SDValue Op0 = Op.getOperand(0);
13684   SDValue Op1 = Op.getOperand(1);
13685   SDLoc dl(Op);
13686   MVT VT = Op.getSimpleValueType();
13687   MVT SrcVT = Op1.getSimpleValueType();
13688   bool IsF128 = (VT == MVT::f128);
13689
13690   // If second operand is smaller, extend it first.
13691   if (SrcVT.bitsLT(VT)) {
13692     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13693     SrcVT = VT;
13694   }
13695   // And if it is bigger, shrink it first.
13696   if (SrcVT.bitsGT(VT)) {
13697     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13698     SrcVT = VT;
13699   }
13700
13701   // At this point the operands and the result should have the same
13702   // type, and that won't be f80 since that is not custom lowered.
13703   assert((VT == MVT::f64 || VT == MVT::f32 || IsF128) &&
13704          "Unexpected type in LowerFCOPYSIGN");
13705
13706   const fltSemantics &Sem =
13707       VT == MVT::f64 ? APFloat::IEEEdouble :
13708           (IsF128 ? APFloat::IEEEquad : APFloat::IEEEsingle);
13709   const unsigned SizeInBits = VT.getSizeInBits();
13710
13711   SmallVector<Constant *, 4> CV(
13712       VT == MVT::f64 ? 2 : (IsF128 ? 1 : 4),
13713       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13714
13715   // First, clear all bits but the sign bit from the second operand (sign).
13716   CV[0] = ConstantFP::get(*Context,
13717                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13718   Constant *C = ConstantVector::get(CV);
13719   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13720   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13721
13722   // Perform all logic operations as 16-byte vectors because there are no
13723   // scalar FP logic instructions in SSE. This allows load folding of the
13724   // constants into the logic instructions.
13725   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : (IsF128 ? MVT::f128 : MVT::v4f32);
13726   SDValue Mask1 =
13727       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13728                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13729                   false, false, false, 16);
13730   if (!IsF128)
13731     Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13732   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13733
13734   // Next, clear the sign bit from the first operand (magnitude).
13735   // If it's a constant, we can clear it here.
13736   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13737     APFloat APF = Op0CN->getValueAPF();
13738     // If the magnitude is a positive zero, the sign bit alone is enough.
13739     if (APF.isPosZero())
13740       return IsF128 ? SignBit :
13741           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13742                       DAG.getIntPtrConstant(0, dl));
13743     APF.clearSign();
13744     CV[0] = ConstantFP::get(*Context, APF);
13745   } else {
13746     CV[0] = ConstantFP::get(
13747         *Context,
13748         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13749   }
13750   C = ConstantVector::get(CV);
13751   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13752   SDValue Val =
13753       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13754                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13755                   false, false, false, 16);
13756   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13757   if (!isa<ConstantFPSDNode>(Op0)) {
13758     if (!IsF128)
13759       Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13760     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13761   }
13762   // OR the magnitude value with the sign bit.
13763   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13764   return IsF128 ? Val :
13765       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13766                   DAG.getIntPtrConstant(0, dl));
13767 }
13768
13769 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13770   SDValue N0 = Op.getOperand(0);
13771   SDLoc dl(Op);
13772   MVT VT = Op.getSimpleValueType();
13773
13774   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13775   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13776                                   DAG.getConstant(1, dl, VT));
13777   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13778 }
13779
13780 // Check whether an OR'd tree is PTEST-able.
13781 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13782                                       SelectionDAG &DAG) {
13783   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13784
13785   if (!Subtarget->hasSSE41())
13786     return SDValue();
13787
13788   if (!Op->hasOneUse())
13789     return SDValue();
13790
13791   SDNode *N = Op.getNode();
13792   SDLoc DL(N);
13793
13794   SmallVector<SDValue, 8> Opnds;
13795   DenseMap<SDValue, unsigned> VecInMap;
13796   SmallVector<SDValue, 8> VecIns;
13797   EVT VT = MVT::Other;
13798
13799   // Recognize a special case where a vector is casted into wide integer to
13800   // test all 0s.
13801   Opnds.push_back(N->getOperand(0));
13802   Opnds.push_back(N->getOperand(1));
13803
13804   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13805     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13806     // BFS traverse all OR'd operands.
13807     if (I->getOpcode() == ISD::OR) {
13808       Opnds.push_back(I->getOperand(0));
13809       Opnds.push_back(I->getOperand(1));
13810       // Re-evaluate the number of nodes to be traversed.
13811       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13812       continue;
13813     }
13814
13815     // Quit if a non-EXTRACT_VECTOR_ELT
13816     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13817       return SDValue();
13818
13819     // Quit if without a constant index.
13820     SDValue Idx = I->getOperand(1);
13821     if (!isa<ConstantSDNode>(Idx))
13822       return SDValue();
13823
13824     SDValue ExtractedFromVec = I->getOperand(0);
13825     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13826     if (M == VecInMap.end()) {
13827       VT = ExtractedFromVec.getValueType();
13828       // Quit if not 128/256-bit vector.
13829       if (!VT.is128BitVector() && !VT.is256BitVector())
13830         return SDValue();
13831       // Quit if not the same type.
13832       if (VecInMap.begin() != VecInMap.end() &&
13833           VT != VecInMap.begin()->first.getValueType())
13834         return SDValue();
13835       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13836       VecIns.push_back(ExtractedFromVec);
13837     }
13838     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13839   }
13840
13841   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13842          "Not extracted from 128-/256-bit vector.");
13843
13844   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13845
13846   for (DenseMap<SDValue, unsigned>::const_iterator
13847         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13848     // Quit if not all elements are used.
13849     if (I->second != FullMask)
13850       return SDValue();
13851   }
13852
13853   MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13854
13855   // Cast all vectors into TestVT for PTEST.
13856   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13857     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13858
13859   // If more than one full vectors are evaluated, OR them first before PTEST.
13860   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13861     // Each iteration will OR 2 nodes and append the result until there is only
13862     // 1 node left, i.e. the final OR'd value of all vectors.
13863     SDValue LHS = VecIns[Slot];
13864     SDValue RHS = VecIns[Slot + 1];
13865     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13866   }
13867
13868   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13869                      VecIns.back(), VecIns.back());
13870 }
13871
13872 /// \brief return true if \c Op has a use that doesn't just read flags.
13873 static bool hasNonFlagsUse(SDValue Op) {
13874   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13875        ++UI) {
13876     SDNode *User = *UI;
13877     unsigned UOpNo = UI.getOperandNo();
13878     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13879       // Look pass truncate.
13880       UOpNo = User->use_begin().getOperandNo();
13881       User = *User->use_begin();
13882     }
13883
13884     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13885         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13886       return true;
13887   }
13888   return false;
13889 }
13890
13891 /// Emit nodes that will be selected as "test Op0,Op0", or something
13892 /// equivalent.
13893 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13894                                     SelectionDAG &DAG) const {
13895   if (Op.getValueType() == MVT::i1) {
13896     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13897     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13898                        DAG.getConstant(0, dl, MVT::i8));
13899   }
13900   // CF and OF aren't always set the way we want. Determine which
13901   // of these we need.
13902   bool NeedCF = false;
13903   bool NeedOF = false;
13904   switch (X86CC) {
13905   default: break;
13906   case X86::COND_A: case X86::COND_AE:
13907   case X86::COND_B: case X86::COND_BE:
13908     NeedCF = true;
13909     break;
13910   case X86::COND_G: case X86::COND_GE:
13911   case X86::COND_L: case X86::COND_LE:
13912   case X86::COND_O: case X86::COND_NO: {
13913     // Check if we really need to set the
13914     // Overflow flag. If NoSignedWrap is present
13915     // that is not actually needed.
13916     switch (Op->getOpcode()) {
13917     case ISD::ADD:
13918     case ISD::SUB:
13919     case ISD::MUL:
13920     case ISD::SHL: {
13921       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13922       if (BinNode->Flags.hasNoSignedWrap())
13923         break;
13924     }
13925     default:
13926       NeedOF = true;
13927       break;
13928     }
13929     break;
13930   }
13931   }
13932   // See if we can use the EFLAGS value from the operand instead of
13933   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13934   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13935   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13936     // Emit a CMP with 0, which is the TEST pattern.
13937     //if (Op.getValueType() == MVT::i1)
13938     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13939     //                     DAG.getConstant(0, MVT::i1));
13940     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13941                        DAG.getConstant(0, dl, Op.getValueType()));
13942   }
13943   unsigned Opcode = 0;
13944   unsigned NumOperands = 0;
13945
13946   // Truncate operations may prevent the merge of the SETCC instruction
13947   // and the arithmetic instruction before it. Attempt to truncate the operands
13948   // of the arithmetic instruction and use a reduced bit-width instruction.
13949   bool NeedTruncation = false;
13950   SDValue ArithOp = Op;
13951   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13952     SDValue Arith = Op->getOperand(0);
13953     // Both the trunc and the arithmetic op need to have one user each.
13954     if (Arith->hasOneUse())
13955       switch (Arith.getOpcode()) {
13956         default: break;
13957         case ISD::ADD:
13958         case ISD::SUB:
13959         case ISD::AND:
13960         case ISD::OR:
13961         case ISD::XOR: {
13962           NeedTruncation = true;
13963           ArithOp = Arith;
13964         }
13965       }
13966   }
13967
13968   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13969   // which may be the result of a CAST.  We use the variable 'Op', which is the
13970   // non-casted variable when we check for possible users.
13971   switch (ArithOp.getOpcode()) {
13972   case ISD::ADD:
13973     // Due to an isel shortcoming, be conservative if this add is likely to be
13974     // selected as part of a load-modify-store instruction. When the root node
13975     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13976     // uses of other nodes in the match, such as the ADD in this case. This
13977     // leads to the ADD being left around and reselected, with the result being
13978     // two adds in the output.  Alas, even if none our users are stores, that
13979     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13980     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13981     // climbing the DAG back to the root, and it doesn't seem to be worth the
13982     // effort.
13983     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13984          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13985       if (UI->getOpcode() != ISD::CopyToReg &&
13986           UI->getOpcode() != ISD::SETCC &&
13987           UI->getOpcode() != ISD::STORE)
13988         goto default_case;
13989
13990     if (ConstantSDNode *C =
13991         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13992       // An add of one will be selected as an INC.
13993       if (C->isOne() && !Subtarget->slowIncDec()) {
13994         Opcode = X86ISD::INC;
13995         NumOperands = 1;
13996         break;
13997       }
13998
13999       // An add of negative one (subtract of one) will be selected as a DEC.
14000       if (C->isAllOnesValue() && !Subtarget->slowIncDec()) {
14001         Opcode = X86ISD::DEC;
14002         NumOperands = 1;
14003         break;
14004       }
14005     }
14006
14007     // Otherwise use a regular EFLAGS-setting add.
14008     Opcode = X86ISD::ADD;
14009     NumOperands = 2;
14010     break;
14011   case ISD::SHL:
14012   case ISD::SRL:
14013     // If we have a constant logical shift that's only used in a comparison
14014     // against zero turn it into an equivalent AND. This allows turning it into
14015     // a TEST instruction later.
14016     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
14017         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
14018       EVT VT = Op.getValueType();
14019       unsigned BitWidth = VT.getSizeInBits();
14020       unsigned ShAmt = Op->getConstantOperandVal(1);
14021       if (ShAmt >= BitWidth) // Avoid undefined shifts.
14022         break;
14023       APInt Mask = ArithOp.getOpcode() == ISD::SRL
14024                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
14025                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
14026       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
14027         break;
14028       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
14029                                 DAG.getConstant(Mask, dl, VT));
14030       DAG.ReplaceAllUsesWith(Op, New);
14031       Op = New;
14032     }
14033     break;
14034
14035   case ISD::AND:
14036     // If the primary and result isn't used, don't bother using X86ISD::AND,
14037     // because a TEST instruction will be better.
14038     if (!hasNonFlagsUse(Op))
14039       break;
14040     // FALL THROUGH
14041   case ISD::SUB:
14042   case ISD::OR:
14043   case ISD::XOR:
14044     // Due to the ISEL shortcoming noted above, be conservative if this op is
14045     // likely to be selected as part of a load-modify-store instruction.
14046     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14047            UE = Op.getNode()->use_end(); UI != UE; ++UI)
14048       if (UI->getOpcode() == ISD::STORE)
14049         goto default_case;
14050
14051     // Otherwise use a regular EFLAGS-setting instruction.
14052     switch (ArithOp.getOpcode()) {
14053     default: llvm_unreachable("unexpected operator!");
14054     case ISD::SUB: Opcode = X86ISD::SUB; break;
14055     case ISD::XOR: Opcode = X86ISD::XOR; break;
14056     case ISD::AND: Opcode = X86ISD::AND; break;
14057     case ISD::OR: {
14058       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
14059         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
14060         if (EFLAGS.getNode())
14061           return EFLAGS;
14062       }
14063       Opcode = X86ISD::OR;
14064       break;
14065     }
14066     }
14067
14068     NumOperands = 2;
14069     break;
14070   case X86ISD::ADD:
14071   case X86ISD::SUB:
14072   case X86ISD::INC:
14073   case X86ISD::DEC:
14074   case X86ISD::OR:
14075   case X86ISD::XOR:
14076   case X86ISD::AND:
14077     return SDValue(Op.getNode(), 1);
14078   default:
14079   default_case:
14080     break;
14081   }
14082
14083   // If we found that truncation is beneficial, perform the truncation and
14084   // update 'Op'.
14085   if (NeedTruncation) {
14086     EVT VT = Op.getValueType();
14087     SDValue WideVal = Op->getOperand(0);
14088     EVT WideVT = WideVal.getValueType();
14089     unsigned ConvertedOp = 0;
14090     // Use a target machine opcode to prevent further DAGCombine
14091     // optimizations that may separate the arithmetic operations
14092     // from the setcc node.
14093     switch (WideVal.getOpcode()) {
14094       default: break;
14095       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
14096       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
14097       case ISD::AND: ConvertedOp = X86ISD::AND; break;
14098       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
14099       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
14100     }
14101
14102     if (ConvertedOp) {
14103       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14104       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
14105         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
14106         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
14107         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
14108       }
14109     }
14110   }
14111
14112   if (Opcode == 0)
14113     // Emit a CMP with 0, which is the TEST pattern.
14114     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14115                        DAG.getConstant(0, dl, Op.getValueType()));
14116
14117   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14118   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
14119
14120   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
14121   DAG.ReplaceAllUsesWith(Op, New);
14122   return SDValue(New.getNode(), 1);
14123 }
14124
14125 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
14126 /// equivalent.
14127 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
14128                                    SDLoc dl, SelectionDAG &DAG) const {
14129   if (isNullConstant(Op1))
14130     return EmitTest(Op0, X86CC, dl, DAG);
14131
14132   assert(!(isa<ConstantSDNode>(Op1) && Op0.getValueType() == MVT::i1) &&
14133          "Unexpected comparison operation for MVT::i1 operands");
14134
14135   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14136        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14137     // Do the comparison at i32 if it's smaller, besides the Atom case.
14138     // This avoids subregister aliasing issues. Keep the smaller reference
14139     // if we're optimizing for size, however, as that'll allow better folding
14140     // of memory operations.
14141     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
14142         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
14143         !Subtarget->isAtom()) {
14144       unsigned ExtendOp =
14145           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14146       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14147       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14148     }
14149     // Use SUB instead of CMP to enable CSE between SUB and CMP.
14150     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14151     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14152                               Op0, Op1);
14153     return SDValue(Sub.getNode(), 1);
14154   }
14155   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14156 }
14157
14158 /// Convert a comparison if required by the subtarget.
14159 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14160                                                  SelectionDAG &DAG) const {
14161   // If the subtarget does not support the FUCOMI instruction, floating-point
14162   // comparisons have to be converted.
14163   if (Subtarget->hasCMov() ||
14164       Cmp.getOpcode() != X86ISD::CMP ||
14165       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14166       !Cmp.getOperand(1).getValueType().isFloatingPoint())
14167     return Cmp;
14168
14169   // The instruction selector will select an FUCOM instruction instead of
14170   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14171   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14172   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14173   SDLoc dl(Cmp);
14174   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14175   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14176   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14177                             DAG.getConstant(8, dl, MVT::i8));
14178   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14179
14180   // Some 64-bit targets lack SAHF support, but they do support FCOMI.
14181   assert(Subtarget->hasLAHFSAHF() && "Target doesn't support SAHF or FCOMI?");
14182   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14183 }
14184
14185 /// The minimum architected relative accuracy is 2^-12. We need one
14186 /// Newton-Raphson step to have a good float result (24 bits of precision).
14187 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14188                                             DAGCombinerInfo &DCI,
14189                                             unsigned &RefinementSteps,
14190                                             bool &UseOneConstNR) const {
14191   EVT VT = Op.getValueType();
14192   const char *RecipOp;
14193
14194   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
14195   // TODO: Add support for AVX512 (v16f32).
14196   // It is likely not profitable to do this for f64 because a double-precision
14197   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14198   // instructions: convert to single, rsqrtss, convert back to double, refine
14199   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14200   // along with FMA, this could be a throughput win.
14201   if (VT == MVT::f32 && Subtarget->hasSSE1())
14202     RecipOp = "sqrtf";
14203   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14204            (VT == MVT::v8f32 && Subtarget->hasAVX()))
14205     RecipOp = "vec-sqrtf";
14206   else
14207     return SDValue();
14208
14209   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14210   if (!Recips.isEnabled(RecipOp))
14211     return SDValue();
14212
14213   RefinementSteps = Recips.getRefinementSteps(RecipOp);
14214   UseOneConstNR = false;
14215   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14216 }
14217
14218 /// The minimum architected relative accuracy is 2^-12. We need one
14219 /// Newton-Raphson step to have a good float result (24 bits of precision).
14220 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14221                                             DAGCombinerInfo &DCI,
14222                                             unsigned &RefinementSteps) const {
14223   EVT VT = Op.getValueType();
14224   const char *RecipOp;
14225
14226   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
14227   // TODO: Add support for AVX512 (v16f32).
14228   // It is likely not profitable to do this for f64 because a double-precision
14229   // reciprocal estimate with refinement on x86 prior to FMA requires
14230   // 15 instructions: convert to single, rcpss, convert back to double, refine
14231   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
14232   // along with FMA, this could be a throughput win.
14233   if (VT == MVT::f32 && Subtarget->hasSSE1())
14234     RecipOp = "divf";
14235   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14236            (VT == MVT::v8f32 && Subtarget->hasAVX()))
14237     RecipOp = "vec-divf";
14238   else
14239     return SDValue();
14240
14241   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14242   if (!Recips.isEnabled(RecipOp))
14243     return SDValue();
14244
14245   RefinementSteps = Recips.getRefinementSteps(RecipOp);
14246   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
14247 }
14248
14249 /// If we have at least two divisions that use the same divisor, convert to
14250 /// multplication by a reciprocal. This may need to be adjusted for a given
14251 /// CPU if a division's cost is not at least twice the cost of a multiplication.
14252 /// This is because we still need one division to calculate the reciprocal and
14253 /// then we need two multiplies by that reciprocal as replacements for the
14254 /// original divisions.
14255 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
14256   return 2;
14257 }
14258
14259 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
14260 /// if it's possible.
14261 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
14262                                      SDLoc dl, SelectionDAG &DAG) const {
14263   SDValue Op0 = And.getOperand(0);
14264   SDValue Op1 = And.getOperand(1);
14265   if (Op0.getOpcode() == ISD::TRUNCATE)
14266     Op0 = Op0.getOperand(0);
14267   if (Op1.getOpcode() == ISD::TRUNCATE)
14268     Op1 = Op1.getOperand(0);
14269
14270   SDValue LHS, RHS;
14271   if (Op1.getOpcode() == ISD::SHL)
14272     std::swap(Op0, Op1);
14273   if (Op0.getOpcode() == ISD::SHL) {
14274     if (isOneConstant(Op0.getOperand(0))) {
14275         // If we looked past a truncate, check that it's only truncating away
14276         // known zeros.
14277         unsigned BitWidth = Op0.getValueSizeInBits();
14278         unsigned AndBitWidth = And.getValueSizeInBits();
14279         if (BitWidth > AndBitWidth) {
14280           APInt Zeros, Ones;
14281           DAG.computeKnownBits(Op0, Zeros, Ones);
14282           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
14283             return SDValue();
14284         }
14285         LHS = Op1;
14286         RHS = Op0.getOperand(1);
14287       }
14288   } else if (Op1.getOpcode() == ISD::Constant) {
14289     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
14290     uint64_t AndRHSVal = AndRHS->getZExtValue();
14291     SDValue AndLHS = Op0;
14292
14293     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
14294       LHS = AndLHS.getOperand(0);
14295       RHS = AndLHS.getOperand(1);
14296     }
14297
14298     // Use BT if the immediate can't be encoded in a TEST instruction.
14299     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
14300       LHS = AndLHS;
14301       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
14302     }
14303   }
14304
14305   if (LHS.getNode()) {
14306     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
14307     // instruction.  Since the shift amount is in-range-or-undefined, we know
14308     // that doing a bittest on the i32 value is ok.  We extend to i32 because
14309     // the encoding for the i16 version is larger than the i32 version.
14310     // Also promote i16 to i32 for performance / code size reason.
14311     if (LHS.getValueType() == MVT::i8 ||
14312         LHS.getValueType() == MVT::i16)
14313       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
14314
14315     // If the operand types disagree, extend the shift amount to match.  Since
14316     // BT ignores high bits (like shifts) we can use anyextend.
14317     if (LHS.getValueType() != RHS.getValueType())
14318       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
14319
14320     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
14321     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
14322     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14323                        DAG.getConstant(Cond, dl, MVT::i8), BT);
14324   }
14325
14326   return SDValue();
14327 }
14328
14329 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14330 /// mask CMPs.
14331 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14332                               SDValue &Op1) {
14333   unsigned SSECC;
14334   bool Swap = false;
14335
14336   // SSE Condition code mapping:
14337   //  0 - EQ
14338   //  1 - LT
14339   //  2 - LE
14340   //  3 - UNORD
14341   //  4 - NEQ
14342   //  5 - NLT
14343   //  6 - NLE
14344   //  7 - ORD
14345   switch (SetCCOpcode) {
14346   default: llvm_unreachable("Unexpected SETCC condition");
14347   case ISD::SETOEQ:
14348   case ISD::SETEQ:  SSECC = 0; break;
14349   case ISD::SETOGT:
14350   case ISD::SETGT:  Swap = true; // Fallthrough
14351   case ISD::SETLT:
14352   case ISD::SETOLT: SSECC = 1; break;
14353   case ISD::SETOGE:
14354   case ISD::SETGE:  Swap = true; // Fallthrough
14355   case ISD::SETLE:
14356   case ISD::SETOLE: SSECC = 2; break;
14357   case ISD::SETUO:  SSECC = 3; break;
14358   case ISD::SETUNE:
14359   case ISD::SETNE:  SSECC = 4; break;
14360   case ISD::SETULE: Swap = true; // Fallthrough
14361   case ISD::SETUGE: SSECC = 5; break;
14362   case ISD::SETULT: Swap = true; // Fallthrough
14363   case ISD::SETUGT: SSECC = 6; break;
14364   case ISD::SETO:   SSECC = 7; break;
14365   case ISD::SETUEQ:
14366   case ISD::SETONE: SSECC = 8; break;
14367   }
14368   if (Swap)
14369     std::swap(Op0, Op1);
14370
14371   return SSECC;
14372 }
14373
14374 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14375 // ones, and then concatenate the result back.
14376 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14377   MVT VT = Op.getSimpleValueType();
14378
14379   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14380          "Unsupported value type for operation");
14381
14382   unsigned NumElems = VT.getVectorNumElements();
14383   SDLoc dl(Op);
14384   SDValue CC = Op.getOperand(2);
14385
14386   // Extract the LHS vectors
14387   SDValue LHS = Op.getOperand(0);
14388   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14389   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14390
14391   // Extract the RHS vectors
14392   SDValue RHS = Op.getOperand(1);
14393   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14394   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14395
14396   // Issue the operation on the smaller types and concatenate the result back
14397   MVT EltVT = VT.getVectorElementType();
14398   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14399   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14400                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14401                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14402 }
14403
14404 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14405   SDValue Op0 = Op.getOperand(0);
14406   SDValue Op1 = Op.getOperand(1);
14407   SDValue CC = Op.getOperand(2);
14408   MVT VT = Op.getSimpleValueType();
14409   SDLoc dl(Op);
14410
14411   assert(Op0.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14412          "Unexpected type for boolean compare operation");
14413   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14414   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14415                                DAG.getConstant(-1, dl, VT));
14416   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14417                                DAG.getConstant(-1, dl, VT));
14418   switch (SetCCOpcode) {
14419   default: llvm_unreachable("Unexpected SETCC condition");
14420   case ISD::SETEQ:
14421     // (x == y) -> ~(x ^ y)
14422     return DAG.getNode(ISD::XOR, dl, VT,
14423                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14424                        DAG.getConstant(-1, dl, VT));
14425   case ISD::SETNE:
14426     // (x != y) -> (x ^ y)
14427     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14428   case ISD::SETUGT:
14429   case ISD::SETGT:
14430     // (x > y) -> (x & ~y)
14431     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14432   case ISD::SETULT:
14433   case ISD::SETLT:
14434     // (x < y) -> (~x & y)
14435     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14436   case ISD::SETULE:
14437   case ISD::SETLE:
14438     // (x <= y) -> (~x | y)
14439     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14440   case ISD::SETUGE:
14441   case ISD::SETGE:
14442     // (x >=y) -> (x | ~y)
14443     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14444   }
14445 }
14446
14447 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14448                                      const X86Subtarget *Subtarget) {
14449   SDValue Op0 = Op.getOperand(0);
14450   SDValue Op1 = Op.getOperand(1);
14451   SDValue CC = Op.getOperand(2);
14452   MVT VT = Op.getSimpleValueType();
14453   SDLoc dl(Op);
14454
14455   assert(Op0.getSimpleValueType().getVectorElementType().getSizeInBits() >= 8 &&
14456          Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14457          "Cannot set masked compare for this operation");
14458
14459   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14460   unsigned  Opc = 0;
14461   bool Unsigned = false;
14462   bool Swap = false;
14463   unsigned SSECC;
14464   switch (SetCCOpcode) {
14465   default: llvm_unreachable("Unexpected SETCC condition");
14466   case ISD::SETNE:  SSECC = 4; break;
14467   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14468   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14469   case ISD::SETLT:  Swap = true; //fall-through
14470   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14471   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14472   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14473   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14474   case ISD::SETULE: Unsigned = true; //fall-through
14475   case ISD::SETLE:  SSECC = 2; break;
14476   }
14477
14478   if (Swap)
14479     std::swap(Op0, Op1);
14480   if (Opc)
14481     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14482   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14483   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14484                      DAG.getConstant(SSECC, dl, MVT::i8));
14485 }
14486
14487 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14488 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14489 /// return an empty value.
14490 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14491 {
14492   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14493   if (!BV)
14494     return SDValue();
14495
14496   MVT VT = Op1.getSimpleValueType();
14497   MVT EVT = VT.getVectorElementType();
14498   unsigned n = VT.getVectorNumElements();
14499   SmallVector<SDValue, 8> ULTOp1;
14500
14501   for (unsigned i = 0; i < n; ++i) {
14502     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14503     if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EVT)
14504       return SDValue();
14505
14506     // Avoid underflow.
14507     APInt Val = Elt->getAPIntValue();
14508     if (Val == 0)
14509       return SDValue();
14510
14511     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14512   }
14513
14514   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14515 }
14516
14517 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14518                            SelectionDAG &DAG) {
14519   SDValue Op0 = Op.getOperand(0);
14520   SDValue Op1 = Op.getOperand(1);
14521   SDValue CC = Op.getOperand(2);
14522   MVT VT = Op.getSimpleValueType();
14523   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14524   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14525   SDLoc dl(Op);
14526
14527   if (isFP) {
14528 #ifndef NDEBUG
14529     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14530     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14531 #endif
14532
14533     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14534     unsigned Opc = X86ISD::CMPP;
14535     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14536       assert(VT.getVectorNumElements() <= 16);
14537       Opc = X86ISD::CMPM;
14538     }
14539     // In the two special cases we can't handle, emit two comparisons.
14540     if (SSECC == 8) {
14541       unsigned CC0, CC1;
14542       unsigned CombineOpc;
14543       if (SetCCOpcode == ISD::SETUEQ) {
14544         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14545       } else {
14546         assert(SetCCOpcode == ISD::SETONE);
14547         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14548       }
14549
14550       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14551                                  DAG.getConstant(CC0, dl, MVT::i8));
14552       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14553                                  DAG.getConstant(CC1, dl, MVT::i8));
14554       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14555     }
14556     // Handle all other FP comparisons here.
14557     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14558                        DAG.getConstant(SSECC, dl, MVT::i8));
14559   }
14560
14561   MVT VTOp0 = Op0.getSimpleValueType();
14562   assert(VTOp0 == Op1.getSimpleValueType() &&
14563          "Expected operands with same type!");
14564   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14565          "Invalid number of packed elements for source and destination!");
14566
14567   if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14568     // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14569     // legalizer to a wider vector type.  In the case of 'vsetcc' nodes, the
14570     // legalizer firstly checks if the first operand in input to the setcc has
14571     // a legal type. If so, then it promotes the return type to that same type.
14572     // Otherwise, the return type is promoted to the 'next legal type' which,
14573     // for a vector of MVT::i1 is always a 128-bit integer vector type.
14574     //
14575     // We reach this code only if the following two conditions are met:
14576     // 1. Both return type and operand type have been promoted to wider types
14577     //    by the type legalizer.
14578     // 2. The original operand type has been promoted to a 256-bit vector.
14579     //
14580     // Note that condition 2. only applies for AVX targets.
14581     SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14582     return DAG.getZExtOrTrunc(NewOp, dl, VT);
14583   }
14584
14585   // The non-AVX512 code below works under the assumption that source and
14586   // destination types are the same.
14587   assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14588          "Value types for source and destination must be the same!");
14589
14590   // Break 256-bit integer vector compare into smaller ones.
14591   if (VT.is256BitVector() && !Subtarget->hasInt256())
14592     return Lower256IntVSETCC(Op, DAG);
14593
14594   MVT OpVT = Op1.getSimpleValueType();
14595   if (OpVT.getVectorElementType() == MVT::i1)
14596     return LowerBoolVSETCC_AVX512(Op, DAG);
14597
14598   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14599   if (Subtarget->hasAVX512()) {
14600     if (Op1.getSimpleValueType().is512BitVector() ||
14601         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14602         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14603       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14604
14605     // In AVX-512 architecture setcc returns mask with i1 elements,
14606     // But there is no compare instruction for i8 and i16 elements in KNL.
14607     // We are not talking about 512-bit operands in this case, these
14608     // types are illegal.
14609     if (MaskResult &&
14610         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14611          OpVT.getVectorElementType().getSizeInBits() >= 8))
14612       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14613                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14614   }
14615
14616   // Lower using XOP integer comparisons.
14617   if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14618        VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14619     // Translate compare code to XOP PCOM compare mode.
14620     unsigned CmpMode = 0;
14621     switch (SetCCOpcode) {
14622     default: llvm_unreachable("Unexpected SETCC condition");
14623     case ISD::SETULT:
14624     case ISD::SETLT: CmpMode = 0x00; break;
14625     case ISD::SETULE:
14626     case ISD::SETLE: CmpMode = 0x01; break;
14627     case ISD::SETUGT:
14628     case ISD::SETGT: CmpMode = 0x02; break;
14629     case ISD::SETUGE:
14630     case ISD::SETGE: CmpMode = 0x03; break;
14631     case ISD::SETEQ: CmpMode = 0x04; break;
14632     case ISD::SETNE: CmpMode = 0x05; break;
14633     }
14634
14635     // Are we comparing unsigned or signed integers?
14636     unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14637       ? X86ISD::VPCOMU : X86ISD::VPCOM;
14638
14639     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14640                        DAG.getConstant(CmpMode, dl, MVT::i8));
14641   }
14642
14643   // We are handling one of the integer comparisons here.  Since SSE only has
14644   // GT and EQ comparisons for integer, swapping operands and multiple
14645   // operations may be required for some comparisons.
14646   unsigned Opc;
14647   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14648   bool Subus = false;
14649
14650   switch (SetCCOpcode) {
14651   default: llvm_unreachable("Unexpected SETCC condition");
14652   case ISD::SETNE:  Invert = true;
14653   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14654   case ISD::SETLT:  Swap = true;
14655   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14656   case ISD::SETGE:  Swap = true;
14657   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14658                     Invert = true; break;
14659   case ISD::SETULT: Swap = true;
14660   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14661                     FlipSigns = true; break;
14662   case ISD::SETUGE: Swap = true;
14663   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14664                     FlipSigns = true; Invert = true; break;
14665   }
14666
14667   // Special case: Use min/max operations for SETULE/SETUGE
14668   MVT VET = VT.getVectorElementType();
14669   bool hasMinMax =
14670        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14671     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14672
14673   if (hasMinMax) {
14674     switch (SetCCOpcode) {
14675     default: break;
14676     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14677     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14678     }
14679
14680     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14681   }
14682
14683   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14684   if (!MinMax && hasSubus) {
14685     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14686     // Op0 u<= Op1:
14687     //   t = psubus Op0, Op1
14688     //   pcmpeq t, <0..0>
14689     switch (SetCCOpcode) {
14690     default: break;
14691     case ISD::SETULT: {
14692       // If the comparison is against a constant we can turn this into a
14693       // setule.  With psubus, setule does not require a swap.  This is
14694       // beneficial because the constant in the register is no longer
14695       // destructed as the destination so it can be hoisted out of a loop.
14696       // Only do this pre-AVX since vpcmp* is no longer destructive.
14697       if (Subtarget->hasAVX())
14698         break;
14699       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14700       if (ULEOp1.getNode()) {
14701         Op1 = ULEOp1;
14702         Subus = true; Invert = false; Swap = false;
14703       }
14704       break;
14705     }
14706     // Psubus is better than flip-sign because it requires no inversion.
14707     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14708     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14709     }
14710
14711     if (Subus) {
14712       Opc = X86ISD::SUBUS;
14713       FlipSigns = false;
14714     }
14715   }
14716
14717   if (Swap)
14718     std::swap(Op0, Op1);
14719
14720   // Check that the operation in question is available (most are plain SSE2,
14721   // but PCMPGTQ and PCMPEQQ have different requirements).
14722   if (VT == MVT::v2i64) {
14723     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14724       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14725
14726       // First cast everything to the right type.
14727       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14728       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14729
14730       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14731       // bits of the inputs before performing those operations. The lower
14732       // compare is always unsigned.
14733       SDValue SB;
14734       if (FlipSigns) {
14735         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14736       } else {
14737         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14738         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14739         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14740                          Sign, Zero, Sign, Zero);
14741       }
14742       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14743       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14744
14745       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14746       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14747       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14748
14749       // Create masks for only the low parts/high parts of the 64 bit integers.
14750       static const int MaskHi[] = { 1, 1, 3, 3 };
14751       static const int MaskLo[] = { 0, 0, 2, 2 };
14752       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14753       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14754       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14755
14756       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14757       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14758
14759       if (Invert)
14760         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14761
14762       return DAG.getBitcast(VT, Result);
14763     }
14764
14765     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14766       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14767       // pcmpeqd + pshufd + pand.
14768       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14769
14770       // First cast everything to the right type.
14771       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14772       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14773
14774       // Do the compare.
14775       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14776
14777       // Make sure the lower and upper halves are both all-ones.
14778       static const int Mask[] = { 1, 0, 3, 2 };
14779       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14780       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14781
14782       if (Invert)
14783         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14784
14785       return DAG.getBitcast(VT, Result);
14786     }
14787   }
14788
14789   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14790   // bits of the inputs before performing those operations.
14791   if (FlipSigns) {
14792     MVT EltVT = VT.getVectorElementType();
14793     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14794                                  VT);
14795     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14796     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14797   }
14798
14799   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14800
14801   // If the logical-not of the result is required, perform that now.
14802   if (Invert)
14803     Result = DAG.getNOT(dl, Result, VT);
14804
14805   if (MinMax)
14806     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14807
14808   if (Subus)
14809     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14810                          getZeroVector(VT, Subtarget, DAG, dl));
14811
14812   return Result;
14813 }
14814
14815 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14816
14817   MVT VT = Op.getSimpleValueType();
14818
14819   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14820
14821   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14822          && "SetCC type must be 8-bit or 1-bit integer");
14823   SDValue Op0 = Op.getOperand(0);
14824   SDValue Op1 = Op.getOperand(1);
14825   SDLoc dl(Op);
14826   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14827
14828   // Optimize to BT if possible.
14829   // Lower (X & (1 << N)) == 0 to BT(X, N).
14830   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14831   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14832   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14833       isNullConstant(Op1) &&
14834       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14835     if (SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG)) {
14836       if (VT == MVT::i1)
14837         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14838       return NewSetCC;
14839     }
14840   }
14841
14842   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14843   // these.
14844   if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
14845       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14846
14847     // If the input is a setcc, then reuse the input setcc or use a new one with
14848     // the inverted condition.
14849     if (Op0.getOpcode() == X86ISD::SETCC) {
14850       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14851       bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
14852       if (!Invert)
14853         return Op0;
14854
14855       CCode = X86::GetOppositeBranchCondition(CCode);
14856       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14857                                   DAG.getConstant(CCode, dl, MVT::i8),
14858                                   Op0.getOperand(1));
14859       if (VT == MVT::i1)
14860         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14861       return SetCC;
14862     }
14863   }
14864   if ((Op0.getValueType() == MVT::i1) && isOneConstant(Op1) &&
14865       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14866
14867     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14868     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14869   }
14870
14871   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14872   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14873   if (X86CC == X86::COND_INVALID)
14874     return SDValue();
14875
14876   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14877   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14878   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14879                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14880   if (VT == MVT::i1)
14881     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14882   return SetCC;
14883 }
14884
14885 SDValue X86TargetLowering::LowerSETCCE(SDValue Op, SelectionDAG &DAG) const {
14886   SDValue LHS = Op.getOperand(0);
14887   SDValue RHS = Op.getOperand(1);
14888   SDValue Carry = Op.getOperand(2);
14889   SDValue Cond = Op.getOperand(3);
14890   SDLoc DL(Op);
14891
14892   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
14893   X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
14894
14895   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
14896   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14897   SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry);
14898   return DAG.getNode(X86ISD::SETCC, DL, Op.getValueType(),
14899                      DAG.getConstant(CC, DL, MVT::i8), Cmp.getValue(1));
14900 }
14901
14902 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14903 static bool isX86LogicalCmp(SDValue Op) {
14904   unsigned Opc = Op.getNode()->getOpcode();
14905   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14906       Opc == X86ISD::SAHF)
14907     return true;
14908   if (Op.getResNo() == 1 &&
14909       (Opc == X86ISD::ADD ||
14910        Opc == X86ISD::SUB ||
14911        Opc == X86ISD::ADC ||
14912        Opc == X86ISD::SBB ||
14913        Opc == X86ISD::SMUL ||
14914        Opc == X86ISD::UMUL ||
14915        Opc == X86ISD::INC ||
14916        Opc == X86ISD::DEC ||
14917        Opc == X86ISD::OR ||
14918        Opc == X86ISD::XOR ||
14919        Opc == X86ISD::AND))
14920     return true;
14921
14922   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14923     return true;
14924
14925   return false;
14926 }
14927
14928 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14929   if (V.getOpcode() != ISD::TRUNCATE)
14930     return false;
14931
14932   SDValue VOp0 = V.getOperand(0);
14933   unsigned InBits = VOp0.getValueSizeInBits();
14934   unsigned Bits = V.getValueSizeInBits();
14935   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14936 }
14937
14938 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14939   bool addTest = true;
14940   SDValue Cond  = Op.getOperand(0);
14941   SDValue Op1 = Op.getOperand(1);
14942   SDValue Op2 = Op.getOperand(2);
14943   SDLoc DL(Op);
14944   MVT VT = Op1.getSimpleValueType();
14945   SDValue CC;
14946
14947   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14948   // are available or VBLENDV if AVX is available.
14949   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14950   if (Cond.getOpcode() == ISD::SETCC &&
14951       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14952        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14953       VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
14954     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14955     int SSECC = translateX86FSETCC(
14956         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14957
14958     if (SSECC != 8) {
14959       if (Subtarget->hasAVX512()) {
14960         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14961                                   DAG.getConstant(SSECC, DL, MVT::i8));
14962         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14963       }
14964
14965       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14966                                 DAG.getConstant(SSECC, DL, MVT::i8));
14967
14968       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14969       // of 3 logic instructions for size savings and potentially speed.
14970       // Unfortunately, there is no scalar form of VBLENDV.
14971
14972       // If either operand is a constant, don't try this. We can expect to
14973       // optimize away at least one of the logic instructions later in that
14974       // case, so that sequence would be faster than a variable blend.
14975
14976       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14977       // uses XMM0 as the selection register. That may need just as many
14978       // instructions as the AND/ANDN/OR sequence due to register moves, so
14979       // don't bother.
14980
14981       if (Subtarget->hasAVX() &&
14982           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14983
14984         // Convert to vectors, do a VSELECT, and convert back to scalar.
14985         // All of the conversions should be optimized away.
14986
14987         MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14988         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14989         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14990         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14991
14992         MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14993         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14994
14995         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14996
14997         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14998                            VSel, DAG.getIntPtrConstant(0, DL));
14999       }
15000       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
15001       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
15002       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
15003     }
15004   }
15005
15006   if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
15007     SDValue Op1Scalar;
15008     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
15009       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
15010     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
15011       Op1Scalar = Op1.getOperand(0);
15012     SDValue Op2Scalar;
15013     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
15014       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
15015     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
15016       Op2Scalar = Op2.getOperand(0);
15017     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
15018       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
15019                                       Op1Scalar.getValueType(),
15020                                       Cond, Op1Scalar, Op2Scalar);
15021       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
15022         return DAG.getBitcast(VT, newSelect);
15023       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
15024       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
15025                          DAG.getIntPtrConstant(0, DL));
15026     }
15027   }
15028
15029   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
15030     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
15031     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15032                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
15033     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15034                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
15035     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
15036                                     Cond, Op1, Op2);
15037     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
15038   }
15039
15040   if (Cond.getOpcode() == ISD::SETCC) {
15041     SDValue NewCond = LowerSETCC(Cond, DAG);
15042     if (NewCond.getNode())
15043       Cond = NewCond;
15044   }
15045
15046   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
15047   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
15048   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
15049   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
15050   if (Cond.getOpcode() == X86ISD::SETCC &&
15051       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
15052       isNullConstant(Cond.getOperand(1).getOperand(1))) {
15053     SDValue Cmp = Cond.getOperand(1);
15054
15055     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
15056
15057     if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15058         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
15059       SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
15060
15061       SDValue CmpOp0 = Cmp.getOperand(0);
15062       // Apply further optimizations for special cases
15063       // (select (x != 0), -1, 0) -> neg & sbb
15064       // (select (x == 0), 0, -1) -> neg & sbb
15065       if (isNullConstant(Y) &&
15066             (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
15067           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
15068           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
15069                                     DAG.getConstant(0, DL,
15070                                                     CmpOp0.getValueType()),
15071                                     CmpOp0);
15072           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15073                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
15074                                     SDValue(Neg.getNode(), 1));
15075           return Res;
15076         }
15077
15078       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
15079                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
15080       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15081
15082       SDValue Res =   // Res = 0 or -1.
15083         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15084                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
15085
15086       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
15087         Res = DAG.getNOT(DL, Res, Res.getValueType());
15088
15089       if (!isNullConstant(Op2))
15090         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
15091       return Res;
15092     }
15093   }
15094
15095   // Look past (and (setcc_carry (cmp ...)), 1).
15096   if (Cond.getOpcode() == ISD::AND &&
15097       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15098       isOneConstant(Cond.getOperand(1)))
15099     Cond = Cond.getOperand(0);
15100
15101   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15102   // setting operand in place of the X86ISD::SETCC.
15103   unsigned CondOpcode = Cond.getOpcode();
15104   if (CondOpcode == X86ISD::SETCC ||
15105       CondOpcode == X86ISD::SETCC_CARRY) {
15106     CC = Cond.getOperand(0);
15107
15108     SDValue Cmp = Cond.getOperand(1);
15109     unsigned Opc = Cmp.getOpcode();
15110     MVT VT = Op.getSimpleValueType();
15111
15112     bool IllegalFPCMov = false;
15113     if (VT.isFloatingPoint() && !VT.isVector() &&
15114         !isScalarFPTypeInSSEReg(VT))  // FPStack?
15115       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
15116
15117     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
15118         Opc == X86ISD::BT) { // FIXME
15119       Cond = Cmp;
15120       addTest = false;
15121     }
15122   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15123              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15124              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15125               Cond.getOperand(0).getValueType() != MVT::i8)) {
15126     SDValue LHS = Cond.getOperand(0);
15127     SDValue RHS = Cond.getOperand(1);
15128     unsigned X86Opcode;
15129     unsigned X86Cond;
15130     SDVTList VTs;
15131     switch (CondOpcode) {
15132     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15133     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15134     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15135     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15136     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15137     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15138     default: llvm_unreachable("unexpected overflowing operator");
15139     }
15140     if (CondOpcode == ISD::UMULO)
15141       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15142                           MVT::i32);
15143     else
15144       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15145
15146     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15147
15148     if (CondOpcode == ISD::UMULO)
15149       Cond = X86Op.getValue(2);
15150     else
15151       Cond = X86Op.getValue(1);
15152
15153     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
15154     addTest = false;
15155   }
15156
15157   if (addTest) {
15158     // Look past the truncate if the high bits are known zero.
15159     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15160       Cond = Cond.getOperand(0);
15161
15162     // We know the result of AND is compared against zero. Try to match
15163     // it to BT.
15164     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15165       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG)) {
15166         CC = NewSetCC.getOperand(0);
15167         Cond = NewSetCC.getOperand(1);
15168         addTest = false;
15169       }
15170     }
15171   }
15172
15173   if (addTest) {
15174     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
15175     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
15176   }
15177
15178   // a <  b ? -1 :  0 -> RES = ~setcc_carry
15179   // a <  b ?  0 : -1 -> RES = setcc_carry
15180   // a >= b ? -1 :  0 -> RES = setcc_carry
15181   // a >= b ?  0 : -1 -> RES = ~setcc_carry
15182   if (Cond.getOpcode() == X86ISD::SUB) {
15183     Cond = ConvertCmpIfNecessary(Cond, DAG);
15184     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
15185
15186     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
15187         (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15188         (isNullConstant(Op1) || isNullConstant(Op2))) {
15189       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15190                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
15191                                 Cond);
15192       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
15193         return DAG.getNOT(DL, Res, Res.getValueType());
15194       return Res;
15195     }
15196   }
15197
15198   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15199   // widen the cmov and push the truncate through. This avoids introducing a new
15200   // branch during isel and doesn't add any extensions.
15201   if (Op.getValueType() == MVT::i8 &&
15202       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15203     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15204     if (T1.getValueType() == T2.getValueType() &&
15205         // Blacklist CopyFromReg to avoid partial register stalls.
15206         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15207       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15208       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15209       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15210     }
15211   }
15212
15213   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15214   // condition is true.
15215   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15216   SDValue Ops[] = { Op2, Op1, CC, Cond };
15217   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15218 }
15219
15220 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
15221                                        const X86Subtarget *Subtarget,
15222                                        SelectionDAG &DAG) {
15223   MVT VT = Op->getSimpleValueType(0);
15224   SDValue In = Op->getOperand(0);
15225   MVT InVT = In.getSimpleValueType();
15226   MVT VTElt = VT.getVectorElementType();
15227   MVT InVTElt = InVT.getVectorElementType();
15228   SDLoc dl(Op);
15229
15230   // SKX processor
15231   if ((InVTElt == MVT::i1) &&
15232       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15233         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15234
15235        ((Subtarget->hasBWI() && VT.is512BitVector() &&
15236         VTElt.getSizeInBits() <= 16)) ||
15237
15238        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15239         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15240
15241        ((Subtarget->hasDQI() && VT.is512BitVector() &&
15242         VTElt.getSizeInBits() >= 32))))
15243     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15244
15245   unsigned int NumElts = VT.getVectorNumElements();
15246
15247   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
15248     return SDValue();
15249
15250   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
15251     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
15252       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
15253     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15254   }
15255
15256   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15257   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
15258   SDValue NegOne =
15259    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
15260                    ExtVT);
15261   SDValue Zero =
15262    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
15263
15264   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
15265   if (VT.is512BitVector())
15266     return V;
15267   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
15268 }
15269
15270 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
15271                                              const X86Subtarget *Subtarget,
15272                                              SelectionDAG &DAG) {
15273   SDValue In = Op->getOperand(0);
15274   MVT VT = Op->getSimpleValueType(0);
15275   MVT InVT = In.getSimpleValueType();
15276   assert(VT.getSizeInBits() == InVT.getSizeInBits());
15277
15278   MVT InSVT = InVT.getVectorElementType();
15279   assert(VT.getVectorElementType().getSizeInBits() > InSVT.getSizeInBits());
15280
15281   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
15282     return SDValue();
15283   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
15284     return SDValue();
15285
15286   SDLoc dl(Op);
15287
15288   // SSE41 targets can use the pmovsx* instructions directly.
15289   if (Subtarget->hasSSE41())
15290     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15291
15292   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
15293   SDValue Curr = In;
15294   MVT CurrVT = InVT;
15295
15296   // As SRAI is only available on i16/i32 types, we expand only up to i32
15297   // and handle i64 separately.
15298   while (CurrVT != VT && CurrVT.getVectorElementType() != MVT::i32) {
15299     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
15300     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
15301     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
15302     Curr = DAG.getBitcast(CurrVT, Curr);
15303   }
15304
15305   SDValue SignExt = Curr;
15306   if (CurrVT != InVT) {
15307     unsigned SignExtShift =
15308         CurrVT.getVectorElementType().getSizeInBits() - InSVT.getSizeInBits();
15309     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15310                           DAG.getConstant(SignExtShift, dl, MVT::i8));
15311   }
15312
15313   if (CurrVT == VT)
15314     return SignExt;
15315
15316   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
15317     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15318                                DAG.getConstant(31, dl, MVT::i8));
15319     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
15320     return DAG.getBitcast(VT, Ext);
15321   }
15322
15323   return SDValue();
15324 }
15325
15326 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15327                                 SelectionDAG &DAG) {
15328   MVT VT = Op->getSimpleValueType(0);
15329   SDValue In = Op->getOperand(0);
15330   MVT InVT = In.getSimpleValueType();
15331   SDLoc dl(Op);
15332
15333   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15334     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15335
15336   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15337       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15338       (VT != MVT::v16i16 || InVT != MVT::v16i8))
15339     return SDValue();
15340
15341   if (Subtarget->hasInt256())
15342     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15343
15344   // Optimize vectors in AVX mode
15345   // Sign extend  v8i16 to v8i32 and
15346   //              v4i32 to v4i64
15347   //
15348   // Divide input vector into two parts
15349   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15350   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15351   // concat the vectors to original VT
15352
15353   unsigned NumElems = InVT.getVectorNumElements();
15354   SDValue Undef = DAG.getUNDEF(InVT);
15355
15356   SmallVector<int,8> ShufMask1(NumElems, -1);
15357   for (unsigned i = 0; i != NumElems/2; ++i)
15358     ShufMask1[i] = i;
15359
15360   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15361
15362   SmallVector<int,8> ShufMask2(NumElems, -1);
15363   for (unsigned i = 0; i != NumElems/2; ++i)
15364     ShufMask2[i] = i + NumElems/2;
15365
15366   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15367
15368   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
15369                                 VT.getVectorNumElements()/2);
15370
15371   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15372   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15373
15374   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15375 }
15376
15377 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15378 // may emit an illegal shuffle but the expansion is still better than scalar
15379 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15380 // we'll emit a shuffle and a arithmetic shift.
15381 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15382 // TODO: It is possible to support ZExt by zeroing the undef values during
15383 // the shuffle phase or after the shuffle.
15384 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15385                                  SelectionDAG &DAG) {
15386   MVT RegVT = Op.getSimpleValueType();
15387   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15388   assert(RegVT.isInteger() &&
15389          "We only custom lower integer vector sext loads.");
15390
15391   // Nothing useful we can do without SSE2 shuffles.
15392   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15393
15394   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15395   SDLoc dl(Ld);
15396   EVT MemVT = Ld->getMemoryVT();
15397   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15398   unsigned RegSz = RegVT.getSizeInBits();
15399
15400   ISD::LoadExtType Ext = Ld->getExtensionType();
15401
15402   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15403          && "Only anyext and sext are currently implemented.");
15404   assert(MemVT != RegVT && "Cannot extend to the same type");
15405   assert(MemVT.isVector() && "Must load a vector from memory");
15406
15407   unsigned NumElems = RegVT.getVectorNumElements();
15408   unsigned MemSz = MemVT.getSizeInBits();
15409   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15410
15411   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15412     // The only way in which we have a legal 256-bit vector result but not the
15413     // integer 256-bit operations needed to directly lower a sextload is if we
15414     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15415     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15416     // correctly legalized. We do this late to allow the canonical form of
15417     // sextload to persist throughout the rest of the DAG combiner -- it wants
15418     // to fold together any extensions it can, and so will fuse a sign_extend
15419     // of an sextload into a sextload targeting a wider value.
15420     SDValue Load;
15421     if (MemSz == 128) {
15422       // Just switch this to a normal load.
15423       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15424                                        "it must be a legal 128-bit vector "
15425                                        "type!");
15426       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15427                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15428                   Ld->isInvariant(), Ld->getAlignment());
15429     } else {
15430       assert(MemSz < 128 &&
15431              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15432       // Do an sext load to a 128-bit vector type. We want to use the same
15433       // number of elements, but elements half as wide. This will end up being
15434       // recursively lowered by this routine, but will succeed as we definitely
15435       // have all the necessary features if we're using AVX1.
15436       EVT HalfEltVT =
15437           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15438       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15439       Load =
15440           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15441                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15442                          Ld->isNonTemporal(), Ld->isInvariant(),
15443                          Ld->getAlignment());
15444     }
15445
15446     // Replace chain users with the new chain.
15447     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15448     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15449
15450     // Finally, do a normal sign-extend to the desired register.
15451     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15452   }
15453
15454   // All sizes must be a power of two.
15455   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15456          "Non-power-of-two elements are not custom lowered!");
15457
15458   // Attempt to load the original value using scalar loads.
15459   // Find the largest scalar type that divides the total loaded size.
15460   MVT SclrLoadTy = MVT::i8;
15461   for (MVT Tp : MVT::integer_valuetypes()) {
15462     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15463       SclrLoadTy = Tp;
15464     }
15465   }
15466
15467   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15468   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15469       (64 <= MemSz))
15470     SclrLoadTy = MVT::f64;
15471
15472   // Calculate the number of scalar loads that we need to perform
15473   // in order to load our vector from memory.
15474   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15475
15476   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15477          "Can only lower sext loads with a single scalar load!");
15478
15479   unsigned loadRegZize = RegSz;
15480   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15481     loadRegZize = 128;
15482
15483   // Represent our vector as a sequence of elements which are the
15484   // largest scalar that we can load.
15485   EVT LoadUnitVecVT = EVT::getVectorVT(
15486       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15487
15488   // Represent the data using the same element type that is stored in
15489   // memory. In practice, we ''widen'' MemVT.
15490   EVT WideVecVT =
15491       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15492                        loadRegZize / MemVT.getScalarSizeInBits());
15493
15494   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15495          "Invalid vector type");
15496
15497   // We can't shuffle using an illegal type.
15498   assert(TLI.isTypeLegal(WideVecVT) &&
15499          "We only lower types that form legal widened vector types");
15500
15501   SmallVector<SDValue, 8> Chains;
15502   SDValue Ptr = Ld->getBasePtr();
15503   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15504                                       TLI.getPointerTy(DAG.getDataLayout()));
15505   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15506
15507   for (unsigned i = 0; i < NumLoads; ++i) {
15508     // Perform a single load.
15509     SDValue ScalarLoad =
15510         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15511                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15512                     Ld->getAlignment());
15513     Chains.push_back(ScalarLoad.getValue(1));
15514     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15515     // another round of DAGCombining.
15516     if (i == 0)
15517       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15518     else
15519       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15520                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
15521
15522     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15523   }
15524
15525   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15526
15527   // Bitcast the loaded value to a vector of the original element type, in
15528   // the size of the target vector type.
15529   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15530   unsigned SizeRatio = RegSz / MemSz;
15531
15532   if (Ext == ISD::SEXTLOAD) {
15533     // If we have SSE4.1, we can directly emit a VSEXT node.
15534     if (Subtarget->hasSSE41()) {
15535       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15536       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15537       return Sext;
15538     }
15539
15540     // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15541     // lanes.
15542     assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15543            "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15544
15545     SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15546     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15547     return Shuff;
15548   }
15549
15550   // Redistribute the loaded elements into the different locations.
15551   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15552   for (unsigned i = 0; i != NumElems; ++i)
15553     ShuffleVec[i * SizeRatio] = i;
15554
15555   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15556                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15557
15558   // Bitcast to the requested type.
15559   Shuff = DAG.getBitcast(RegVT, Shuff);
15560   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15561   return Shuff;
15562 }
15563
15564 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15565 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15566 // from the AND / OR.
15567 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15568   Opc = Op.getOpcode();
15569   if (Opc != ISD::OR && Opc != ISD::AND)
15570     return false;
15571   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15572           Op.getOperand(0).hasOneUse() &&
15573           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15574           Op.getOperand(1).hasOneUse());
15575 }
15576
15577 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15578 // 1 and that the SETCC node has a single use.
15579 static bool isXor1OfSetCC(SDValue Op) {
15580   if (Op.getOpcode() != ISD::XOR)
15581     return false;
15582   if (isOneConstant(Op.getOperand(1)))
15583     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15584            Op.getOperand(0).hasOneUse();
15585   return false;
15586 }
15587
15588 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15589   bool addTest = true;
15590   SDValue Chain = Op.getOperand(0);
15591   SDValue Cond  = Op.getOperand(1);
15592   SDValue Dest  = Op.getOperand(2);
15593   SDLoc dl(Op);
15594   SDValue CC;
15595   bool Inverted = false;
15596
15597   if (Cond.getOpcode() == ISD::SETCC) {
15598     // Check for setcc([su]{add,sub,mul}o == 0).
15599     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15600         isNullConstant(Cond.getOperand(1)) &&
15601         Cond.getOperand(0).getResNo() == 1 &&
15602         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15603          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15604          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15605          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15606          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15607          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15608       Inverted = true;
15609       Cond = Cond.getOperand(0);
15610     } else {
15611       SDValue NewCond = LowerSETCC(Cond, DAG);
15612       if (NewCond.getNode())
15613         Cond = NewCond;
15614     }
15615   }
15616 #if 0
15617   // FIXME: LowerXALUO doesn't handle these!!
15618   else if (Cond.getOpcode() == X86ISD::ADD  ||
15619            Cond.getOpcode() == X86ISD::SUB  ||
15620            Cond.getOpcode() == X86ISD::SMUL ||
15621            Cond.getOpcode() == X86ISD::UMUL)
15622     Cond = LowerXALUO(Cond, DAG);
15623 #endif
15624
15625   // Look pass (and (setcc_carry (cmp ...)), 1).
15626   if (Cond.getOpcode() == ISD::AND &&
15627       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15628       isOneConstant(Cond.getOperand(1)))
15629     Cond = Cond.getOperand(0);
15630
15631   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15632   // setting operand in place of the X86ISD::SETCC.
15633   unsigned CondOpcode = Cond.getOpcode();
15634   if (CondOpcode == X86ISD::SETCC ||
15635       CondOpcode == X86ISD::SETCC_CARRY) {
15636     CC = Cond.getOperand(0);
15637
15638     SDValue Cmp = Cond.getOperand(1);
15639     unsigned Opc = Cmp.getOpcode();
15640     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15641     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15642       Cond = Cmp;
15643       addTest = false;
15644     } else {
15645       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15646       default: break;
15647       case X86::COND_O:
15648       case X86::COND_B:
15649         // These can only come from an arithmetic instruction with overflow,
15650         // e.g. SADDO, UADDO.
15651         Cond = Cond.getNode()->getOperand(1);
15652         addTest = false;
15653         break;
15654       }
15655     }
15656   }
15657   CondOpcode = Cond.getOpcode();
15658   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15659       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15660       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15661        Cond.getOperand(0).getValueType() != MVT::i8)) {
15662     SDValue LHS = Cond.getOperand(0);
15663     SDValue RHS = Cond.getOperand(1);
15664     unsigned X86Opcode;
15665     unsigned X86Cond;
15666     SDVTList VTs;
15667     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15668     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15669     // X86ISD::INC).
15670     switch (CondOpcode) {
15671     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15672     case ISD::SADDO:
15673       if (isOneConstant(RHS)) {
15674           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15675           break;
15676         }
15677       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15678     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15679     case ISD::SSUBO:
15680       if (isOneConstant(RHS)) {
15681           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15682           break;
15683         }
15684       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15685     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15686     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15687     default: llvm_unreachable("unexpected overflowing operator");
15688     }
15689     if (Inverted)
15690       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15691     if (CondOpcode == ISD::UMULO)
15692       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15693                           MVT::i32);
15694     else
15695       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15696
15697     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15698
15699     if (CondOpcode == ISD::UMULO)
15700       Cond = X86Op.getValue(2);
15701     else
15702       Cond = X86Op.getValue(1);
15703
15704     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15705     addTest = false;
15706   } else {
15707     unsigned CondOpc;
15708     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15709       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15710       if (CondOpc == ISD::OR) {
15711         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15712         // two branches instead of an explicit OR instruction with a
15713         // separate test.
15714         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15715             isX86LogicalCmp(Cmp)) {
15716           CC = Cond.getOperand(0).getOperand(0);
15717           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15718                               Chain, Dest, CC, Cmp);
15719           CC = Cond.getOperand(1).getOperand(0);
15720           Cond = Cmp;
15721           addTest = false;
15722         }
15723       } else { // ISD::AND
15724         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15725         // two branches instead of an explicit AND instruction with a
15726         // separate test. However, we only do this if this block doesn't
15727         // have a fall-through edge, because this requires an explicit
15728         // jmp when the condition is false.
15729         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15730             isX86LogicalCmp(Cmp) &&
15731             Op.getNode()->hasOneUse()) {
15732           X86::CondCode CCode =
15733             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15734           CCode = X86::GetOppositeBranchCondition(CCode);
15735           CC = DAG.getConstant(CCode, dl, MVT::i8);
15736           SDNode *User = *Op.getNode()->use_begin();
15737           // Look for an unconditional branch following this conditional branch.
15738           // We need this because we need to reverse the successors in order
15739           // to implement FCMP_OEQ.
15740           if (User->getOpcode() == ISD::BR) {
15741             SDValue FalseBB = User->getOperand(1);
15742             SDNode *NewBR =
15743               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15744             assert(NewBR == User);
15745             (void)NewBR;
15746             Dest = FalseBB;
15747
15748             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15749                                 Chain, Dest, CC, Cmp);
15750             X86::CondCode CCode =
15751               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15752             CCode = X86::GetOppositeBranchCondition(CCode);
15753             CC = DAG.getConstant(CCode, dl, MVT::i8);
15754             Cond = Cmp;
15755             addTest = false;
15756           }
15757         }
15758       }
15759     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15760       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15761       // It should be transformed during dag combiner except when the condition
15762       // is set by a arithmetics with overflow node.
15763       X86::CondCode CCode =
15764         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15765       CCode = X86::GetOppositeBranchCondition(CCode);
15766       CC = DAG.getConstant(CCode, dl, MVT::i8);
15767       Cond = Cond.getOperand(0).getOperand(1);
15768       addTest = false;
15769     } else if (Cond.getOpcode() == ISD::SETCC &&
15770                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15771       // For FCMP_OEQ, we can emit
15772       // two branches instead of an explicit AND instruction with a
15773       // separate test. However, we only do this if this block doesn't
15774       // have a fall-through edge, because this requires an explicit
15775       // jmp when the condition is false.
15776       if (Op.getNode()->hasOneUse()) {
15777         SDNode *User = *Op.getNode()->use_begin();
15778         // Look for an unconditional branch following this conditional branch.
15779         // We need this because we need to reverse the successors in order
15780         // to implement FCMP_OEQ.
15781         if (User->getOpcode() == ISD::BR) {
15782           SDValue FalseBB = User->getOperand(1);
15783           SDNode *NewBR =
15784             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15785           assert(NewBR == User);
15786           (void)NewBR;
15787           Dest = FalseBB;
15788
15789           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15790                                     Cond.getOperand(0), Cond.getOperand(1));
15791           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15792           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15793           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15794                               Chain, Dest, CC, Cmp);
15795           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15796           Cond = Cmp;
15797           addTest = false;
15798         }
15799       }
15800     } else if (Cond.getOpcode() == ISD::SETCC &&
15801                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15802       // For FCMP_UNE, we can emit
15803       // two branches instead of an explicit AND instruction with a
15804       // separate test. However, we only do this if this block doesn't
15805       // have a fall-through edge, because this requires an explicit
15806       // jmp when the condition is false.
15807       if (Op.getNode()->hasOneUse()) {
15808         SDNode *User = *Op.getNode()->use_begin();
15809         // Look for an unconditional branch following this conditional branch.
15810         // We need this because we need to reverse the successors in order
15811         // to implement FCMP_UNE.
15812         if (User->getOpcode() == ISD::BR) {
15813           SDValue FalseBB = User->getOperand(1);
15814           SDNode *NewBR =
15815             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15816           assert(NewBR == User);
15817           (void)NewBR;
15818
15819           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15820                                     Cond.getOperand(0), Cond.getOperand(1));
15821           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15822           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15823           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15824                               Chain, Dest, CC, Cmp);
15825           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15826           Cond = Cmp;
15827           addTest = false;
15828           Dest = FalseBB;
15829         }
15830       }
15831     }
15832   }
15833
15834   if (addTest) {
15835     // Look pass the truncate if the high bits are known zero.
15836     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15837         Cond = Cond.getOperand(0);
15838
15839     // We know the result of AND is compared against zero. Try to match
15840     // it to BT.
15841     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15842       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG)) {
15843         CC = NewSetCC.getOperand(0);
15844         Cond = NewSetCC.getOperand(1);
15845         addTest = false;
15846       }
15847     }
15848   }
15849
15850   if (addTest) {
15851     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15852     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15853     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15854   }
15855   Cond = ConvertCmpIfNecessary(Cond, DAG);
15856   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15857                      Chain, Dest, CC, Cond);
15858 }
15859
15860 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15861 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15862 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15863 // that the guard pages used by the OS virtual memory manager are allocated in
15864 // correct sequence.
15865 SDValue
15866 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15867                                            SelectionDAG &DAG) const {
15868   MachineFunction &MF = DAG.getMachineFunction();
15869   bool SplitStack = MF.shouldSplitStack();
15870   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15871                SplitStack;
15872   SDLoc dl(Op);
15873
15874   // Get the inputs.
15875   SDNode *Node = Op.getNode();
15876   SDValue Chain = Op.getOperand(0);
15877   SDValue Size  = Op.getOperand(1);
15878   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15879   EVT VT = Node->getValueType(0);
15880
15881   // Chain the dynamic stack allocation so that it doesn't modify the stack
15882   // pointer when other instructions are using the stack.
15883   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true), dl);
15884
15885   bool Is64Bit = Subtarget->is64Bit();
15886   MVT SPTy = getPointerTy(DAG.getDataLayout());
15887
15888   SDValue Result;
15889   if (!Lower) {
15890     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15891     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15892     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15893                     " not tell us which reg is the stack pointer!");
15894     EVT VT = Node->getValueType(0);
15895     SDValue Tmp3 = Node->getOperand(2);
15896
15897     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15898     Chain = SP.getValue(1);
15899     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15900     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15901     unsigned StackAlign = TFI.getStackAlignment();
15902     Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15903     if (Align > StackAlign)
15904       Result = DAG.getNode(ISD::AND, dl, VT, Result,
15905                          DAG.getConstant(-(uint64_t)Align, dl, VT));
15906     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
15907   } else if (SplitStack) {
15908     MachineRegisterInfo &MRI = MF.getRegInfo();
15909
15910     if (Is64Bit) {
15911       // The 64 bit implementation of segmented stacks needs to clobber both r10
15912       // r11. This makes it impossible to use it along with nested parameters.
15913       const Function *F = MF.getFunction();
15914
15915       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15916            I != E; ++I)
15917         if (I->hasNestAttr())
15918           report_fatal_error("Cannot use segmented stacks with functions that "
15919                              "have nested arguments.");
15920     }
15921
15922     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15923     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15924     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15925     Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15926                                 DAG.getRegister(Vreg, SPTy));
15927   } else {
15928     SDValue Flag;
15929     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15930
15931     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15932     Flag = Chain.getValue(1);
15933     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15934
15935     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15936
15937     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15938     unsigned SPReg = RegInfo->getStackRegister();
15939     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15940     Chain = SP.getValue(1);
15941
15942     if (Align) {
15943       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15944                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15945       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15946     }
15947
15948     Result = SP;
15949   }
15950
15951   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15952                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
15953
15954   SDValue Ops[2] = {Result, Chain};
15955   return DAG.getMergeValues(Ops, dl);
15956 }
15957
15958 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15959   MachineFunction &MF = DAG.getMachineFunction();
15960   auto PtrVT = getPointerTy(MF.getDataLayout());
15961   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15962
15963   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15964   SDLoc DL(Op);
15965
15966   if (!Subtarget->is64Bit() ||
15967       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15968     // vastart just stores the address of the VarArgsFrameIndex slot into the
15969     // memory location argument.
15970     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15971     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15972                         MachinePointerInfo(SV), false, false, 0);
15973   }
15974
15975   // __va_list_tag:
15976   //   gp_offset         (0 - 6 * 8)
15977   //   fp_offset         (48 - 48 + 8 * 16)
15978   //   overflow_arg_area (point to parameters coming in memory).
15979   //   reg_save_area
15980   SmallVector<SDValue, 8> MemOps;
15981   SDValue FIN = Op.getOperand(1);
15982   // Store gp_offset
15983   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15984                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15985                                                DL, MVT::i32),
15986                                FIN, MachinePointerInfo(SV), false, false, 0);
15987   MemOps.push_back(Store);
15988
15989   // Store fp_offset
15990   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15991   Store = DAG.getStore(Op.getOperand(0), DL,
15992                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15993                                        MVT::i32),
15994                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15995   MemOps.push_back(Store);
15996
15997   // Store ptr to overflow_arg_area
15998   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15999   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
16000   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
16001                        MachinePointerInfo(SV, 8),
16002                        false, false, 0);
16003   MemOps.push_back(Store);
16004
16005   // Store ptr to reg_save_area.
16006   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
16007       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
16008   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
16009   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
16010       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
16011   MemOps.push_back(Store);
16012   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
16013 }
16014
16015 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
16016   assert(Subtarget->is64Bit() &&
16017          "LowerVAARG only handles 64-bit va_arg!");
16018   assert(Op.getNode()->getNumOperands() == 4);
16019
16020   MachineFunction &MF = DAG.getMachineFunction();
16021   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
16022     // The Win64 ABI uses char* instead of a structure.
16023     return DAG.expandVAArg(Op.getNode());
16024
16025   SDValue Chain = Op.getOperand(0);
16026   SDValue SrcPtr = Op.getOperand(1);
16027   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16028   unsigned Align = Op.getConstantOperandVal(3);
16029   SDLoc dl(Op);
16030
16031   EVT ArgVT = Op.getNode()->getValueType(0);
16032   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16033   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
16034   uint8_t ArgMode;
16035
16036   // Decide which area this value should be read from.
16037   // TODO: Implement the AMD64 ABI in its entirety. This simple
16038   // selection mechanism works only for the basic types.
16039   if (ArgVT == MVT::f80) {
16040     llvm_unreachable("va_arg for f80 not yet implemented");
16041   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
16042     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
16043   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
16044     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
16045   } else {
16046     llvm_unreachable("Unhandled argument type in LowerVAARG");
16047   }
16048
16049   if (ArgMode == 2) {
16050     // Sanity Check: Make sure using fp_offset makes sense.
16051     assert(!Subtarget->useSoftFloat() &&
16052            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
16053            Subtarget->hasSSE1());
16054   }
16055
16056   // Insert VAARG_64 node into the DAG
16057   // VAARG_64 returns two values: Variable Argument Address, Chain
16058   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
16059                        DAG.getConstant(ArgMode, dl, MVT::i8),
16060                        DAG.getConstant(Align, dl, MVT::i32)};
16061   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
16062   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
16063                                           VTs, InstOps, MVT::i64,
16064                                           MachinePointerInfo(SV),
16065                                           /*Align=*/0,
16066                                           /*Volatile=*/false,
16067                                           /*ReadMem=*/true,
16068                                           /*WriteMem=*/true);
16069   Chain = VAARG.getValue(1);
16070
16071   // Load the next argument and return it
16072   return DAG.getLoad(ArgVT, dl,
16073                      Chain,
16074                      VAARG,
16075                      MachinePointerInfo(),
16076                      false, false, false, 0);
16077 }
16078
16079 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
16080                            SelectionDAG &DAG) {
16081   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
16082   // where a va_list is still an i8*.
16083   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
16084   if (Subtarget->isCallingConvWin64(
16085         DAG.getMachineFunction().getFunction()->getCallingConv()))
16086     // Probably a Win64 va_copy.
16087     return DAG.expandVACopy(Op.getNode());
16088
16089   SDValue Chain = Op.getOperand(0);
16090   SDValue DstPtr = Op.getOperand(1);
16091   SDValue SrcPtr = Op.getOperand(2);
16092   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
16093   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16094   SDLoc DL(Op);
16095
16096   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
16097                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
16098                        false, false,
16099                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
16100 }
16101
16102 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
16103 // amount is a constant. Takes immediate version of shift as input.
16104 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
16105                                           SDValue SrcOp, uint64_t ShiftAmt,
16106                                           SelectionDAG &DAG) {
16107   MVT ElementType = VT.getVectorElementType();
16108
16109   // Fold this packed shift into its first operand if ShiftAmt is 0.
16110   if (ShiftAmt == 0)
16111     return SrcOp;
16112
16113   // Check for ShiftAmt >= element width
16114   if (ShiftAmt >= ElementType.getSizeInBits()) {
16115     if (Opc == X86ISD::VSRAI)
16116       ShiftAmt = ElementType.getSizeInBits() - 1;
16117     else
16118       return DAG.getConstant(0, dl, VT);
16119   }
16120
16121   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
16122          && "Unknown target vector shift-by-constant node");
16123
16124   // Fold this packed vector shift into a build vector if SrcOp is a
16125   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
16126   if (VT == SrcOp.getSimpleValueType() &&
16127       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
16128     SmallVector<SDValue, 8> Elts;
16129     unsigned NumElts = SrcOp->getNumOperands();
16130     ConstantSDNode *ND;
16131
16132     switch(Opc) {
16133     default: llvm_unreachable(nullptr);
16134     case X86ISD::VSHLI:
16135       for (unsigned i=0; i!=NumElts; ++i) {
16136         SDValue CurrentOp = SrcOp->getOperand(i);
16137         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16138           Elts.push_back(CurrentOp);
16139           continue;
16140         }
16141         ND = cast<ConstantSDNode>(CurrentOp);
16142         const APInt &C = ND->getAPIntValue();
16143         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
16144       }
16145       break;
16146     case X86ISD::VSRLI:
16147       for (unsigned i=0; i!=NumElts; ++i) {
16148         SDValue CurrentOp = SrcOp->getOperand(i);
16149         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16150           Elts.push_back(CurrentOp);
16151           continue;
16152         }
16153         ND = cast<ConstantSDNode>(CurrentOp);
16154         const APInt &C = ND->getAPIntValue();
16155         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
16156       }
16157       break;
16158     case X86ISD::VSRAI:
16159       for (unsigned i=0; i!=NumElts; ++i) {
16160         SDValue CurrentOp = SrcOp->getOperand(i);
16161         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16162           Elts.push_back(CurrentOp);
16163           continue;
16164         }
16165         ND = cast<ConstantSDNode>(CurrentOp);
16166         const APInt &C = ND->getAPIntValue();
16167         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
16168       }
16169       break;
16170     }
16171
16172     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16173   }
16174
16175   return DAG.getNode(Opc, dl, VT, SrcOp,
16176                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
16177 }
16178
16179 // getTargetVShiftNode - Handle vector element shifts where the shift amount
16180 // may or may not be a constant. Takes immediate version of shift as input.
16181 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
16182                                    SDValue SrcOp, SDValue ShAmt,
16183                                    SelectionDAG &DAG) {
16184   MVT SVT = ShAmt.getSimpleValueType();
16185   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
16186
16187   // Catch shift-by-constant.
16188   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
16189     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
16190                                       CShAmt->getZExtValue(), DAG);
16191
16192   // Change opcode to non-immediate version
16193   switch (Opc) {
16194     default: llvm_unreachable("Unknown target vector shift node");
16195     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16196     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16197     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16198   }
16199
16200   const X86Subtarget &Subtarget =
16201       static_cast<const X86Subtarget &>(DAG.getSubtarget());
16202   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
16203       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
16204     // Let the shuffle legalizer expand this shift amount node.
16205     SDValue Op0 = ShAmt.getOperand(0);
16206     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
16207     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
16208   } else {
16209     // Need to build a vector containing shift amount.
16210     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
16211     SmallVector<SDValue, 4> ShOps;
16212     ShOps.push_back(ShAmt);
16213     if (SVT == MVT::i32) {
16214       ShOps.push_back(DAG.getConstant(0, dl, SVT));
16215       ShOps.push_back(DAG.getUNDEF(SVT));
16216     }
16217     ShOps.push_back(DAG.getUNDEF(SVT));
16218
16219     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
16220     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
16221   }
16222
16223   // The return type has to be a 128-bit type with the same element
16224   // type as the input type.
16225   MVT EltVT = VT.getVectorElementType();
16226   MVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16227
16228   ShAmt = DAG.getBitcast(ShVT, ShAmt);
16229   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16230 }
16231
16232 /// \brief Return Mask with the necessary casting or extending
16233 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
16234 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
16235                            const X86Subtarget *Subtarget,
16236                            SelectionDAG &DAG, SDLoc dl) {
16237
16238   if (MaskVT.bitsGT(Mask.getSimpleValueType())) {
16239     // Mask should be extended
16240     Mask = DAG.getNode(ISD::ANY_EXTEND, dl,
16241                        MVT::getIntegerVT(MaskVT.getSizeInBits()), Mask);
16242   }
16243
16244   if (Mask.getSimpleValueType() == MVT::i64 && Subtarget->is32Bit()) {
16245     if (MaskVT == MVT::v64i1) {
16246       assert(Subtarget->hasBWI() && "Expected AVX512BW target!");
16247       // In case 32bit mode, bitcast i64 is illegal, extend/split it.
16248       SDValue Lo, Hi;
16249       Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16250                           DAG.getConstant(0, dl, MVT::i32));
16251       Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16252                           DAG.getConstant(1, dl, MVT::i32));
16253
16254       Lo = DAG.getBitcast(MVT::v32i1, Lo);
16255       Hi = DAG.getBitcast(MVT::v32i1, Hi);
16256
16257       return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
16258     } else {
16259       // MaskVT require < 64bit. Truncate mask (should succeed in any case),
16260       // and bitcast.
16261       MVT TruncVT = MVT::getIntegerVT(MaskVT.getSizeInBits());
16262       return DAG.getBitcast(MaskVT,
16263                             DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Mask));
16264     }
16265
16266   } else {
16267     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16268                                      Mask.getSimpleValueType().getSizeInBits());
16269     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16270     // are extracted by EXTRACT_SUBVECTOR.
16271     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16272                        DAG.getBitcast(BitcastVT, Mask),
16273                        DAG.getIntPtrConstant(0, dl));
16274   }
16275 }
16276
16277 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16278 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16279 /// necessary casting or extending for \p Mask when lowering masking intrinsics
16280 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16281                   SDValue PreservedSrc,
16282                   const X86Subtarget *Subtarget,
16283                   SelectionDAG &DAG) {
16284   MVT VT = Op.getSimpleValueType();
16285   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16286   unsigned OpcodeSelect = ISD::VSELECT;
16287   SDLoc dl(Op);
16288
16289   if (isAllOnesConstant(Mask))
16290     return Op;
16291
16292   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16293
16294   switch (Op.getOpcode()) {
16295   default: break;
16296   case X86ISD::PCMPEQM:
16297   case X86ISD::PCMPGTM:
16298   case X86ISD::CMPM:
16299   case X86ISD::CMPMU:
16300     return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16301   case X86ISD::VFPCLASS:
16302     case X86ISD::VFPCLASSS:
16303     return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
16304   case X86ISD::VTRUNC:
16305   case X86ISD::VTRUNCS:
16306   case X86ISD::VTRUNCUS:
16307     // We can't use ISD::VSELECT here because it is not always "Legal"
16308     // for the destination type. For example vpmovqb require only AVX512
16309     // and vselect that can operate on byte element type require BWI
16310     OpcodeSelect = X86ISD::SELECT;
16311     break;
16312   }
16313   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16314     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16315   return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
16316 }
16317
16318 /// \brief Creates an SDNode for a predicated scalar operation.
16319 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
16320 /// The mask is coming as MVT::i8 and it should be truncated
16321 /// to MVT::i1 while lowering masking intrinsics.
16322 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
16323 /// "X86select" instead of "vselect". We just can't create the "vselect" node
16324 /// for a scalar instruction.
16325 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16326                                     SDValue PreservedSrc,
16327                                     const X86Subtarget *Subtarget,
16328                                     SelectionDAG &DAG) {
16329   if (isAllOnesConstant(Mask))
16330     return Op;
16331
16332   MVT VT = Op.getSimpleValueType();
16333   SDLoc dl(Op);
16334   // The mask should be of type MVT::i1
16335   SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16336
16337   if (Op.getOpcode() == X86ISD::FSETCC)
16338     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
16339   if (Op.getOpcode() == X86ISD::VFPCLASS ||
16340       Op.getOpcode() == X86ISD::VFPCLASSS)
16341     return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
16342
16343   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16344     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16345   return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16346 }
16347
16348 static int getSEHRegistrationNodeSize(const Function *Fn) {
16349   if (!Fn->hasPersonalityFn())
16350     report_fatal_error(
16351         "querying registration node size for function without personality");
16352   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
16353   // WinEHStatePass for the full struct definition.
16354   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
16355   case EHPersonality::MSVC_X86SEH: return 24;
16356   case EHPersonality::MSVC_CXX: return 16;
16357   default: break;
16358   }
16359   report_fatal_error(
16360       "can only recover FP for 32-bit MSVC EH personality functions");
16361 }
16362
16363 /// When the MSVC runtime transfers control to us, either to an outlined
16364 /// function or when returning to a parent frame after catching an exception, we
16365 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
16366 /// Here's the math:
16367 ///   RegNodeBase = EntryEBP - RegNodeSize
16368 ///   ParentFP = RegNodeBase - ParentFrameOffset
16369 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16370 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16371 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16372                                    SDValue EntryEBP) {
16373   MachineFunction &MF = DAG.getMachineFunction();
16374   SDLoc dl;
16375
16376   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16377   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16378
16379   // It's possible that the parent function no longer has a personality function
16380   // if the exceptional code was optimized away, in which case we just return
16381   // the incoming EBP.
16382   if (!Fn->hasPersonalityFn())
16383     return EntryEBP;
16384
16385   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16386   // registration, or the .set_setframe offset.
16387   MCSymbol *OffsetSym =
16388       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16389           GlobalValue::getRealLinkageName(Fn->getName()));
16390   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16391   SDValue ParentFrameOffset =
16392       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16393
16394   // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
16395   // prologue to RBP in the parent function.
16396   const X86Subtarget &Subtarget =
16397       static_cast<const X86Subtarget &>(DAG.getSubtarget());
16398   if (Subtarget.is64Bit())
16399     return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
16400
16401   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16402   // RegNodeBase = EntryEBP - RegNodeSize
16403   // ParentFP = RegNodeBase - ParentFrameOffset
16404   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16405                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
16406   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
16407 }
16408
16409 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16410                                        SelectionDAG &DAG) {
16411   SDLoc dl(Op);
16412   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16413   MVT VT = Op.getSimpleValueType();
16414   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16415   if (IntrData) {
16416     switch(IntrData->Type) {
16417     case INTR_TYPE_1OP:
16418       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16419     case INTR_TYPE_2OP:
16420       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16421         Op.getOperand(2));
16422     case INTR_TYPE_2OP_IMM8:
16423       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16424                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16425     case INTR_TYPE_3OP:
16426       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16427         Op.getOperand(2), Op.getOperand(3));
16428     case INTR_TYPE_4OP:
16429       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16430         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16431     case INTR_TYPE_1OP_MASK_RM: {
16432       SDValue Src = Op.getOperand(1);
16433       SDValue PassThru = Op.getOperand(2);
16434       SDValue Mask = Op.getOperand(3);
16435       SDValue RoundingMode;
16436       // We allways add rounding mode to the Node.
16437       // If the rounding mode is not specified, we add the
16438       // "current direction" mode.
16439       if (Op.getNumOperands() == 4)
16440         RoundingMode =
16441           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16442       else
16443         RoundingMode = Op.getOperand(4);
16444       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16445       if (IntrWithRoundingModeOpcode != 0)
16446         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16447             X86::STATIC_ROUNDING::CUR_DIRECTION)
16448           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16449                                       dl, Op.getValueType(), Src, RoundingMode),
16450                                       Mask, PassThru, Subtarget, DAG);
16451       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16452                                               RoundingMode),
16453                                   Mask, PassThru, Subtarget, DAG);
16454     }
16455     case INTR_TYPE_1OP_MASK: {
16456       SDValue Src = Op.getOperand(1);
16457       SDValue PassThru = Op.getOperand(2);
16458       SDValue Mask = Op.getOperand(3);
16459       // We add rounding mode to the Node when
16460       //   - RM Opcode is specified and
16461       //   - RM is not "current direction".
16462       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16463       if (IntrWithRoundingModeOpcode != 0) {
16464         SDValue Rnd = Op.getOperand(4);
16465         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16466         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16467           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16468                                       dl, Op.getValueType(),
16469                                       Src, Rnd),
16470                                       Mask, PassThru, Subtarget, DAG);
16471         }
16472       }
16473       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16474                                   Mask, PassThru, Subtarget, DAG);
16475     }
16476     case INTR_TYPE_SCALAR_MASK: {
16477       SDValue Src1 = Op.getOperand(1);
16478       SDValue Src2 = Op.getOperand(2);
16479       SDValue passThru = Op.getOperand(3);
16480       SDValue Mask = Op.getOperand(4);
16481       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16482                                   Mask, passThru, Subtarget, DAG);
16483     }
16484     case INTR_TYPE_SCALAR_MASK_RM: {
16485       SDValue Src1 = Op.getOperand(1);
16486       SDValue Src2 = Op.getOperand(2);
16487       SDValue Src0 = Op.getOperand(3);
16488       SDValue Mask = Op.getOperand(4);
16489       // There are 2 kinds of intrinsics in this group:
16490       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16491       // (2) With rounding mode and sae - 7 operands.
16492       if (Op.getNumOperands() == 6) {
16493         SDValue Sae  = Op.getOperand(5);
16494         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16495         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16496                                                 Sae),
16497                                     Mask, Src0, Subtarget, DAG);
16498       }
16499       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16500       SDValue RoundingMode  = Op.getOperand(5);
16501       SDValue Sae  = Op.getOperand(6);
16502       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16503                                               RoundingMode, Sae),
16504                                   Mask, Src0, Subtarget, DAG);
16505     }
16506     case INTR_TYPE_2OP_MASK:
16507     case INTR_TYPE_2OP_IMM8_MASK: {
16508       SDValue Src1 = Op.getOperand(1);
16509       SDValue Src2 = Op.getOperand(2);
16510       SDValue PassThru = Op.getOperand(3);
16511       SDValue Mask = Op.getOperand(4);
16512
16513       if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16514         Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16515
16516       // We specify 2 possible opcodes for intrinsics with rounding modes.
16517       // First, we check if the intrinsic may have non-default rounding mode,
16518       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16519       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16520       if (IntrWithRoundingModeOpcode != 0) {
16521         SDValue Rnd = Op.getOperand(5);
16522         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16523         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16524           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16525                                       dl, Op.getValueType(),
16526                                       Src1, Src2, Rnd),
16527                                       Mask, PassThru, Subtarget, DAG);
16528         }
16529       }
16530       // TODO: Intrinsics should have fast-math-flags to propagate.
16531       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16532                                   Mask, PassThru, Subtarget, DAG);
16533     }
16534     case INTR_TYPE_2OP_MASK_RM: {
16535       SDValue Src1 = Op.getOperand(1);
16536       SDValue Src2 = Op.getOperand(2);
16537       SDValue PassThru = Op.getOperand(3);
16538       SDValue Mask = Op.getOperand(4);
16539       // We specify 2 possible modes for intrinsics, with/without rounding
16540       // modes.
16541       // First, we check if the intrinsic have rounding mode (6 operands),
16542       // if not, we set rounding mode to "current".
16543       SDValue Rnd;
16544       if (Op.getNumOperands() == 6)
16545         Rnd = Op.getOperand(5);
16546       else
16547         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16548       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16549                                               Src1, Src2, Rnd),
16550                                   Mask, PassThru, Subtarget, DAG);
16551     }
16552     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16553       SDValue Src1 = Op.getOperand(1);
16554       SDValue Src2 = Op.getOperand(2);
16555       SDValue Src3 = Op.getOperand(3);
16556       SDValue PassThru = Op.getOperand(4);
16557       SDValue Mask = Op.getOperand(5);
16558       SDValue Sae  = Op.getOperand(6);
16559
16560       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16561                                               Src2, Src3, Sae),
16562                                   Mask, PassThru, Subtarget, DAG);
16563     }
16564     case INTR_TYPE_3OP_MASK_RM: {
16565       SDValue Src1 = Op.getOperand(1);
16566       SDValue Src2 = Op.getOperand(2);
16567       SDValue Imm = Op.getOperand(3);
16568       SDValue PassThru = Op.getOperand(4);
16569       SDValue Mask = Op.getOperand(5);
16570       // We specify 2 possible modes for intrinsics, with/without rounding
16571       // modes.
16572       // First, we check if the intrinsic have rounding mode (7 operands),
16573       // if not, we set rounding mode to "current".
16574       SDValue Rnd;
16575       if (Op.getNumOperands() == 7)
16576         Rnd = Op.getOperand(6);
16577       else
16578         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16579       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16580         Src1, Src2, Imm, Rnd),
16581         Mask, PassThru, Subtarget, DAG);
16582     }
16583     case INTR_TYPE_3OP_IMM8_MASK:
16584     case INTR_TYPE_3OP_MASK:
16585     case INSERT_SUBVEC: {
16586       SDValue Src1 = Op.getOperand(1);
16587       SDValue Src2 = Op.getOperand(2);
16588       SDValue Src3 = Op.getOperand(3);
16589       SDValue PassThru = Op.getOperand(4);
16590       SDValue Mask = Op.getOperand(5);
16591
16592       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16593         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16594       else if (IntrData->Type == INSERT_SUBVEC) {
16595         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16596         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16597         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16598         Imm *= Src2.getSimpleValueType().getVectorNumElements();
16599         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16600       }
16601
16602       // We specify 2 possible opcodes for intrinsics with rounding modes.
16603       // First, we check if the intrinsic may have non-default rounding mode,
16604       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16605       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16606       if (IntrWithRoundingModeOpcode != 0) {
16607         SDValue Rnd = Op.getOperand(6);
16608         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16609         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16610           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16611                                       dl, Op.getValueType(),
16612                                       Src1, Src2, Src3, Rnd),
16613                                       Mask, PassThru, Subtarget, DAG);
16614         }
16615       }
16616       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16617                                               Src1, Src2, Src3),
16618                                   Mask, PassThru, Subtarget, DAG);
16619     }
16620     case VPERM_3OP_MASKZ:
16621     case VPERM_3OP_MASK:{
16622       // Src2 is the PassThru
16623       SDValue Src1 = Op.getOperand(1);
16624       SDValue Src2 = Op.getOperand(2);
16625       SDValue Src3 = Op.getOperand(3);
16626       SDValue Mask = Op.getOperand(4);
16627       MVT VT = Op.getSimpleValueType();
16628       SDValue PassThru = SDValue();
16629
16630       // set PassThru element
16631       if (IntrData->Type == VPERM_3OP_MASKZ)
16632         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16633       else
16634         PassThru = DAG.getBitcast(VT, Src2);
16635
16636       // Swap Src1 and Src2 in the node creation
16637       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16638                                               dl, Op.getValueType(),
16639                                               Src2, Src1, Src3),
16640                                   Mask, PassThru, Subtarget, DAG);
16641     }
16642     case FMA_OP_MASK3:
16643     case FMA_OP_MASKZ:
16644     case FMA_OP_MASK: {
16645       SDValue Src1 = Op.getOperand(1);
16646       SDValue Src2 = Op.getOperand(2);
16647       SDValue Src3 = Op.getOperand(3);
16648       SDValue Mask = Op.getOperand(4);
16649       MVT VT = Op.getSimpleValueType();
16650       SDValue PassThru = SDValue();
16651
16652       // set PassThru element
16653       if (IntrData->Type == FMA_OP_MASKZ)
16654         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16655       else if (IntrData->Type == FMA_OP_MASK3)
16656         PassThru = Src3;
16657       else
16658         PassThru = Src1;
16659
16660       // We specify 2 possible opcodes for intrinsics with rounding modes.
16661       // First, we check if the intrinsic may have non-default rounding mode,
16662       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16663       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16664       if (IntrWithRoundingModeOpcode != 0) {
16665         SDValue Rnd = Op.getOperand(5);
16666         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16667             X86::STATIC_ROUNDING::CUR_DIRECTION)
16668           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16669                                                   dl, Op.getValueType(),
16670                                                   Src1, Src2, Src3, Rnd),
16671                                       Mask, PassThru, Subtarget, DAG);
16672       }
16673       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16674                                               dl, Op.getValueType(),
16675                                               Src1, Src2, Src3),
16676                                   Mask, PassThru, Subtarget, DAG);
16677     }
16678     case TERLOG_OP_MASK:
16679     case TERLOG_OP_MASKZ: {
16680       SDValue Src1 = Op.getOperand(1);
16681       SDValue Src2 = Op.getOperand(2);
16682       SDValue Src3 = Op.getOperand(3);
16683       SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16684       SDValue Mask = Op.getOperand(5);
16685       MVT VT = Op.getSimpleValueType();
16686       SDValue PassThru = Src1;
16687       // Set PassThru element.
16688       if (IntrData->Type == TERLOG_OP_MASKZ)
16689         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16690
16691       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16692                                               Src1, Src2, Src3, Src4),
16693                                   Mask, PassThru, Subtarget, DAG);
16694     }
16695     case FPCLASS: {
16696       // FPclass intrinsics with mask
16697        SDValue Src1 = Op.getOperand(1);
16698        MVT VT = Src1.getSimpleValueType();
16699        MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16700        SDValue Imm = Op.getOperand(2);
16701        SDValue Mask = Op.getOperand(3);
16702        MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16703                                      Mask.getSimpleValueType().getSizeInBits());
16704        SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16705        SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16706                                                  DAG.getTargetConstant(0, dl, MaskVT),
16707                                                  Subtarget, DAG);
16708        SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16709                                  DAG.getUNDEF(BitcastVT), FPclassMask,
16710                                  DAG.getIntPtrConstant(0, dl));
16711        return DAG.getBitcast(Op.getValueType(), Res);
16712     }
16713     case FPCLASSS: {
16714       SDValue Src1 = Op.getOperand(1);
16715       SDValue Imm = Op.getOperand(2);
16716       SDValue Mask = Op.getOperand(3);
16717       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16718       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16719         DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16720       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16721     }
16722     case CMP_MASK:
16723     case CMP_MASK_CC: {
16724       // Comparison intrinsics with masks.
16725       // Example of transformation:
16726       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16727       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16728       // (i8 (bitcast
16729       //   (v8i1 (insert_subvector undef,
16730       //           (v2i1 (and (PCMPEQM %a, %b),
16731       //                      (extract_subvector
16732       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16733       MVT VT = Op.getOperand(1).getSimpleValueType();
16734       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16735       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16736       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16737                                        Mask.getSimpleValueType().getSizeInBits());
16738       SDValue Cmp;
16739       if (IntrData->Type == CMP_MASK_CC) {
16740         SDValue CC = Op.getOperand(3);
16741         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16742         // We specify 2 possible opcodes for intrinsics with rounding modes.
16743         // First, we check if the intrinsic may have non-default rounding mode,
16744         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16745         if (IntrData->Opc1 != 0) {
16746           SDValue Rnd = Op.getOperand(5);
16747           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16748               X86::STATIC_ROUNDING::CUR_DIRECTION)
16749             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16750                               Op.getOperand(2), CC, Rnd);
16751         }
16752         //default rounding mode
16753         if(!Cmp.getNode())
16754             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16755                               Op.getOperand(2), CC);
16756
16757       } else {
16758         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16759         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16760                           Op.getOperand(2));
16761       }
16762       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16763                                              DAG.getTargetConstant(0, dl,
16764                                                                    MaskVT),
16765                                              Subtarget, DAG);
16766       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16767                                 DAG.getUNDEF(BitcastVT), CmpMask,
16768                                 DAG.getIntPtrConstant(0, dl));
16769       return DAG.getBitcast(Op.getValueType(), Res);
16770     }
16771     case CMP_MASK_SCALAR_CC: {
16772       SDValue Src1 = Op.getOperand(1);
16773       SDValue Src2 = Op.getOperand(2);
16774       SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16775       SDValue Mask = Op.getOperand(4);
16776
16777       SDValue Cmp;
16778       if (IntrData->Opc1 != 0) {
16779         SDValue Rnd = Op.getOperand(5);
16780         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16781             X86::STATIC_ROUNDING::CUR_DIRECTION)
16782           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16783       }
16784       //default rounding mode
16785       if(!Cmp.getNode())
16786         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16787
16788       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16789                                              DAG.getTargetConstant(0, dl,
16790                                                                    MVT::i1),
16791                                              Subtarget, DAG);
16792
16793       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16794                          DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16795                          DAG.getValueType(MVT::i1));
16796     }
16797     case COMI: { // Comparison intrinsics
16798       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16799       SDValue LHS = Op.getOperand(1);
16800       SDValue RHS = Op.getOperand(2);
16801       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16802       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16803       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16804       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16805                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16806       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16807     }
16808     case COMI_RM: { // Comparison intrinsics with Sae
16809       SDValue LHS = Op.getOperand(1);
16810       SDValue RHS = Op.getOperand(2);
16811       SDValue CC = Op.getOperand(3);
16812       SDValue Sae = Op.getOperand(4);
16813       auto ComiType = TranslateX86ConstCondToX86CC(CC);
16814       // choose between ordered and unordered (comi/ucomi)
16815       unsigned comiOp = std::get<0>(ComiType) ? IntrData->Opc0 : IntrData->Opc1;
16816       SDValue Cond;
16817       if (cast<ConstantSDNode>(Sae)->getZExtValue() !=
16818                                            X86::STATIC_ROUNDING::CUR_DIRECTION)
16819         Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS, Sae);
16820       else
16821         Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS);
16822       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16823         DAG.getConstant(std::get<1>(ComiType), dl, MVT::i8), Cond);
16824       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16825     }
16826     case VSHIFT:
16827       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16828                                  Op.getOperand(1), Op.getOperand(2), DAG);
16829     case VSHIFT_MASK:
16830       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16831                                                       Op.getSimpleValueType(),
16832                                                       Op.getOperand(1),
16833                                                       Op.getOperand(2), DAG),
16834                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16835                                   DAG);
16836     case COMPRESS_EXPAND_IN_REG: {
16837       SDValue Mask = Op.getOperand(3);
16838       SDValue DataToCompress = Op.getOperand(1);
16839       SDValue PassThru = Op.getOperand(2);
16840       if (isAllOnesConstant(Mask)) // return data as is
16841         return Op.getOperand(1);
16842
16843       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16844                                               DataToCompress),
16845                                   Mask, PassThru, Subtarget, DAG);
16846     }
16847     case BROADCASTM: {
16848       SDValue Mask = Op.getOperand(1);
16849       MVT MaskVT = MVT::getVectorVT(MVT::i1,
16850                                     Mask.getSimpleValueType().getSizeInBits());
16851       Mask = DAG.getBitcast(MaskVT, Mask);
16852       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Mask);
16853     }
16854     case BLEND: {
16855       SDValue Mask = Op.getOperand(3);
16856       MVT VT = Op.getSimpleValueType();
16857       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16858       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16859       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16860                          Op.getOperand(2));
16861     }
16862     case KUNPCK: {
16863       MVT VT = Op.getSimpleValueType();
16864       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits()/2);
16865
16866       SDValue Src1 = getMaskNode(Op.getOperand(1), MaskVT, Subtarget, DAG, dl);
16867       SDValue Src2 = getMaskNode(Op.getOperand(2), MaskVT, Subtarget, DAG, dl);
16868       // Arguments should be swapped.
16869       SDValue Res = DAG.getNode(IntrData->Opc0, dl,
16870                                 MVT::getVectorVT(MVT::i1, VT.getSizeInBits()),
16871                                 Src2, Src1);
16872       return DAG.getBitcast(VT, Res);
16873     }
16874     case CONVERT_TO_MASK: {
16875       MVT SrcVT = Op.getOperand(1).getSimpleValueType();
16876       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
16877       MVT BitcastVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits());
16878
16879       SDValue CvtMask = DAG.getNode(IntrData->Opc0, dl, MaskVT,
16880                                     Op.getOperand(1));
16881       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16882                                 DAG.getUNDEF(BitcastVT), CvtMask,
16883                                 DAG.getIntPtrConstant(0, dl));
16884       return DAG.getBitcast(Op.getValueType(), Res);
16885     }
16886     case CONVERT_MASK_TO_VEC: {
16887       SDValue Mask = Op.getOperand(1);
16888       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16889       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16890       return DAG.getNode(IntrData->Opc0, dl, VT, VMask);
16891     }
16892     case BRCST_SUBVEC_TO_VEC: {
16893       SDValue Src = Op.getOperand(1);
16894       SDValue Passthru = Op.getOperand(2);
16895       SDValue Mask = Op.getOperand(3);
16896       EVT resVT = Passthru.getValueType();
16897       SDValue subVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, resVT,
16898                                        DAG.getUNDEF(resVT), Src,
16899                                        DAG.getIntPtrConstant(0, dl));
16900       SDValue immVal;
16901       if (Src.getSimpleValueType().is256BitVector() && resVT.is512BitVector())
16902         immVal = DAG.getConstant(0x44, dl, MVT::i8);
16903       else
16904         immVal = DAG.getConstant(0, dl, MVT::i8);
16905       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16906                                               subVec, subVec, immVal),
16907                                   Mask, Passthru, Subtarget, DAG);
16908     }
16909     default:
16910       break;
16911     }
16912   }
16913
16914   switch (IntNo) {
16915   default: return SDValue();    // Don't custom lower most intrinsics.
16916
16917   case Intrinsic::x86_avx2_permd:
16918   case Intrinsic::x86_avx2_permps:
16919     // Operands intentionally swapped. Mask is last operand to intrinsic,
16920     // but second operand for node/instruction.
16921     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16922                        Op.getOperand(2), Op.getOperand(1));
16923
16924   // ptest and testp intrinsics. The intrinsic these come from are designed to
16925   // return an integer value, not just an instruction so lower it to the ptest
16926   // or testp pattern and a setcc for the result.
16927   case Intrinsic::x86_sse41_ptestz:
16928   case Intrinsic::x86_sse41_ptestc:
16929   case Intrinsic::x86_sse41_ptestnzc:
16930   case Intrinsic::x86_avx_ptestz_256:
16931   case Intrinsic::x86_avx_ptestc_256:
16932   case Intrinsic::x86_avx_ptestnzc_256:
16933   case Intrinsic::x86_avx_vtestz_ps:
16934   case Intrinsic::x86_avx_vtestc_ps:
16935   case Intrinsic::x86_avx_vtestnzc_ps:
16936   case Intrinsic::x86_avx_vtestz_pd:
16937   case Intrinsic::x86_avx_vtestc_pd:
16938   case Intrinsic::x86_avx_vtestnzc_pd:
16939   case Intrinsic::x86_avx_vtestz_ps_256:
16940   case Intrinsic::x86_avx_vtestc_ps_256:
16941   case Intrinsic::x86_avx_vtestnzc_ps_256:
16942   case Intrinsic::x86_avx_vtestz_pd_256:
16943   case Intrinsic::x86_avx_vtestc_pd_256:
16944   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16945     bool IsTestPacked = false;
16946     unsigned X86CC;
16947     switch (IntNo) {
16948     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16949     case Intrinsic::x86_avx_vtestz_ps:
16950     case Intrinsic::x86_avx_vtestz_pd:
16951     case Intrinsic::x86_avx_vtestz_ps_256:
16952     case Intrinsic::x86_avx_vtestz_pd_256:
16953       IsTestPacked = true; // Fallthrough
16954     case Intrinsic::x86_sse41_ptestz:
16955     case Intrinsic::x86_avx_ptestz_256:
16956       // ZF = 1
16957       X86CC = X86::COND_E;
16958       break;
16959     case Intrinsic::x86_avx_vtestc_ps:
16960     case Intrinsic::x86_avx_vtestc_pd:
16961     case Intrinsic::x86_avx_vtestc_ps_256:
16962     case Intrinsic::x86_avx_vtestc_pd_256:
16963       IsTestPacked = true; // Fallthrough
16964     case Intrinsic::x86_sse41_ptestc:
16965     case Intrinsic::x86_avx_ptestc_256:
16966       // CF = 1
16967       X86CC = X86::COND_B;
16968       break;
16969     case Intrinsic::x86_avx_vtestnzc_ps:
16970     case Intrinsic::x86_avx_vtestnzc_pd:
16971     case Intrinsic::x86_avx_vtestnzc_ps_256:
16972     case Intrinsic::x86_avx_vtestnzc_pd_256:
16973       IsTestPacked = true; // Fallthrough
16974     case Intrinsic::x86_sse41_ptestnzc:
16975     case Intrinsic::x86_avx_ptestnzc_256:
16976       // ZF and CF = 0
16977       X86CC = X86::COND_A;
16978       break;
16979     }
16980
16981     SDValue LHS = Op.getOperand(1);
16982     SDValue RHS = Op.getOperand(2);
16983     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16984     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16985     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16986     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16987     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16988   }
16989   case Intrinsic::x86_avx512_kortestz_w:
16990   case Intrinsic::x86_avx512_kortestc_w: {
16991     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16992     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16993     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16994     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16995     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16996     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16997     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16998   }
16999
17000   case Intrinsic::x86_sse42_pcmpistria128:
17001   case Intrinsic::x86_sse42_pcmpestria128:
17002   case Intrinsic::x86_sse42_pcmpistric128:
17003   case Intrinsic::x86_sse42_pcmpestric128:
17004   case Intrinsic::x86_sse42_pcmpistrio128:
17005   case Intrinsic::x86_sse42_pcmpestrio128:
17006   case Intrinsic::x86_sse42_pcmpistris128:
17007   case Intrinsic::x86_sse42_pcmpestris128:
17008   case Intrinsic::x86_sse42_pcmpistriz128:
17009   case Intrinsic::x86_sse42_pcmpestriz128: {
17010     unsigned Opcode;
17011     unsigned X86CC;
17012     switch (IntNo) {
17013     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17014     case Intrinsic::x86_sse42_pcmpistria128:
17015       Opcode = X86ISD::PCMPISTRI;
17016       X86CC = X86::COND_A;
17017       break;
17018     case Intrinsic::x86_sse42_pcmpestria128:
17019       Opcode = X86ISD::PCMPESTRI;
17020       X86CC = X86::COND_A;
17021       break;
17022     case Intrinsic::x86_sse42_pcmpistric128:
17023       Opcode = X86ISD::PCMPISTRI;
17024       X86CC = X86::COND_B;
17025       break;
17026     case Intrinsic::x86_sse42_pcmpestric128:
17027       Opcode = X86ISD::PCMPESTRI;
17028       X86CC = X86::COND_B;
17029       break;
17030     case Intrinsic::x86_sse42_pcmpistrio128:
17031       Opcode = X86ISD::PCMPISTRI;
17032       X86CC = X86::COND_O;
17033       break;
17034     case Intrinsic::x86_sse42_pcmpestrio128:
17035       Opcode = X86ISD::PCMPESTRI;
17036       X86CC = X86::COND_O;
17037       break;
17038     case Intrinsic::x86_sse42_pcmpistris128:
17039       Opcode = X86ISD::PCMPISTRI;
17040       X86CC = X86::COND_S;
17041       break;
17042     case Intrinsic::x86_sse42_pcmpestris128:
17043       Opcode = X86ISD::PCMPESTRI;
17044       X86CC = X86::COND_S;
17045       break;
17046     case Intrinsic::x86_sse42_pcmpistriz128:
17047       Opcode = X86ISD::PCMPISTRI;
17048       X86CC = X86::COND_E;
17049       break;
17050     case Intrinsic::x86_sse42_pcmpestriz128:
17051       Opcode = X86ISD::PCMPESTRI;
17052       X86CC = X86::COND_E;
17053       break;
17054     }
17055     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17056     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17057     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
17058     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17059                                 DAG.getConstant(X86CC, dl, MVT::i8),
17060                                 SDValue(PCMP.getNode(), 1));
17061     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17062   }
17063
17064   case Intrinsic::x86_sse42_pcmpistri128:
17065   case Intrinsic::x86_sse42_pcmpestri128: {
17066     unsigned Opcode;
17067     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
17068       Opcode = X86ISD::PCMPISTRI;
17069     else
17070       Opcode = X86ISD::PCMPESTRI;
17071
17072     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17073     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17074     return DAG.getNode(Opcode, dl, VTs, NewOps);
17075   }
17076
17077   case Intrinsic::x86_seh_lsda: {
17078     // Compute the symbol for the LSDA. We know it'll get emitted later.
17079     MachineFunction &MF = DAG.getMachineFunction();
17080     SDValue Op1 = Op.getOperand(1);
17081     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
17082     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
17083         GlobalValue::getRealLinkageName(Fn->getName()));
17084
17085     // Generate a simple absolute symbol reference. This intrinsic is only
17086     // supported on 32-bit Windows, which isn't PIC.
17087     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
17088     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
17089   }
17090
17091   case Intrinsic::x86_seh_recoverfp: {
17092     SDValue FnOp = Op.getOperand(1);
17093     SDValue IncomingFPOp = Op.getOperand(2);
17094     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
17095     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
17096     if (!Fn)
17097       report_fatal_error(
17098           "llvm.x86.seh.recoverfp must take a function as the first argument");
17099     return recoverFramePointer(DAG, Fn, IncomingFPOp);
17100   }
17101
17102   case Intrinsic::localaddress: {
17103     // Returns one of the stack, base, or frame pointer registers, depending on
17104     // which is used to reference local variables.
17105     MachineFunction &MF = DAG.getMachineFunction();
17106     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17107     unsigned Reg;
17108     if (RegInfo->hasBasePointer(MF))
17109       Reg = RegInfo->getBaseRegister();
17110     else // This function handles the SP or FP case.
17111       Reg = RegInfo->getPtrSizedFrameRegister(MF);
17112     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
17113   }
17114   }
17115 }
17116
17117 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17118                               SDValue Src, SDValue Mask, SDValue Base,
17119                               SDValue Index, SDValue ScaleOp, SDValue Chain,
17120                               const X86Subtarget * Subtarget) {
17121   SDLoc dl(Op);
17122   auto *C = cast<ConstantSDNode>(ScaleOp);
17123   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17124   MVT MaskVT = MVT::getVectorVT(MVT::i1,
17125                              Index.getSimpleValueType().getVectorNumElements());
17126   SDValue MaskInReg;
17127   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17128   if (MaskC)
17129     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17130   else {
17131     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17132                                      Mask.getSimpleValueType().getSizeInBits());
17133
17134     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17135     // are extracted by EXTRACT_SUBVECTOR.
17136     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17137                             DAG.getBitcast(BitcastVT, Mask),
17138                             DAG.getIntPtrConstant(0, dl));
17139   }
17140   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
17141   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17142   SDValue Segment = DAG.getRegister(0, MVT::i32);
17143   if (Src.getOpcode() == ISD::UNDEF)
17144     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
17145   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17146   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17147   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
17148   return DAG.getMergeValues(RetOps, dl);
17149 }
17150
17151 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17152                                SDValue Src, SDValue Mask, SDValue Base,
17153                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
17154   SDLoc dl(Op);
17155   auto *C = cast<ConstantSDNode>(ScaleOp);
17156   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17157   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17158   SDValue Segment = DAG.getRegister(0, MVT::i32);
17159   MVT MaskVT = MVT::getVectorVT(MVT::i1,
17160                              Index.getSimpleValueType().getVectorNumElements());
17161   SDValue MaskInReg;
17162   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17163   if (MaskC)
17164     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17165   else {
17166     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17167                                      Mask.getSimpleValueType().getSizeInBits());
17168
17169     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17170     // are extracted by EXTRACT_SUBVECTOR.
17171     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17172                             DAG.getBitcast(BitcastVT, Mask),
17173                             DAG.getIntPtrConstant(0, dl));
17174   }
17175   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
17176   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
17177   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17178   return SDValue(Res, 1);
17179 }
17180
17181 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17182                                SDValue Mask, SDValue Base, SDValue Index,
17183                                SDValue ScaleOp, SDValue Chain) {
17184   SDLoc dl(Op);
17185   auto *C = cast<ConstantSDNode>(ScaleOp);
17186   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17187   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17188   SDValue Segment = DAG.getRegister(0, MVT::i32);
17189   MVT MaskVT =
17190     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
17191   SDValue MaskInReg;
17192   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17193   if (MaskC)
17194     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17195   else
17196     MaskInReg = DAG.getBitcast(MaskVT, Mask);
17197   //SDVTList VTs = DAG.getVTList(MVT::Other);
17198   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17199   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
17200   return SDValue(Res, 0);
17201 }
17202
17203 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
17204 // read performance monitor counters (x86_rdpmc).
17205 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
17206                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17207                               SmallVectorImpl<SDValue> &Results) {
17208   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17209   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17210   SDValue LO, HI;
17211
17212   // The ECX register is used to select the index of the performance counter
17213   // to read.
17214   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
17215                                    N->getOperand(2));
17216   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
17217
17218   // Reads the content of a 64-bit performance counter and returns it in the
17219   // registers EDX:EAX.
17220   if (Subtarget->is64Bit()) {
17221     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17222     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17223                             LO.getValue(2));
17224   } else {
17225     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17226     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17227                             LO.getValue(2));
17228   }
17229   Chain = HI.getValue(1);
17230
17231   if (Subtarget->is64Bit()) {
17232     // The EAX register is loaded with the low-order 32 bits. The EDX register
17233     // is loaded with the supported high-order bits of the counter.
17234     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17235                               DAG.getConstant(32, DL, MVT::i8));
17236     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17237     Results.push_back(Chain);
17238     return;
17239   }
17240
17241   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17242   SDValue Ops[] = { LO, HI };
17243   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17244   Results.push_back(Pair);
17245   Results.push_back(Chain);
17246 }
17247
17248 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17249 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17250 // also used to custom lower READCYCLECOUNTER nodes.
17251 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17252                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17253                               SmallVectorImpl<SDValue> &Results) {
17254   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17255   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17256   SDValue LO, HI;
17257
17258   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17259   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17260   // and the EAX register is loaded with the low-order 32 bits.
17261   if (Subtarget->is64Bit()) {
17262     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17263     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17264                             LO.getValue(2));
17265   } else {
17266     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17267     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17268                             LO.getValue(2));
17269   }
17270   SDValue Chain = HI.getValue(1);
17271
17272   if (Opcode == X86ISD::RDTSCP_DAG) {
17273     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17274
17275     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17276     // the ECX register. Add 'ecx' explicitly to the chain.
17277     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17278                                      HI.getValue(2));
17279     // Explicitly store the content of ECX at the location passed in input
17280     // to the 'rdtscp' intrinsic.
17281     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17282                          MachinePointerInfo(), false, false, 0);
17283   }
17284
17285   if (Subtarget->is64Bit()) {
17286     // The EDX register is loaded with the high-order 32 bits of the MSR, and
17287     // the EAX register is loaded with the low-order 32 bits.
17288     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17289                               DAG.getConstant(32, DL, MVT::i8));
17290     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17291     Results.push_back(Chain);
17292     return;
17293   }
17294
17295   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17296   SDValue Ops[] = { LO, HI };
17297   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17298   Results.push_back(Pair);
17299   Results.push_back(Chain);
17300 }
17301
17302 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17303                                      SelectionDAG &DAG) {
17304   SmallVector<SDValue, 2> Results;
17305   SDLoc DL(Op);
17306   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17307                           Results);
17308   return DAG.getMergeValues(Results, DL);
17309 }
17310
17311 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
17312   MachineFunction &MF = DAG.getMachineFunction();
17313   SDValue Chain = Op.getOperand(0);
17314   SDValue RegNode = Op.getOperand(2);
17315   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
17316   if (!EHInfo)
17317     report_fatal_error("EH registrations only live in functions using WinEH");
17318
17319   // Cast the operand to an alloca, and remember the frame index.
17320   auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
17321   if (!FINode)
17322     report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
17323   EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
17324
17325   // Return the chain operand without making any DAG nodes.
17326   return Chain;
17327 }
17328
17329 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
17330 /// return truncate Store/MaskedStore Node
17331 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
17332                                                SelectionDAG &DAG,
17333                                                MVT ElementType) {
17334   SDLoc dl(Op);
17335   SDValue Mask = Op.getOperand(4);
17336   SDValue DataToTruncate = Op.getOperand(3);
17337   SDValue Addr = Op.getOperand(2);
17338   SDValue Chain = Op.getOperand(0);
17339
17340   MVT VT  = DataToTruncate.getSimpleValueType();
17341   MVT SVT = MVT::getVectorVT(ElementType, VT.getVectorNumElements());
17342
17343   if (isAllOnesConstant(Mask)) // return just a truncate store
17344     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
17345                              MachinePointerInfo(), SVT, false, false,
17346                              SVT.getScalarSizeInBits()/8);
17347
17348   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17349   MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17350                                    Mask.getSimpleValueType().getSizeInBits());
17351   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17352   // are extracted by EXTRACT_SUBVECTOR.
17353   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17354                               DAG.getBitcast(BitcastVT, Mask),
17355                               DAG.getIntPtrConstant(0, dl));
17356
17357   MachineMemOperand *MMO = DAG.getMachineFunction().
17358     getMachineMemOperand(MachinePointerInfo(),
17359                          MachineMemOperand::MOStore, SVT.getStoreSize(),
17360                          SVT.getScalarSizeInBits()/8);
17361
17362   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
17363                             VMask, SVT, MMO, true);
17364 }
17365
17366 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17367                                       SelectionDAG &DAG) {
17368   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17369
17370   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17371   if (!IntrData) {
17372     if (IntNo == llvm::Intrinsic::x86_seh_ehregnode)
17373       return MarkEHRegistrationNode(Op, DAG);
17374     if (IntNo == llvm::Intrinsic::x86_flags_read_u32 ||
17375         IntNo == llvm::Intrinsic::x86_flags_read_u64 ||
17376         IntNo == llvm::Intrinsic::x86_flags_write_u32 ||
17377         IntNo == llvm::Intrinsic::x86_flags_write_u64) {
17378       // We need a frame pointer because this will get lowered to a PUSH/POP
17379       // sequence.
17380       MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17381       MFI->setHasOpaqueSPAdjustment(true);
17382       // Don't do anything here, we will expand these intrinsics out later
17383       // during ExpandISelPseudos in EmitInstrWithCustomInserter.
17384       return SDValue();
17385     }
17386     return SDValue();
17387   }
17388
17389   SDLoc dl(Op);
17390   switch(IntrData->Type) {
17391   default: llvm_unreachable("Unknown Intrinsic Type");
17392   case RDSEED:
17393   case RDRAND: {
17394     // Emit the node with the right value type.
17395     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17396     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17397
17398     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17399     // Otherwise return the value from Rand, which is always 0, casted to i32.
17400     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17401                       DAG.getConstant(1, dl, Op->getValueType(1)),
17402                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
17403                       SDValue(Result.getNode(), 1) };
17404     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17405                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
17406                                   Ops);
17407
17408     // Return { result, isValid, chain }.
17409     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17410                        SDValue(Result.getNode(), 2));
17411   }
17412   case GATHER: {
17413   //gather(v1, mask, index, base, scale);
17414     SDValue Chain = Op.getOperand(0);
17415     SDValue Src   = Op.getOperand(2);
17416     SDValue Base  = Op.getOperand(3);
17417     SDValue Index = Op.getOperand(4);
17418     SDValue Mask  = Op.getOperand(5);
17419     SDValue Scale = Op.getOperand(6);
17420     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17421                          Chain, Subtarget);
17422   }
17423   case SCATTER: {
17424   //scatter(base, mask, index, v1, scale);
17425     SDValue Chain = Op.getOperand(0);
17426     SDValue Base  = Op.getOperand(2);
17427     SDValue Mask  = Op.getOperand(3);
17428     SDValue Index = Op.getOperand(4);
17429     SDValue Src   = Op.getOperand(5);
17430     SDValue Scale = Op.getOperand(6);
17431     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17432                           Scale, Chain);
17433   }
17434   case PREFETCH: {
17435     SDValue Hint = Op.getOperand(6);
17436     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17437     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17438     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17439     SDValue Chain = Op.getOperand(0);
17440     SDValue Mask  = Op.getOperand(2);
17441     SDValue Index = Op.getOperand(3);
17442     SDValue Base  = Op.getOperand(4);
17443     SDValue Scale = Op.getOperand(5);
17444     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17445   }
17446   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17447   case RDTSC: {
17448     SmallVector<SDValue, 2> Results;
17449     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17450                             Results);
17451     return DAG.getMergeValues(Results, dl);
17452   }
17453   // Read Performance Monitoring Counters.
17454   case RDPMC: {
17455     SmallVector<SDValue, 2> Results;
17456     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17457     return DAG.getMergeValues(Results, dl);
17458   }
17459   // XTEST intrinsics.
17460   case XTEST: {
17461     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17462     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17463     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17464                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17465                                 InTrans);
17466     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17467     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17468                        Ret, SDValue(InTrans.getNode(), 1));
17469   }
17470   // ADC/ADCX/SBB
17471   case ADX: {
17472     SmallVector<SDValue, 2> Results;
17473     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17474     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17475     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17476                                 DAG.getConstant(-1, dl, MVT::i8));
17477     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17478                               Op.getOperand(4), GenCF.getValue(1));
17479     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17480                                  Op.getOperand(5), MachinePointerInfo(),
17481                                  false, false, 0);
17482     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17483                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17484                                 Res.getValue(1));
17485     Results.push_back(SetCC);
17486     Results.push_back(Store);
17487     return DAG.getMergeValues(Results, dl);
17488   }
17489   case COMPRESS_TO_MEM: {
17490     SDLoc dl(Op);
17491     SDValue Mask = Op.getOperand(4);
17492     SDValue DataToCompress = Op.getOperand(3);
17493     SDValue Addr = Op.getOperand(2);
17494     SDValue Chain = Op.getOperand(0);
17495
17496     MVT VT = DataToCompress.getSimpleValueType();
17497     if (isAllOnesConstant(Mask)) // return just a store
17498       return DAG.getStore(Chain, dl, DataToCompress, Addr,
17499                           MachinePointerInfo(), false, false,
17500                           VT.getScalarSizeInBits()/8);
17501
17502     SDValue Compressed =
17503       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17504                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17505     return DAG.getStore(Chain, dl, Compressed, Addr,
17506                         MachinePointerInfo(), false, false,
17507                         VT.getScalarSizeInBits()/8);
17508   }
17509   case TRUNCATE_TO_MEM_VI8:
17510     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17511   case TRUNCATE_TO_MEM_VI16:
17512     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17513   case TRUNCATE_TO_MEM_VI32:
17514     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17515   case EXPAND_FROM_MEM: {
17516     SDLoc dl(Op);
17517     SDValue Mask = Op.getOperand(4);
17518     SDValue PassThru = Op.getOperand(3);
17519     SDValue Addr = Op.getOperand(2);
17520     SDValue Chain = Op.getOperand(0);
17521     MVT VT = Op.getSimpleValueType();
17522
17523     if (isAllOnesConstant(Mask)) // return just a load
17524       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17525                          false, VT.getScalarSizeInBits()/8);
17526
17527     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17528                                        false, false, false,
17529                                        VT.getScalarSizeInBits()/8);
17530
17531     SDValue Results[] = {
17532       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17533                            Mask, PassThru, Subtarget, DAG), Chain};
17534     return DAG.getMergeValues(Results, dl);
17535   }
17536   }
17537 }
17538
17539 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17540                                            SelectionDAG &DAG) const {
17541   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17542   MFI->setReturnAddressIsTaken(true);
17543
17544   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17545     return SDValue();
17546
17547   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17548   SDLoc dl(Op);
17549   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17550
17551   if (Depth > 0) {
17552     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17553     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17554     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17555     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17556                        DAG.getNode(ISD::ADD, dl, PtrVT,
17557                                    FrameAddr, Offset),
17558                        MachinePointerInfo(), false, false, false, 0);
17559   }
17560
17561   // Just load the return address.
17562   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17563   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17564                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17565 }
17566
17567 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17568   MachineFunction &MF = DAG.getMachineFunction();
17569   MachineFrameInfo *MFI = MF.getFrameInfo();
17570   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17571   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17572   EVT VT = Op.getValueType();
17573
17574   MFI->setFrameAddressIsTaken(true);
17575
17576   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17577     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
17578     // is not possible to crawl up the stack without looking at the unwind codes
17579     // simultaneously.
17580     int FrameAddrIndex = FuncInfo->getFAIndex();
17581     if (!FrameAddrIndex) {
17582       // Set up a frame object for the return address.
17583       unsigned SlotSize = RegInfo->getSlotSize();
17584       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17585           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17586       FuncInfo->setFAIndex(FrameAddrIndex);
17587     }
17588     return DAG.getFrameIndex(FrameAddrIndex, VT);
17589   }
17590
17591   unsigned FrameReg =
17592       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17593   SDLoc dl(Op);  // FIXME probably not meaningful
17594   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17595   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17596           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17597          "Invalid Frame Register!");
17598   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17599   while (Depth--)
17600     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17601                             MachinePointerInfo(),
17602                             false, false, false, 0);
17603   return FrameAddr;
17604 }
17605
17606 // FIXME? Maybe this could be a TableGen attribute on some registers and
17607 // this table could be generated automatically from RegInfo.
17608 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17609                                               SelectionDAG &DAG) const {
17610   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17611   const MachineFunction &MF = DAG.getMachineFunction();
17612
17613   unsigned Reg = StringSwitch<unsigned>(RegName)
17614                        .Case("esp", X86::ESP)
17615                        .Case("rsp", X86::RSP)
17616                        .Case("ebp", X86::EBP)
17617                        .Case("rbp", X86::RBP)
17618                        .Default(0);
17619
17620   if (Reg == X86::EBP || Reg == X86::RBP) {
17621     if (!TFI.hasFP(MF))
17622       report_fatal_error("register " + StringRef(RegName) +
17623                          " is allocatable: function has no frame pointer");
17624 #ifndef NDEBUG
17625     else {
17626       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17627       unsigned FrameReg =
17628           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17629       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17630              "Invalid Frame Register!");
17631     }
17632 #endif
17633   }
17634
17635   if (Reg)
17636     return Reg;
17637
17638   report_fatal_error("Invalid register name global variable");
17639 }
17640
17641 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17642                                                      SelectionDAG &DAG) const {
17643   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17644   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17645 }
17646
17647 unsigned X86TargetLowering::getExceptionPointerRegister(
17648     const Constant *PersonalityFn) const {
17649   if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
17650     return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17651
17652   return Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
17653 }
17654
17655 unsigned X86TargetLowering::getExceptionSelectorRegister(
17656     const Constant *PersonalityFn) const {
17657   // Funclet personalities don't use selectors (the runtime does the selection).
17658   assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
17659   return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17660 }
17661
17662 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17663   SDValue Chain     = Op.getOperand(0);
17664   SDValue Offset    = Op.getOperand(1);
17665   SDValue Handler   = Op.getOperand(2);
17666   SDLoc dl      (Op);
17667
17668   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17669   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17670   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17671   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17672           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17673          "Invalid Frame Register!");
17674   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17675   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17676
17677   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17678                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17679                                                        dl));
17680   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17681   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17682                        false, false, 0);
17683   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17684
17685   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17686                      DAG.getRegister(StoreAddrReg, PtrVT));
17687 }
17688
17689 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17690                                                SelectionDAG &DAG) const {
17691   SDLoc DL(Op);
17692   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17693                      DAG.getVTList(MVT::i32, MVT::Other),
17694                      Op.getOperand(0), Op.getOperand(1));
17695 }
17696
17697 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17698                                                 SelectionDAG &DAG) const {
17699   SDLoc DL(Op);
17700   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17701                      Op.getOperand(0), Op.getOperand(1));
17702 }
17703
17704 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17705   return Op.getOperand(0);
17706 }
17707
17708 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17709                                                 SelectionDAG &DAG) const {
17710   SDValue Root = Op.getOperand(0);
17711   SDValue Trmp = Op.getOperand(1); // trampoline
17712   SDValue FPtr = Op.getOperand(2); // nested function
17713   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17714   SDLoc dl (Op);
17715
17716   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17717   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17718
17719   if (Subtarget->is64Bit()) {
17720     SDValue OutChains[6];
17721
17722     // Large code-model.
17723     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17724     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17725
17726     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17727     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17728
17729     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17730
17731     // Load the pointer to the nested function into R11.
17732     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17733     SDValue Addr = Trmp;
17734     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17735                                 Addr, MachinePointerInfo(TrmpAddr),
17736                                 false, false, 0);
17737
17738     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17739                        DAG.getConstant(2, dl, MVT::i64));
17740     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17741                                 MachinePointerInfo(TrmpAddr, 2),
17742                                 false, false, 2);
17743
17744     // Load the 'nest' parameter value into R10.
17745     // R10 is specified in X86CallingConv.td
17746     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17747     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17748                        DAG.getConstant(10, dl, MVT::i64));
17749     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17750                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17751                                 false, false, 0);
17752
17753     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17754                        DAG.getConstant(12, dl, MVT::i64));
17755     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17756                                 MachinePointerInfo(TrmpAddr, 12),
17757                                 false, false, 2);
17758
17759     // Jump to the nested function.
17760     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17761     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17762                        DAG.getConstant(20, dl, MVT::i64));
17763     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17764                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17765                                 false, false, 0);
17766
17767     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17768     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17769                        DAG.getConstant(22, dl, MVT::i64));
17770     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17771                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17772                                 false, false, 0);
17773
17774     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17775   } else {
17776     const Function *Func =
17777       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17778     CallingConv::ID CC = Func->getCallingConv();
17779     unsigned NestReg;
17780
17781     switch (CC) {
17782     default:
17783       llvm_unreachable("Unsupported calling convention");
17784     case CallingConv::C:
17785     case CallingConv::X86_StdCall: {
17786       // Pass 'nest' parameter in ECX.
17787       // Must be kept in sync with X86CallingConv.td
17788       NestReg = X86::ECX;
17789
17790       // Check that ECX wasn't needed by an 'inreg' parameter.
17791       FunctionType *FTy = Func->getFunctionType();
17792       const AttributeSet &Attrs = Func->getAttributes();
17793
17794       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17795         unsigned InRegCount = 0;
17796         unsigned Idx = 1;
17797
17798         for (FunctionType::param_iterator I = FTy->param_begin(),
17799              E = FTy->param_end(); I != E; ++I, ++Idx)
17800           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17801             auto &DL = DAG.getDataLayout();
17802             // FIXME: should only count parameters that are lowered to integers.
17803             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17804           }
17805
17806         if (InRegCount > 2) {
17807           report_fatal_error("Nest register in use - reduce number of inreg"
17808                              " parameters!");
17809         }
17810       }
17811       break;
17812     }
17813     case CallingConv::X86_FastCall:
17814     case CallingConv::X86_ThisCall:
17815     case CallingConv::Fast:
17816       // Pass 'nest' parameter in EAX.
17817       // Must be kept in sync with X86CallingConv.td
17818       NestReg = X86::EAX;
17819       break;
17820     }
17821
17822     SDValue OutChains[4];
17823     SDValue Addr, Disp;
17824
17825     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17826                        DAG.getConstant(10, dl, MVT::i32));
17827     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17828
17829     // This is storing the opcode for MOV32ri.
17830     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17831     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17832     OutChains[0] = DAG.getStore(Root, dl,
17833                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17834                                 Trmp, MachinePointerInfo(TrmpAddr),
17835                                 false, false, 0);
17836
17837     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17838                        DAG.getConstant(1, dl, MVT::i32));
17839     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17840                                 MachinePointerInfo(TrmpAddr, 1),
17841                                 false, false, 1);
17842
17843     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17844     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17845                        DAG.getConstant(5, dl, MVT::i32));
17846     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17847                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17848                                 false, false, 1);
17849
17850     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17851                        DAG.getConstant(6, dl, MVT::i32));
17852     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17853                                 MachinePointerInfo(TrmpAddr, 6),
17854                                 false, false, 1);
17855
17856     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17857   }
17858 }
17859
17860 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17861                                             SelectionDAG &DAG) const {
17862   /*
17863    The rounding mode is in bits 11:10 of FPSR, and has the following
17864    settings:
17865      00 Round to nearest
17866      01 Round to -inf
17867      10 Round to +inf
17868      11 Round to 0
17869
17870   FLT_ROUNDS, on the other hand, expects the following:
17871     -1 Undefined
17872      0 Round to 0
17873      1 Round to nearest
17874      2 Round to +inf
17875      3 Round to -inf
17876
17877   To perform the conversion, we do:
17878     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17879   */
17880
17881   MachineFunction &MF = DAG.getMachineFunction();
17882   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17883   unsigned StackAlignment = TFI.getStackAlignment();
17884   MVT VT = Op.getSimpleValueType();
17885   SDLoc DL(Op);
17886
17887   // Save FP Control Word to stack slot
17888   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17889   SDValue StackSlot =
17890       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17891
17892   MachineMemOperand *MMO =
17893       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17894                               MachineMemOperand::MOStore, 2, 2);
17895
17896   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17897   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17898                                           DAG.getVTList(MVT::Other),
17899                                           Ops, MVT::i16, MMO);
17900
17901   // Load FP Control Word from stack slot
17902   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17903                             MachinePointerInfo(), false, false, false, 0);
17904
17905   // Transform as necessary
17906   SDValue CWD1 =
17907     DAG.getNode(ISD::SRL, DL, MVT::i16,
17908                 DAG.getNode(ISD::AND, DL, MVT::i16,
17909                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17910                 DAG.getConstant(11, DL, MVT::i8));
17911   SDValue CWD2 =
17912     DAG.getNode(ISD::SRL, DL, MVT::i16,
17913                 DAG.getNode(ISD::AND, DL, MVT::i16,
17914                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17915                 DAG.getConstant(9, DL, MVT::i8));
17916
17917   SDValue RetVal =
17918     DAG.getNode(ISD::AND, DL, MVT::i16,
17919                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17920                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17921                             DAG.getConstant(1, DL, MVT::i16)),
17922                 DAG.getConstant(3, DL, MVT::i16));
17923
17924   return DAG.getNode((VT.getSizeInBits() < 16 ?
17925                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17926 }
17927
17928 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
17929 //
17930 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
17931 //    to 512-bit vector.
17932 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
17933 //    ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
17934 //    split the vector, perform operation on it's Lo a Hi part and
17935 //    concatenate the results.
17936 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
17937   SDLoc dl(Op);
17938   MVT VT = Op.getSimpleValueType();
17939   MVT EltVT = VT.getVectorElementType();
17940   unsigned NumElems = VT.getVectorNumElements();
17941
17942   if (EltVT == MVT::i64 || EltVT == MVT::i32) {
17943     // Extend to 512 bit vector.
17944     assert((VT.is256BitVector() || VT.is128BitVector()) &&
17945               "Unsupported value type for operation");
17946
17947     MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
17948     SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
17949                                  DAG.getUNDEF(NewVT),
17950                                  Op.getOperand(0),
17951                                  DAG.getIntPtrConstant(0, dl));
17952     SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
17953
17954     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
17955                        DAG.getIntPtrConstant(0, dl));
17956   }
17957
17958   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
17959           "Unsupported element type");
17960
17961   if (16 < NumElems) {
17962     // Split vector, it's Lo and Hi parts will be handled in next iteration.
17963     SDValue Lo, Hi;
17964     std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
17965     MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
17966
17967     Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
17968     Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
17969
17970     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
17971   }
17972
17973   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
17974
17975   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
17976           "Unsupported value type for operation");
17977
17978   // Use native supported vector instruction vplzcntd.
17979   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
17980   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
17981   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
17982   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
17983
17984   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
17985 }
17986
17987 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
17988                          SelectionDAG &DAG) {
17989   MVT VT = Op.getSimpleValueType();
17990   MVT OpVT = VT;
17991   unsigned NumBits = VT.getSizeInBits();
17992   SDLoc dl(Op);
17993
17994   if (VT.isVector() && Subtarget->hasAVX512())
17995     return LowerVectorCTLZ_AVX512(Op, DAG);
17996
17997   Op = Op.getOperand(0);
17998   if (VT == MVT::i8) {
17999     // Zero extend to i32 since there is not an i8 bsr.
18000     OpVT = MVT::i32;
18001     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18002   }
18003
18004   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
18005   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18006   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18007
18008   // If src is zero (i.e. bsr sets ZF), returns NumBits.
18009   SDValue Ops[] = {
18010     Op,
18011     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
18012     DAG.getConstant(X86::COND_E, dl, MVT::i8),
18013     Op.getValue(1)
18014   };
18015   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
18016
18017   // Finally xor with NumBits-1.
18018   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18019                    DAG.getConstant(NumBits - 1, dl, OpVT));
18020
18021   if (VT == MVT::i8)
18022     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18023   return Op;
18024 }
18025
18026 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
18027                                     SelectionDAG &DAG) {
18028   MVT VT = Op.getSimpleValueType();
18029   EVT OpVT = VT;
18030   unsigned NumBits = VT.getSizeInBits();
18031   SDLoc dl(Op);
18032
18033   Op = Op.getOperand(0);
18034   if (VT == MVT::i8) {
18035     // Zero extend to i32 since there is not an i8 bsr.
18036     OpVT = MVT::i32;
18037     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18038   }
18039
18040   // Issue a bsr (scan bits in reverse).
18041   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18042   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18043
18044   // And xor with NumBits-1.
18045   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18046                    DAG.getConstant(NumBits - 1, dl, OpVT));
18047
18048   if (VT == MVT::i8)
18049     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18050   return Op;
18051 }
18052
18053 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
18054   MVT VT = Op.getSimpleValueType();
18055   unsigned NumBits = VT.getScalarSizeInBits();
18056   SDLoc dl(Op);
18057
18058   if (VT.isVector()) {
18059     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18060
18061     SDValue N0 = Op.getOperand(0);
18062     SDValue Zero = DAG.getConstant(0, dl, VT);
18063
18064     // lsb(x) = (x & -x)
18065     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
18066                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
18067
18068     // cttz_undef(x) = (width - 1) - ctlz(lsb)
18069     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
18070         TLI.isOperationLegal(ISD::CTLZ, VT)) {
18071       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
18072       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
18073                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
18074     }
18075
18076     // cttz(x) = ctpop(lsb - 1)
18077     SDValue One = DAG.getConstant(1, dl, VT);
18078     return DAG.getNode(ISD::CTPOP, dl, VT,
18079                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
18080   }
18081
18082   assert(Op.getOpcode() == ISD::CTTZ &&
18083          "Only scalar CTTZ requires custom lowering");
18084
18085   // Issue a bsf (scan bits forward) which also sets EFLAGS.
18086   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18087   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
18088
18089   // If src is zero (i.e. bsf sets ZF), returns NumBits.
18090   SDValue Ops[] = {
18091     Op,
18092     DAG.getConstant(NumBits, dl, VT),
18093     DAG.getConstant(X86::COND_E, dl, MVT::i8),
18094     Op.getValue(1)
18095   };
18096   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
18097 }
18098
18099 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
18100 // ones, and then concatenate the result back.
18101 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
18102   MVT VT = Op.getSimpleValueType();
18103
18104   assert(VT.is256BitVector() && VT.isInteger() &&
18105          "Unsupported value type for operation");
18106
18107   unsigned NumElems = VT.getVectorNumElements();
18108   SDLoc dl(Op);
18109
18110   // Extract the LHS vectors
18111   SDValue LHS = Op.getOperand(0);
18112   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18113   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18114
18115   // Extract the RHS vectors
18116   SDValue RHS = Op.getOperand(1);
18117   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
18118   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
18119
18120   MVT EltVT = VT.getVectorElementType();
18121   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18122
18123   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18124                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
18125                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
18126 }
18127
18128 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
18129   if (Op.getValueType() == MVT::i1)
18130     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18131                        Op.getOperand(0), Op.getOperand(1));
18132   assert(Op.getSimpleValueType().is256BitVector() &&
18133          Op.getSimpleValueType().isInteger() &&
18134          "Only handle AVX 256-bit vector integer operation");
18135   return Lower256IntArith(Op, DAG);
18136 }
18137
18138 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
18139   if (Op.getValueType() == MVT::i1)
18140     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18141                        Op.getOperand(0), Op.getOperand(1));
18142   assert(Op.getSimpleValueType().is256BitVector() &&
18143          Op.getSimpleValueType().isInteger() &&
18144          "Only handle AVX 256-bit vector integer operation");
18145   return Lower256IntArith(Op, DAG);
18146 }
18147
18148 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
18149   assert(Op.getSimpleValueType().is256BitVector() &&
18150          Op.getSimpleValueType().isInteger() &&
18151          "Only handle AVX 256-bit vector integer operation");
18152   return Lower256IntArith(Op, DAG);
18153 }
18154
18155 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
18156                         SelectionDAG &DAG) {
18157   SDLoc dl(Op);
18158   MVT VT = Op.getSimpleValueType();
18159
18160   if (VT == MVT::i1)
18161     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
18162
18163   // Decompose 256-bit ops into smaller 128-bit ops.
18164   if (VT.is256BitVector() && !Subtarget->hasInt256())
18165     return Lower256IntArith(Op, DAG);
18166
18167   SDValue A = Op.getOperand(0);
18168   SDValue B = Op.getOperand(1);
18169
18170   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
18171   // pairs, multiply and truncate.
18172   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
18173     if (Subtarget->hasInt256()) {
18174       if (VT == MVT::v32i8) {
18175         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
18176         SDValue Lo = DAG.getIntPtrConstant(0, dl);
18177         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
18178         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
18179         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
18180         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
18181         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
18182         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18183                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
18184                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
18185       }
18186
18187       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
18188       return DAG.getNode(
18189           ISD::TRUNCATE, dl, VT,
18190           DAG.getNode(ISD::MUL, dl, ExVT,
18191                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
18192                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
18193     }
18194
18195     assert(VT == MVT::v16i8 &&
18196            "Pre-AVX2 support only supports v16i8 multiplication");
18197     MVT ExVT = MVT::v8i16;
18198
18199     // Extract the lo parts and sign extend to i16
18200     SDValue ALo, BLo;
18201     if (Subtarget->hasSSE41()) {
18202       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
18203       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
18204     } else {
18205       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
18206                               -1, 4, -1, 5, -1, 6, -1, 7};
18207       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18208       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18209       ALo = DAG.getBitcast(ExVT, ALo);
18210       BLo = DAG.getBitcast(ExVT, BLo);
18211       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
18212       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
18213     }
18214
18215     // Extract the hi parts and sign extend to i16
18216     SDValue AHi, BHi;
18217     if (Subtarget->hasSSE41()) {
18218       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
18219                               -1, -1, -1, -1, -1, -1, -1, -1};
18220       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18221       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18222       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
18223       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
18224     } else {
18225       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
18226                               -1, 12, -1, 13, -1, 14, -1, 15};
18227       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18228       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18229       AHi = DAG.getBitcast(ExVT, AHi);
18230       BHi = DAG.getBitcast(ExVT, BHi);
18231       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
18232       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
18233     }
18234
18235     // Multiply, mask the lower 8bits of the lo/hi results and pack
18236     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
18237     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
18238     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
18239     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
18240     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18241   }
18242
18243   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
18244   if (VT == MVT::v4i32) {
18245     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
18246            "Should not custom lower when pmuldq is available!");
18247
18248     // Extract the odd parts.
18249     static const int UnpackMask[] = { 1, -1, 3, -1 };
18250     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18251     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18252
18253     // Multiply the even parts.
18254     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18255     // Now multiply odd parts.
18256     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18257
18258     Evens = DAG.getBitcast(VT, Evens);
18259     Odds = DAG.getBitcast(VT, Odds);
18260
18261     // Merge the two vectors back together with a shuffle. This expands into 2
18262     // shuffles.
18263     static const int ShufMask[] = { 0, 4, 2, 6 };
18264     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18265   }
18266
18267   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18268          "Only know how to lower V2I64/V4I64/V8I64 multiply");
18269
18270   //  Ahi = psrlqi(a, 32);
18271   //  Bhi = psrlqi(b, 32);
18272   //
18273   //  AloBlo = pmuludq(a, b);
18274   //  AloBhi = pmuludq(a, Bhi);
18275   //  AhiBlo = pmuludq(Ahi, b);
18276
18277   //  AloBhi = psllqi(AloBhi, 32);
18278   //  AhiBlo = psllqi(AhiBlo, 32);
18279   //  return AloBlo + AloBhi + AhiBlo;
18280
18281   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18282   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18283
18284   SDValue AhiBlo = Ahi;
18285   SDValue AloBhi = Bhi;
18286   // Bit cast to 32-bit vectors for MULUDQ
18287   MVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18288                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18289   A = DAG.getBitcast(MulVT, A);
18290   B = DAG.getBitcast(MulVT, B);
18291   Ahi = DAG.getBitcast(MulVT, Ahi);
18292   Bhi = DAG.getBitcast(MulVT, Bhi);
18293
18294   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18295   // After shifting right const values the result may be all-zero.
18296   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
18297     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18298     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18299   }
18300   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
18301     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18302     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18303   }
18304
18305   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18306   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18307 }
18308
18309 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18310   assert(Subtarget->isTargetWin64() && "Unexpected target");
18311   EVT VT = Op.getValueType();
18312   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18313          "Unexpected return type for lowering");
18314
18315   RTLIB::Libcall LC;
18316   bool isSigned;
18317   switch (Op->getOpcode()) {
18318   default: llvm_unreachable("Unexpected request for libcall!");
18319   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
18320   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
18321   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
18322   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
18323   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
18324   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18325   }
18326
18327   SDLoc dl(Op);
18328   SDValue InChain = DAG.getEntryNode();
18329
18330   TargetLowering::ArgListTy Args;
18331   TargetLowering::ArgListEntry Entry;
18332   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18333     EVT ArgVT = Op->getOperand(i).getValueType();
18334     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18335            "Unexpected argument type for lowering");
18336     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18337     Entry.Node = StackPtr;
18338     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18339                            false, false, 16);
18340     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18341     Entry.Ty = PointerType::get(ArgTy,0);
18342     Entry.isSExt = false;
18343     Entry.isZExt = false;
18344     Args.push_back(Entry);
18345   }
18346
18347   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18348                                          getPointerTy(DAG.getDataLayout()));
18349
18350   TargetLowering::CallLoweringInfo CLI(DAG);
18351   CLI.setDebugLoc(dl).setChain(InChain)
18352     .setCallee(getLibcallCallingConv(LC),
18353                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18354                Callee, std::move(Args), 0)
18355     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18356
18357   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18358   return DAG.getBitcast(VT, CallInfo.first);
18359 }
18360
18361 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18362                              SelectionDAG &DAG) {
18363   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18364   MVT VT = Op0.getSimpleValueType();
18365   SDLoc dl(Op);
18366
18367   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18368          (VT == MVT::v8i32 && Subtarget->hasInt256()));
18369
18370   // PMULxD operations multiply each even value (starting at 0) of LHS with
18371   // the related value of RHS and produce a widen result.
18372   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18373   // => <2 x i64> <ae|cg>
18374   //
18375   // In other word, to have all the results, we need to perform two PMULxD:
18376   // 1. one with the even values.
18377   // 2. one with the odd values.
18378   // To achieve #2, with need to place the odd values at an even position.
18379   //
18380   // Place the odd value at an even position (basically, shift all values 1
18381   // step to the left):
18382   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18383   // <a|b|c|d> => <b|undef|d|undef>
18384   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18385   // <e|f|g|h> => <f|undef|h|undef>
18386   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18387
18388   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18389   // ints.
18390   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18391   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18392   unsigned Opcode =
18393       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18394   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18395   // => <2 x i64> <ae|cg>
18396   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18397   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18398   // => <2 x i64> <bf|dh>
18399   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18400
18401   // Shuffle it back into the right order.
18402   SDValue Highs, Lows;
18403   if (VT == MVT::v8i32) {
18404     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18405     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18406     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18407     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18408   } else {
18409     const int HighMask[] = {1, 5, 3, 7};
18410     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18411     const int LowMask[] = {0, 4, 2, 6};
18412     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18413   }
18414
18415   // If we have a signed multiply but no PMULDQ fix up the high parts of a
18416   // unsigned multiply.
18417   if (IsSigned && !Subtarget->hasSSE41()) {
18418     SDValue ShAmt = DAG.getConstant(
18419         31, dl,
18420         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
18421     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18422                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18423     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18424                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18425
18426     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18427     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18428   }
18429
18430   // The first result of MUL_LOHI is actually the low value, followed by the
18431   // high value.
18432   SDValue Ops[] = {Lows, Highs};
18433   return DAG.getMergeValues(Ops, dl);
18434 }
18435
18436 // Return true if the required (according to Opcode) shift-imm form is natively
18437 // supported by the Subtarget
18438 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18439                                         unsigned Opcode) {
18440   if (VT.getScalarSizeInBits() < 16)
18441     return false;
18442
18443   if (VT.is512BitVector() &&
18444       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18445     return true;
18446
18447   bool LShift = VT.is128BitVector() ||
18448     (VT.is256BitVector() && Subtarget->hasInt256());
18449
18450   bool AShift = LShift && (Subtarget->hasVLX() ||
18451     (VT != MVT::v2i64 && VT != MVT::v4i64));
18452   return (Opcode == ISD::SRA) ? AShift : LShift;
18453 }
18454
18455 // The shift amount is a variable, but it is the same for all vector lanes.
18456 // These instructions are defined together with shift-immediate.
18457 static
18458 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18459                                       unsigned Opcode) {
18460   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18461 }
18462
18463 // Return true if the required (according to Opcode) variable-shift form is
18464 // natively supported by the Subtarget
18465 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18466                                     unsigned Opcode) {
18467
18468   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18469     return false;
18470
18471   // vXi16 supported only on AVX-512, BWI
18472   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18473     return false;
18474
18475   if (VT.is512BitVector() || Subtarget->hasVLX())
18476     return true;
18477
18478   bool LShift = VT.is128BitVector() || VT.is256BitVector();
18479   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
18480   return (Opcode == ISD::SRA) ? AShift : LShift;
18481 }
18482
18483 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18484                                          const X86Subtarget *Subtarget) {
18485   MVT VT = Op.getSimpleValueType();
18486   SDLoc dl(Op);
18487   SDValue R = Op.getOperand(0);
18488   SDValue Amt = Op.getOperand(1);
18489
18490   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18491     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18492
18493   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18494     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18495     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18496     SDValue Ex = DAG.getBitcast(ExVT, R);
18497
18498     if (ShiftAmt >= 32) {
18499       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18500       SDValue Upper =
18501           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18502       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18503                                                  ShiftAmt - 32, DAG);
18504       if (VT == MVT::v2i64)
18505         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18506       if (VT == MVT::v4i64)
18507         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18508                                   {9, 1, 11, 3, 13, 5, 15, 7});
18509     } else {
18510       // SRA upper i32, SHL whole i64 and select lower i32.
18511       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18512                                                  ShiftAmt, DAG);
18513       SDValue Lower =
18514           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18515       Lower = DAG.getBitcast(ExVT, Lower);
18516       if (VT == MVT::v2i64)
18517         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18518       if (VT == MVT::v4i64)
18519         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18520                                   {8, 1, 10, 3, 12, 5, 14, 7});
18521     }
18522     return DAG.getBitcast(VT, Ex);
18523   };
18524
18525   // Optimize shl/srl/sra with constant shift amount.
18526   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18527     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18528       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18529
18530       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18531         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18532
18533       // i64 SRA needs to be performed as partial shifts.
18534       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18535           Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18536         return ArithmeticShiftRight64(ShiftAmt);
18537
18538       if (VT == MVT::v16i8 ||
18539           (Subtarget->hasInt256() && VT == MVT::v32i8) ||
18540           VT == MVT::v64i8) {
18541         unsigned NumElts = VT.getVectorNumElements();
18542         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18543
18544         // Simple i8 add case
18545         if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18546           return DAG.getNode(ISD::ADD, dl, VT, R, R);
18547
18548         // ashr(R, 7)  === cmp_slt(R, 0)
18549         if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18550           SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18551           return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18552         }
18553
18554         // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18555         if (VT == MVT::v16i8 && Subtarget->hasXOP())
18556           return SDValue();
18557
18558         if (Op.getOpcode() == ISD::SHL) {
18559           // Make a large shift.
18560           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18561                                                    R, ShiftAmt, DAG);
18562           SHL = DAG.getBitcast(VT, SHL);
18563           // Zero out the rightmost bits.
18564           return DAG.getNode(ISD::AND, dl, VT, SHL,
18565                              DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, VT));
18566         }
18567         if (Op.getOpcode() == ISD::SRL) {
18568           // Make a large shift.
18569           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18570                                                    R, ShiftAmt, DAG);
18571           SRL = DAG.getBitcast(VT, SRL);
18572           // Zero out the leftmost bits.
18573           return DAG.getNode(ISD::AND, dl, VT, SRL,
18574                              DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, VT));
18575         }
18576         if (Op.getOpcode() == ISD::SRA) {
18577           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18578           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18579
18580           SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
18581           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18582           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18583           return Res;
18584         }
18585         llvm_unreachable("Unknown shift opcode.");
18586       }
18587     }
18588   }
18589
18590   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18591   if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18592       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18593
18594     // Peek through any splat that was introduced for i64 shift vectorization.
18595     int SplatIndex = -1;
18596     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18597       if (SVN->isSplat()) {
18598         SplatIndex = SVN->getSplatIndex();
18599         Amt = Amt.getOperand(0);
18600         assert(SplatIndex < (int)VT.getVectorNumElements() &&
18601                "Splat shuffle referencing second operand");
18602       }
18603
18604     if (Amt.getOpcode() != ISD::BITCAST ||
18605         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18606       return SDValue();
18607
18608     Amt = Amt.getOperand(0);
18609     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18610                      VT.getVectorNumElements();
18611     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18612     uint64_t ShiftAmt = 0;
18613     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18614     for (unsigned i = 0; i != Ratio; ++i) {
18615       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18616       if (!C)
18617         return SDValue();
18618       // 6 == Log2(64)
18619       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18620     }
18621
18622     // Check remaining shift amounts (if not a splat).
18623     if (SplatIndex < 0) {
18624       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18625         uint64_t ShAmt = 0;
18626         for (unsigned j = 0; j != Ratio; ++j) {
18627           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18628           if (!C)
18629             return SDValue();
18630           // 6 == Log2(64)
18631           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18632         }
18633         if (ShAmt != ShiftAmt)
18634           return SDValue();
18635       }
18636     }
18637
18638     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18639       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18640
18641     if (Op.getOpcode() == ISD::SRA)
18642       return ArithmeticShiftRight64(ShiftAmt);
18643   }
18644
18645   return SDValue();
18646 }
18647
18648 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18649                                         const X86Subtarget* Subtarget) {
18650   MVT VT = Op.getSimpleValueType();
18651   SDLoc dl(Op);
18652   SDValue R = Op.getOperand(0);
18653   SDValue Amt = Op.getOperand(1);
18654
18655   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18656     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18657
18658   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18659     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18660
18661   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18662     SDValue BaseShAmt;
18663     MVT EltVT = VT.getVectorElementType();
18664
18665     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18666       // Check if this build_vector node is doing a splat.
18667       // If so, then set BaseShAmt equal to the splat value.
18668       BaseShAmt = BV->getSplatValue();
18669       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18670         BaseShAmt = SDValue();
18671     } else {
18672       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18673         Amt = Amt.getOperand(0);
18674
18675       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18676       if (SVN && SVN->isSplat()) {
18677         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18678         SDValue InVec = Amt.getOperand(0);
18679         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18680           assert((SplatIdx < InVec.getSimpleValueType().getVectorNumElements()) &&
18681                  "Unexpected shuffle index found!");
18682           BaseShAmt = InVec.getOperand(SplatIdx);
18683         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18684            if (ConstantSDNode *C =
18685                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18686              if (C->getZExtValue() == SplatIdx)
18687                BaseShAmt = InVec.getOperand(1);
18688            }
18689         }
18690
18691         if (!BaseShAmt)
18692           // Avoid introducing an extract element from a shuffle.
18693           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18694                                   DAG.getIntPtrConstant(SplatIdx, dl));
18695       }
18696     }
18697
18698     if (BaseShAmt.getNode()) {
18699       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18700       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18701         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18702       else if (EltVT.bitsLT(MVT::i32))
18703         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18704
18705       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18706     }
18707   }
18708
18709   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18710   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
18711       Amt.getOpcode() == ISD::BITCAST &&
18712       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18713     Amt = Amt.getOperand(0);
18714     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18715                      VT.getVectorNumElements();
18716     std::vector<SDValue> Vals(Ratio);
18717     for (unsigned i = 0; i != Ratio; ++i)
18718       Vals[i] = Amt.getOperand(i);
18719     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18720       for (unsigned j = 0; j != Ratio; ++j)
18721         if (Vals[j] != Amt.getOperand(i + j))
18722           return SDValue();
18723     }
18724
18725     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18726       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18727   }
18728   return SDValue();
18729 }
18730
18731 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18732                           SelectionDAG &DAG) {
18733   MVT VT = Op.getSimpleValueType();
18734   SDLoc dl(Op);
18735   SDValue R = Op.getOperand(0);
18736   SDValue Amt = Op.getOperand(1);
18737
18738   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18739   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18740
18741   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18742     return V;
18743
18744   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18745     return V;
18746
18747   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18748     return Op;
18749
18750   // XOP has 128-bit variable logical/arithmetic shifts.
18751   // +ve/-ve Amt = shift left/right.
18752   if (Subtarget->hasXOP() &&
18753       (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18754        VT == MVT::v8i16 || VT == MVT::v16i8)) {
18755     if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18756       SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18757       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18758     }
18759     if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18760       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18761     if (Op.getOpcode() == ISD::SRA)
18762       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18763   }
18764
18765   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18766   // shifts per-lane and then shuffle the partial results back together.
18767   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18768     // Splat the shift amounts so the scalar shifts above will catch it.
18769     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18770     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18771     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18772     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18773     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18774   }
18775
18776   // i64 vector arithmetic shift can be emulated with the transform:
18777   // M = lshr(SIGN_BIT, Amt)
18778   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18779   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18780       Op.getOpcode() == ISD::SRA) {
18781     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18782     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18783     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18784     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18785     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18786     return R;
18787   }
18788
18789   // If possible, lower this packed shift into a vector multiply instead of
18790   // expanding it into a sequence of scalar shifts.
18791   // Do this only if the vector shift count is a constant build_vector.
18792   if (Op.getOpcode() == ISD::SHL &&
18793       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18794        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18795       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18796     SmallVector<SDValue, 8> Elts;
18797     MVT SVT = VT.getVectorElementType();
18798     unsigned SVTBits = SVT.getSizeInBits();
18799     APInt One(SVTBits, 1);
18800     unsigned NumElems = VT.getVectorNumElements();
18801
18802     for (unsigned i=0; i !=NumElems; ++i) {
18803       SDValue Op = Amt->getOperand(i);
18804       if (Op->getOpcode() == ISD::UNDEF) {
18805         Elts.push_back(Op);
18806         continue;
18807       }
18808
18809       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18810       APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
18811       uint64_t ShAmt = C.getZExtValue();
18812       if (ShAmt >= SVTBits) {
18813         Elts.push_back(DAG.getUNDEF(SVT));
18814         continue;
18815       }
18816       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18817     }
18818     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18819     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18820   }
18821
18822   // Lower SHL with variable shift amount.
18823   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18824     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18825
18826     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18827                      DAG.getConstant(0x3f800000U, dl, VT));
18828     Op = DAG.getBitcast(MVT::v4f32, Op);
18829     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18830     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18831   }
18832
18833   // If possible, lower this shift as a sequence of two shifts by
18834   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18835   // Example:
18836   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18837   //
18838   // Could be rewritten as:
18839   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18840   //
18841   // The advantage is that the two shifts from the example would be
18842   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18843   // the vector shift into four scalar shifts plus four pairs of vector
18844   // insert/extract.
18845   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18846       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18847     unsigned TargetOpcode = X86ISD::MOVSS;
18848     bool CanBeSimplified;
18849     // The splat value for the first packed shift (the 'X' from the example).
18850     SDValue Amt1 = Amt->getOperand(0);
18851     // The splat value for the second packed shift (the 'Y' from the example).
18852     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18853                                         Amt->getOperand(2);
18854
18855     // See if it is possible to replace this node with a sequence of
18856     // two shifts followed by a MOVSS/MOVSD
18857     if (VT == MVT::v4i32) {
18858       // Check if it is legal to use a MOVSS.
18859       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18860                         Amt2 == Amt->getOperand(3);
18861       if (!CanBeSimplified) {
18862         // Otherwise, check if we can still simplify this node using a MOVSD.
18863         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18864                           Amt->getOperand(2) == Amt->getOperand(3);
18865         TargetOpcode = X86ISD::MOVSD;
18866         Amt2 = Amt->getOperand(2);
18867       }
18868     } else {
18869       // Do similar checks for the case where the machine value type
18870       // is MVT::v8i16.
18871       CanBeSimplified = Amt1 == Amt->getOperand(1);
18872       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18873         CanBeSimplified = Amt2 == Amt->getOperand(i);
18874
18875       if (!CanBeSimplified) {
18876         TargetOpcode = X86ISD::MOVSD;
18877         CanBeSimplified = true;
18878         Amt2 = Amt->getOperand(4);
18879         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18880           CanBeSimplified = Amt1 == Amt->getOperand(i);
18881         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18882           CanBeSimplified = Amt2 == Amt->getOperand(j);
18883       }
18884     }
18885
18886     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18887         isa<ConstantSDNode>(Amt2)) {
18888       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18889       MVT CastVT = MVT::v4i32;
18890       SDValue Splat1 =
18891         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18892       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18893       SDValue Splat2 =
18894         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18895       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18896       if (TargetOpcode == X86ISD::MOVSD)
18897         CastVT = MVT::v2i64;
18898       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18899       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18900       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18901                                             BitCast1, DAG);
18902       return DAG.getBitcast(VT, Result);
18903     }
18904   }
18905
18906   // v4i32 Non Uniform Shifts.
18907   // If the shift amount is constant we can shift each lane using the SSE2
18908   // immediate shifts, else we need to zero-extend each lane to the lower i64
18909   // and shift using the SSE2 variable shifts.
18910   // The separate results can then be blended together.
18911   if (VT == MVT::v4i32) {
18912     unsigned Opc = Op.getOpcode();
18913     SDValue Amt0, Amt1, Amt2, Amt3;
18914     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18915       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18916       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18917       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18918       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18919     } else {
18920       // ISD::SHL is handled above but we include it here for completeness.
18921       switch (Opc) {
18922       default:
18923         llvm_unreachable("Unknown target vector shift node");
18924       case ISD::SHL:
18925         Opc = X86ISD::VSHL;
18926         break;
18927       case ISD::SRL:
18928         Opc = X86ISD::VSRL;
18929         break;
18930       case ISD::SRA:
18931         Opc = X86ISD::VSRA;
18932         break;
18933       }
18934       // The SSE2 shifts use the lower i64 as the same shift amount for
18935       // all lanes and the upper i64 is ignored. These shuffle masks
18936       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18937       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18938       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18939       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18940       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18941       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18942     }
18943
18944     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18945     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18946     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18947     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18948     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18949     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18950     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18951   }
18952
18953   if (VT == MVT::v16i8 ||
18954       (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
18955     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18956     unsigned ShiftOpcode = Op->getOpcode();
18957
18958     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18959       // On SSE41 targets we make use of the fact that VSELECT lowers
18960       // to PBLENDVB which selects bytes based just on the sign bit.
18961       if (Subtarget->hasSSE41()) {
18962         V0 = DAG.getBitcast(VT, V0);
18963         V1 = DAG.getBitcast(VT, V1);
18964         Sel = DAG.getBitcast(VT, Sel);
18965         return DAG.getBitcast(SelVT,
18966                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18967       }
18968       // On pre-SSE41 targets we test for the sign bit by comparing to
18969       // zero - a negative value will set all bits of the lanes to true
18970       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18971       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18972       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18973       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18974     };
18975
18976     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18977     // We can safely do this using i16 shifts as we're only interested in
18978     // the 3 lower bits of each byte.
18979     Amt = DAG.getBitcast(ExtVT, Amt);
18980     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18981     Amt = DAG.getBitcast(VT, Amt);
18982
18983     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18984       // r = VSELECT(r, shift(r, 4), a);
18985       SDValue M =
18986           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18987       R = SignBitSelect(VT, Amt, M, R);
18988
18989       // a += a
18990       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18991
18992       // r = VSELECT(r, shift(r, 2), a);
18993       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18994       R = SignBitSelect(VT, Amt, M, R);
18995
18996       // a += a
18997       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18998
18999       // return VSELECT(r, shift(r, 1), a);
19000       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19001       R = SignBitSelect(VT, Amt, M, R);
19002       return R;
19003     }
19004
19005     if (Op->getOpcode() == ISD::SRA) {
19006       // For SRA we need to unpack each byte to the higher byte of a i16 vector
19007       // so we can correctly sign extend. We don't care what happens to the
19008       // lower byte.
19009       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
19010       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
19011       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
19012       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
19013       ALo = DAG.getBitcast(ExtVT, ALo);
19014       AHi = DAG.getBitcast(ExtVT, AHi);
19015       RLo = DAG.getBitcast(ExtVT, RLo);
19016       RHi = DAG.getBitcast(ExtVT, RHi);
19017
19018       // r = VSELECT(r, shift(r, 4), a);
19019       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19020                                 DAG.getConstant(4, dl, ExtVT));
19021       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19022                                 DAG.getConstant(4, dl, ExtVT));
19023       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19024       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19025
19026       // a += a
19027       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19028       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19029
19030       // r = VSELECT(r, shift(r, 2), a);
19031       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19032                         DAG.getConstant(2, dl, ExtVT));
19033       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19034                         DAG.getConstant(2, dl, ExtVT));
19035       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19036       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19037
19038       // a += a
19039       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19040       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19041
19042       // r = VSELECT(r, shift(r, 1), a);
19043       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19044                         DAG.getConstant(1, dl, ExtVT));
19045       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19046                         DAG.getConstant(1, dl, ExtVT));
19047       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19048       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19049
19050       // Logical shift the result back to the lower byte, leaving a zero upper
19051       // byte
19052       // meaning that we can safely pack with PACKUSWB.
19053       RLo =
19054           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
19055       RHi =
19056           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
19057       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
19058     }
19059   }
19060
19061   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
19062   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
19063   // solution better.
19064   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
19065     MVT ExtVT = MVT::v8i32;
19066     unsigned ExtOpc =
19067         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
19068     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
19069     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
19070     return DAG.getNode(ISD::TRUNCATE, dl, VT,
19071                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
19072   }
19073
19074   if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
19075     MVT ExtVT = MVT::v8i32;
19076     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
19077     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
19078     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
19079     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
19080     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
19081     ALo = DAG.getBitcast(ExtVT, ALo);
19082     AHi = DAG.getBitcast(ExtVT, AHi);
19083     RLo = DAG.getBitcast(ExtVT, RLo);
19084     RHi = DAG.getBitcast(ExtVT, RHi);
19085     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
19086     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
19087     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
19088     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
19089     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
19090   }
19091
19092   if (VT == MVT::v8i16) {
19093     unsigned ShiftOpcode = Op->getOpcode();
19094
19095     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
19096       // On SSE41 targets we make use of the fact that VSELECT lowers
19097       // to PBLENDVB which selects bytes based just on the sign bit.
19098       if (Subtarget->hasSSE41()) {
19099         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
19100         V0 = DAG.getBitcast(ExtVT, V0);
19101         V1 = DAG.getBitcast(ExtVT, V1);
19102         Sel = DAG.getBitcast(ExtVT, Sel);
19103         return DAG.getBitcast(
19104             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
19105       }
19106       // On pre-SSE41 targets we splat the sign bit - a negative value will
19107       // set all bits of the lanes to true and VSELECT uses that in
19108       // its OR(AND(V0,C),AND(V1,~C)) lowering.
19109       SDValue C =
19110           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
19111       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
19112     };
19113
19114     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
19115     if (Subtarget->hasSSE41()) {
19116       // On SSE41 targets we need to replicate the shift mask in both
19117       // bytes for PBLENDVB.
19118       Amt = DAG.getNode(
19119           ISD::OR, dl, VT,
19120           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
19121           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
19122     } else {
19123       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
19124     }
19125
19126     // r = VSELECT(r, shift(r, 8), a);
19127     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
19128     R = SignBitSelect(Amt, M, R);
19129
19130     // a += a
19131     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19132
19133     // r = VSELECT(r, shift(r, 4), a);
19134     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
19135     R = SignBitSelect(Amt, M, R);
19136
19137     // a += a
19138     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19139
19140     // r = VSELECT(r, shift(r, 2), a);
19141     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
19142     R = SignBitSelect(Amt, M, R);
19143
19144     // a += a
19145     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19146
19147     // return VSELECT(r, shift(r, 1), a);
19148     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19149     R = SignBitSelect(Amt, M, R);
19150     return R;
19151   }
19152
19153   // Decompose 256-bit shifts into smaller 128-bit shifts.
19154   if (VT.is256BitVector()) {
19155     unsigned NumElems = VT.getVectorNumElements();
19156     MVT EltVT = VT.getVectorElementType();
19157     MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
19158
19159     // Extract the two vectors
19160     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
19161     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
19162
19163     // Recreate the shift amount vectors
19164     SDValue Amt1, Amt2;
19165     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
19166       // Constant shift amount
19167       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
19168       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
19169       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
19170
19171       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
19172       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
19173     } else {
19174       // Variable shift amount
19175       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
19176       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
19177     }
19178
19179     // Issue new vector shifts for the smaller types
19180     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
19181     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
19182
19183     // Concatenate the result back
19184     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
19185   }
19186
19187   return SDValue();
19188 }
19189
19190 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
19191                            SelectionDAG &DAG) {
19192   MVT VT = Op.getSimpleValueType();
19193   SDLoc DL(Op);
19194   SDValue R = Op.getOperand(0);
19195   SDValue Amt = Op.getOperand(1);
19196
19197   assert(VT.isVector() && "Custom lowering only for vector rotates!");
19198   assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
19199   assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
19200
19201   // XOP has 128-bit vector variable + immediate rotates.
19202   // +ve/-ve Amt = rotate left/right.
19203
19204   // Split 256-bit integers.
19205   if (VT.is256BitVector())
19206     return Lower256IntArith(Op, DAG);
19207
19208   assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
19209
19210   // Attempt to rotate by immediate.
19211   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
19212     if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
19213       uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
19214       assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
19215       return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
19216                          DAG.getConstant(RotateAmt, DL, MVT::i8));
19217     }
19218   }
19219
19220   // Use general rotate by variable (per-element).
19221   return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
19222 }
19223
19224 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
19225   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
19226   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
19227   // looks for this combo and may remove the "setcc" instruction if the "setcc"
19228   // has only one use.
19229   SDNode *N = Op.getNode();
19230   SDValue LHS = N->getOperand(0);
19231   SDValue RHS = N->getOperand(1);
19232   unsigned BaseOp = 0;
19233   unsigned Cond = 0;
19234   SDLoc DL(Op);
19235   switch (Op.getOpcode()) {
19236   default: llvm_unreachable("Unknown ovf instruction!");
19237   case ISD::SADDO:
19238     // A subtract of one will be selected as a INC. Note that INC doesn't
19239     // set CF, so we can't do this for UADDO.
19240     if (isOneConstant(RHS)) {
19241         BaseOp = X86ISD::INC;
19242         Cond = X86::COND_O;
19243         break;
19244       }
19245     BaseOp = X86ISD::ADD;
19246     Cond = X86::COND_O;
19247     break;
19248   case ISD::UADDO:
19249     BaseOp = X86ISD::ADD;
19250     Cond = X86::COND_B;
19251     break;
19252   case ISD::SSUBO:
19253     // A subtract of one will be selected as a DEC. Note that DEC doesn't
19254     // set CF, so we can't do this for USUBO.
19255     if (isOneConstant(RHS)) {
19256         BaseOp = X86ISD::DEC;
19257         Cond = X86::COND_O;
19258         break;
19259       }
19260     BaseOp = X86ISD::SUB;
19261     Cond = X86::COND_O;
19262     break;
19263   case ISD::USUBO:
19264     BaseOp = X86ISD::SUB;
19265     Cond = X86::COND_B;
19266     break;
19267   case ISD::SMULO:
19268     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
19269     Cond = X86::COND_O;
19270     break;
19271   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
19272     if (N->getValueType(0) == MVT::i8) {
19273       BaseOp = X86ISD::UMUL8;
19274       Cond = X86::COND_O;
19275       break;
19276     }
19277     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
19278                                  MVT::i32);
19279     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
19280
19281     SDValue SetCC =
19282       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19283                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
19284                   SDValue(Sum.getNode(), 2));
19285
19286     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19287   }
19288   }
19289
19290   // Also sets EFLAGS.
19291   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
19292   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
19293
19294   SDValue SetCC =
19295     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
19296                 DAG.getConstant(Cond, DL, MVT::i32),
19297                 SDValue(Sum.getNode(), 1));
19298
19299   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19300 }
19301
19302 /// Returns true if the operand type is exactly twice the native width, and
19303 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
19304 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
19305 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
19306 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
19307   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
19308
19309   if (OpWidth == 64)
19310     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
19311   else if (OpWidth == 128)
19312     return Subtarget->hasCmpxchg16b();
19313   else
19314     return false;
19315 }
19316
19317 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
19318   return needsCmpXchgNb(SI->getValueOperand()->getType());
19319 }
19320
19321 // Note: this turns large loads into lock cmpxchg8b/16b.
19322 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
19323 TargetLowering::AtomicExpansionKind
19324 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
19325   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
19326   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
19327                                                : AtomicExpansionKind::None;
19328 }
19329
19330 TargetLowering::AtomicExpansionKind
19331 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
19332   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19333   Type *MemType = AI->getType();
19334
19335   // If the operand is too big, we must see if cmpxchg8/16b is available
19336   // and default to library calls otherwise.
19337   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
19338     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
19339                                    : AtomicExpansionKind::None;
19340   }
19341
19342   AtomicRMWInst::BinOp Op = AI->getOperation();
19343   switch (Op) {
19344   default:
19345     llvm_unreachable("Unknown atomic operation");
19346   case AtomicRMWInst::Xchg:
19347   case AtomicRMWInst::Add:
19348   case AtomicRMWInst::Sub:
19349     // It's better to use xadd, xsub or xchg for these in all cases.
19350     return AtomicExpansionKind::None;
19351   case AtomicRMWInst::Or:
19352   case AtomicRMWInst::And:
19353   case AtomicRMWInst::Xor:
19354     // If the atomicrmw's result isn't actually used, we can just add a "lock"
19355     // prefix to a normal instruction for these operations.
19356     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
19357                             : AtomicExpansionKind::None;
19358   case AtomicRMWInst::Nand:
19359   case AtomicRMWInst::Max:
19360   case AtomicRMWInst::Min:
19361   case AtomicRMWInst::UMax:
19362   case AtomicRMWInst::UMin:
19363     // These always require a non-trivial set of data operations on x86. We must
19364     // use a cmpxchg loop.
19365     return AtomicExpansionKind::CmpXChg;
19366   }
19367 }
19368
19369 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19370   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19371   // no-sse2). There isn't any reason to disable it if the target processor
19372   // supports it.
19373   return Subtarget.hasSSE2() || Subtarget.is64Bit();
19374 }
19375
19376 LoadInst *
19377 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19378   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19379   Type *MemType = AI->getType();
19380   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19381   // there is no benefit in turning such RMWs into loads, and it is actually
19382   // harmful as it introduces a mfence.
19383   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19384     return nullptr;
19385
19386   auto Builder = IRBuilder<>(AI);
19387   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19388   auto SynchScope = AI->getSynchScope();
19389   // We must restrict the ordering to avoid generating loads with Release or
19390   // ReleaseAcquire orderings.
19391   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19392   auto Ptr = AI->getPointerOperand();
19393
19394   // Before the load we need a fence. Here is an example lifted from
19395   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19396   // is required:
19397   // Thread 0:
19398   //   x.store(1, relaxed);
19399   //   r1 = y.fetch_add(0, release);
19400   // Thread 1:
19401   //   y.fetch_add(42, acquire);
19402   //   r2 = x.load(relaxed);
19403   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19404   // lowered to just a load without a fence. A mfence flushes the store buffer,
19405   // making the optimization clearly correct.
19406   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19407   // otherwise, we might be able to be more aggressive on relaxed idempotent
19408   // rmw. In practice, they do not look useful, so we don't try to be
19409   // especially clever.
19410   if (SynchScope == SingleThread)
19411     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19412     // the IR level, so we must wrap it in an intrinsic.
19413     return nullptr;
19414
19415   if (!hasMFENCE(*Subtarget))
19416     // FIXME: it might make sense to use a locked operation here but on a
19417     // different cache-line to prevent cache-line bouncing. In practice it
19418     // is probably a small win, and x86 processors without mfence are rare
19419     // enough that we do not bother.
19420     return nullptr;
19421
19422   Function *MFence =
19423       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19424   Builder.CreateCall(MFence, {});
19425
19426   // Finally we can emit the atomic load.
19427   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19428           AI->getType()->getPrimitiveSizeInBits());
19429   Loaded->setAtomic(Order, SynchScope);
19430   AI->replaceAllUsesWith(Loaded);
19431   AI->eraseFromParent();
19432   return Loaded;
19433 }
19434
19435 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19436                                  SelectionDAG &DAG) {
19437   SDLoc dl(Op);
19438   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19439     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19440   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19441     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19442
19443   // The only fence that needs an instruction is a sequentially-consistent
19444   // cross-thread fence.
19445   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19446     if (hasMFENCE(*Subtarget))
19447       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19448
19449     SDValue Chain = Op.getOperand(0);
19450     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19451     SDValue Ops[] = {
19452       DAG.getRegister(X86::ESP, MVT::i32),     // Base
19453       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
19454       DAG.getRegister(0, MVT::i32),            // Index
19455       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
19456       DAG.getRegister(0, MVT::i32),            // Segment.
19457       Zero,
19458       Chain
19459     };
19460     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19461     return SDValue(Res, 0);
19462   }
19463
19464   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19465   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19466 }
19467
19468 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19469                              SelectionDAG &DAG) {
19470   MVT T = Op.getSimpleValueType();
19471   SDLoc DL(Op);
19472   unsigned Reg = 0;
19473   unsigned size = 0;
19474   switch(T.SimpleTy) {
19475   default: llvm_unreachable("Invalid value type!");
19476   case MVT::i8:  Reg = X86::AL;  size = 1; break;
19477   case MVT::i16: Reg = X86::AX;  size = 2; break;
19478   case MVT::i32: Reg = X86::EAX; size = 4; break;
19479   case MVT::i64:
19480     assert(Subtarget->is64Bit() && "Node not type legal!");
19481     Reg = X86::RAX; size = 8;
19482     break;
19483   }
19484   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19485                                   Op.getOperand(2), SDValue());
19486   SDValue Ops[] = { cpIn.getValue(0),
19487                     Op.getOperand(1),
19488                     Op.getOperand(3),
19489                     DAG.getTargetConstant(size, DL, MVT::i8),
19490                     cpIn.getValue(1) };
19491   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19492   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19493   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19494                                            Ops, T, MMO);
19495
19496   SDValue cpOut =
19497     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19498   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19499                                       MVT::i32, cpOut.getValue(2));
19500   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19501                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19502                                 EFLAGS);
19503
19504   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19505   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19506   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19507   return SDValue();
19508 }
19509
19510 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19511                             SelectionDAG &DAG) {
19512   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19513   MVT DstVT = Op.getSimpleValueType();
19514
19515   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19516     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19517     if (DstVT != MVT::f64)
19518       // This conversion needs to be expanded.
19519       return SDValue();
19520
19521     SDValue InVec = Op->getOperand(0);
19522     SDLoc dl(Op);
19523     unsigned NumElts = SrcVT.getVectorNumElements();
19524     MVT SVT = SrcVT.getVectorElementType();
19525
19526     // Widen the vector in input in the case of MVT::v2i32.
19527     // Example: from MVT::v2i32 to MVT::v4i32.
19528     SmallVector<SDValue, 16> Elts;
19529     for (unsigned i = 0, e = NumElts; i != e; ++i)
19530       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19531                                  DAG.getIntPtrConstant(i, dl)));
19532
19533     // Explicitly mark the extra elements as Undef.
19534     Elts.append(NumElts, DAG.getUNDEF(SVT));
19535
19536     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19537     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19538     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19539     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19540                        DAG.getIntPtrConstant(0, dl));
19541   }
19542
19543   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19544          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19545   assert((DstVT == MVT::i64 ||
19546           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19547          "Unexpected custom BITCAST");
19548   // i64 <=> MMX conversions are Legal.
19549   if (SrcVT==MVT::i64 && DstVT.isVector())
19550     return Op;
19551   if (DstVT==MVT::i64 && SrcVT.isVector())
19552     return Op;
19553   // MMX <=> MMX conversions are Legal.
19554   if (SrcVT.isVector() && DstVT.isVector())
19555     return Op;
19556   // All other conversions need to be expanded.
19557   return SDValue();
19558 }
19559
19560 /// Compute the horizontal sum of bytes in V for the elements of VT.
19561 ///
19562 /// Requires V to be a byte vector and VT to be an integer vector type with
19563 /// wider elements than V's type. The width of the elements of VT determines
19564 /// how many bytes of V are summed horizontally to produce each element of the
19565 /// result.
19566 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19567                                       const X86Subtarget *Subtarget,
19568                                       SelectionDAG &DAG) {
19569   SDLoc DL(V);
19570   MVT ByteVecVT = V.getSimpleValueType();
19571   MVT EltVT = VT.getVectorElementType();
19572   int NumElts = VT.getVectorNumElements();
19573   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19574          "Expected value to have byte element type.");
19575   assert(EltVT != MVT::i8 &&
19576          "Horizontal byte sum only makes sense for wider elements!");
19577   unsigned VecSize = VT.getSizeInBits();
19578   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19579
19580   // PSADBW instruction horizontally add all bytes and leave the result in i64
19581   // chunks, thus directly computes the pop count for v2i64 and v4i64.
19582   if (EltVT == MVT::i64) {
19583     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19584     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19585     V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
19586     return DAG.getBitcast(VT, V);
19587   }
19588
19589   if (EltVT == MVT::i32) {
19590     // We unpack the low half and high half into i32s interleaved with zeros so
19591     // that we can use PSADBW to horizontally sum them. The most useful part of
19592     // this is that it lines up the results of two PSADBW instructions to be
19593     // two v2i64 vectors which concatenated are the 4 population counts. We can
19594     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19595     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19596     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19597     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19598
19599     // Do the horizontal sums into two v2i64s.
19600     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19601     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19602     Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19603                       DAG.getBitcast(ByteVecVT, Low), Zeros);
19604     High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19605                        DAG.getBitcast(ByteVecVT, High), Zeros);
19606
19607     // Merge them together.
19608     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19609     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19610                     DAG.getBitcast(ShortVecVT, Low),
19611                     DAG.getBitcast(ShortVecVT, High));
19612
19613     return DAG.getBitcast(VT, V);
19614   }
19615
19616   // The only element type left is i16.
19617   assert(EltVT == MVT::i16 && "Unknown how to handle type");
19618
19619   // To obtain pop count for each i16 element starting from the pop count for
19620   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19621   // right by 8. It is important to shift as i16s as i8 vector shift isn't
19622   // directly supported.
19623   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19624   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19625   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19626   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19627                   DAG.getBitcast(ByteVecVT, V));
19628   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19629 }
19630
19631 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19632                                         const X86Subtarget *Subtarget,
19633                                         SelectionDAG &DAG) {
19634   MVT VT = Op.getSimpleValueType();
19635   MVT EltVT = VT.getVectorElementType();
19636   unsigned VecSize = VT.getSizeInBits();
19637
19638   // Implement a lookup table in register by using an algorithm based on:
19639   // http://wm.ite.pl/articles/sse-popcount.html
19640   //
19641   // The general idea is that every lower byte nibble in the input vector is an
19642   // index into a in-register pre-computed pop count table. We then split up the
19643   // input vector in two new ones: (1) a vector with only the shifted-right
19644   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19645   // masked out higher ones) for each byte. PSHUB is used separately with both
19646   // to index the in-register table. Next, both are added and the result is a
19647   // i8 vector where each element contains the pop count for input byte.
19648   //
19649   // To obtain the pop count for elements != i8, we follow up with the same
19650   // approach and use additional tricks as described below.
19651   //
19652   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19653                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19654                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19655                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19656
19657   int NumByteElts = VecSize / 8;
19658   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19659   SDValue In = DAG.getBitcast(ByteVecVT, Op);
19660   SmallVector<SDValue, 16> LUTVec;
19661   for (int i = 0; i < NumByteElts; ++i)
19662     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19663   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19664   SmallVector<SDValue, 16> Mask0F(NumByteElts,
19665                                   DAG.getConstant(0x0F, DL, MVT::i8));
19666   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19667
19668   // High nibbles
19669   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19670   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19671   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19672
19673   // Low nibbles
19674   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19675
19676   // The input vector is used as the shuffle mask that index elements into the
19677   // LUT. After counting low and high nibbles, add the vector to obtain the
19678   // final pop count per i8 element.
19679   SDValue HighPopCnt =
19680       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19681   SDValue LowPopCnt =
19682       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19683   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19684
19685   if (EltVT == MVT::i8)
19686     return PopCnt;
19687
19688   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19689 }
19690
19691 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19692                                        const X86Subtarget *Subtarget,
19693                                        SelectionDAG &DAG) {
19694   MVT VT = Op.getSimpleValueType();
19695   assert(VT.is128BitVector() &&
19696          "Only 128-bit vector bitmath lowering supported.");
19697
19698   int VecSize = VT.getSizeInBits();
19699   MVT EltVT = VT.getVectorElementType();
19700   int Len = EltVT.getSizeInBits();
19701
19702   // This is the vectorized version of the "best" algorithm from
19703   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19704   // with a minor tweak to use a series of adds + shifts instead of vector
19705   // multiplications. Implemented for all integer vector types. We only use
19706   // this when we don't have SSSE3 which allows a LUT-based lowering that is
19707   // much faster, even faster than using native popcnt instructions.
19708
19709   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19710     MVT VT = V.getSimpleValueType();
19711     SmallVector<SDValue, 32> Shifters(
19712         VT.getVectorNumElements(),
19713         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19714     return DAG.getNode(OpCode, DL, VT, V,
19715                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19716   };
19717   auto GetMask = [&](SDValue V, APInt Mask) {
19718     MVT VT = V.getSimpleValueType();
19719     SmallVector<SDValue, 32> Masks(
19720         VT.getVectorNumElements(),
19721         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19722     return DAG.getNode(ISD::AND, DL, VT, V,
19723                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19724   };
19725
19726   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19727   // x86, so set the SRL type to have elements at least i16 wide. This is
19728   // correct because all of our SRLs are followed immediately by a mask anyways
19729   // that handles any bits that sneak into the high bits of the byte elements.
19730   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19731
19732   SDValue V = Op;
19733
19734   // v = v - ((v >> 1) & 0x55555555...)
19735   SDValue Srl =
19736       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19737   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19738   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19739
19740   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19741   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19742   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19743   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19744   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19745
19746   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19747   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19748   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19749   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19750
19751   // At this point, V contains the byte-wise population count, and we are
19752   // merely doing a horizontal sum if necessary to get the wider element
19753   // counts.
19754   if (EltVT == MVT::i8)
19755     return V;
19756
19757   return LowerHorizontalByteSum(
19758       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19759       DAG);
19760 }
19761
19762 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19763                                 SelectionDAG &DAG) {
19764   MVT VT = Op.getSimpleValueType();
19765   // FIXME: Need to add AVX-512 support here!
19766   assert((VT.is256BitVector() || VT.is128BitVector()) &&
19767          "Unknown CTPOP type to handle");
19768   SDLoc DL(Op.getNode());
19769   SDValue Op0 = Op.getOperand(0);
19770
19771   if (!Subtarget->hasSSSE3()) {
19772     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19773     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19774     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19775   }
19776
19777   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19778     unsigned NumElems = VT.getVectorNumElements();
19779
19780     // Extract each 128-bit vector, compute pop count and concat the result.
19781     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19782     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19783
19784     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19785                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19786                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19787   }
19788
19789   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19790 }
19791
19792 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19793                           SelectionDAG &DAG) {
19794   assert(Op.getSimpleValueType().isVector() &&
19795          "We only do custom lowering for vector population count.");
19796   return LowerVectorCTPOP(Op, Subtarget, DAG);
19797 }
19798
19799 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19800   SDNode *Node = Op.getNode();
19801   SDLoc dl(Node);
19802   EVT T = Node->getValueType(0);
19803   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19804                               DAG.getConstant(0, dl, T), Node->getOperand(2));
19805   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19806                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19807                        Node->getOperand(0),
19808                        Node->getOperand(1), negOp,
19809                        cast<AtomicSDNode>(Node)->getMemOperand(),
19810                        cast<AtomicSDNode>(Node)->getOrdering(),
19811                        cast<AtomicSDNode>(Node)->getSynchScope());
19812 }
19813
19814 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19815   SDNode *Node = Op.getNode();
19816   SDLoc dl(Node);
19817   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19818
19819   // Convert seq_cst store -> xchg
19820   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19821   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19822   //        (The only way to get a 16-byte store is cmpxchg16b)
19823   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19824   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19825       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19826     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19827                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19828                                  Node->getOperand(0),
19829                                  Node->getOperand(1), Node->getOperand(2),
19830                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19831                                  cast<AtomicSDNode>(Node)->getOrdering(),
19832                                  cast<AtomicSDNode>(Node)->getSynchScope());
19833     return Swap.getValue(1);
19834   }
19835   // Other atomic stores have a simple pattern.
19836   return Op;
19837 }
19838
19839 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19840   MVT VT = Op.getNode()->getSimpleValueType(0);
19841
19842   // Let legalize expand this if it isn't a legal type yet.
19843   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19844     return SDValue();
19845
19846   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19847
19848   unsigned Opc;
19849   bool ExtraOp = false;
19850   switch (Op.getOpcode()) {
19851   default: llvm_unreachable("Invalid code");
19852   case ISD::ADDC: Opc = X86ISD::ADD; break;
19853   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19854   case ISD::SUBC: Opc = X86ISD::SUB; break;
19855   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19856   }
19857
19858   if (!ExtraOp)
19859     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19860                        Op.getOperand(1));
19861   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19862                      Op.getOperand(1), Op.getOperand(2));
19863 }
19864
19865 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19866                             SelectionDAG &DAG) {
19867   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19868
19869   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19870   // which returns the values as { float, float } (in XMM0) or
19871   // { double, double } (which is returned in XMM0, XMM1).
19872   SDLoc dl(Op);
19873   SDValue Arg = Op.getOperand(0);
19874   EVT ArgVT = Arg.getValueType();
19875   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19876
19877   TargetLowering::ArgListTy Args;
19878   TargetLowering::ArgListEntry Entry;
19879
19880   Entry.Node = Arg;
19881   Entry.Ty = ArgTy;
19882   Entry.isSExt = false;
19883   Entry.isZExt = false;
19884   Args.push_back(Entry);
19885
19886   bool isF64 = ArgVT == MVT::f64;
19887   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19888   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19889   // the results are returned via SRet in memory.
19890   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19891   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19892   SDValue Callee =
19893       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19894
19895   Type *RetTy = isF64
19896     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19897     : (Type*)VectorType::get(ArgTy, 4);
19898
19899   TargetLowering::CallLoweringInfo CLI(DAG);
19900   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19901     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19902
19903   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19904
19905   if (isF64)
19906     // Returned in xmm0 and xmm1.
19907     return CallResult.first;
19908
19909   // Returned in bits 0:31 and 32:64 xmm0.
19910   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19911                                CallResult.first, DAG.getIntPtrConstant(0, dl));
19912   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19913                                CallResult.first, DAG.getIntPtrConstant(1, dl));
19914   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19915   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19916 }
19917
19918 /// Widen a vector input to a vector of NVT.  The
19919 /// input vector must have the same element type as NVT.
19920 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
19921                             bool FillWithZeroes = false) {
19922   // Check if InOp already has the right width.
19923   MVT InVT = InOp.getSimpleValueType();
19924   if (InVT == NVT)
19925     return InOp;
19926
19927   if (InOp.isUndef())
19928     return DAG.getUNDEF(NVT);
19929
19930   assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
19931          "input and widen element type must match");
19932
19933   unsigned InNumElts = InVT.getVectorNumElements();
19934   unsigned WidenNumElts = NVT.getVectorNumElements();
19935   assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
19936          "Unexpected request for vector widening");
19937
19938   EVT EltVT = NVT.getVectorElementType();
19939
19940   SDLoc dl(InOp);
19941   if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
19942       InOp.getNumOperands() == 2) {
19943     SDValue N1 = InOp.getOperand(1);
19944     if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
19945         N1.isUndef()) {
19946       InOp = InOp.getOperand(0);
19947       InVT = InOp.getSimpleValueType();
19948       InNumElts = InVT.getVectorNumElements();
19949     }
19950   }
19951   if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
19952       ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
19953     SmallVector<SDValue, 16> Ops;
19954     for (unsigned i = 0; i < InNumElts; ++i)
19955       Ops.push_back(InOp.getOperand(i));
19956
19957     SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
19958       DAG.getUNDEF(EltVT);
19959     for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
19960       Ops.push_back(FillVal);
19961     return DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Ops);
19962   }
19963   SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
19964     DAG.getUNDEF(NVT);
19965   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
19966                      InOp, DAG.getIntPtrConstant(0, dl));
19967 }
19968
19969 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19970                              SelectionDAG &DAG) {
19971   assert(Subtarget->hasAVX512() &&
19972          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19973
19974   // X86 scatter kills mask register, so its type should be added to
19975   // the list of return values.
19976   // If the "scatter" has 2 return values, it is already handled.
19977   if (Op.getNode()->getNumValues() == 2)
19978     return Op;
19979
19980   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19981   SDValue Src = N->getValue();
19982   MVT VT = Src.getSimpleValueType();
19983   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19984   SDLoc dl(Op);
19985
19986   SDValue NewScatter;
19987   SDValue Index = N->getIndex();
19988   SDValue Mask = N->getMask();
19989   SDValue Chain = N->getChain();
19990   SDValue BasePtr = N->getBasePtr();
19991   MVT MemVT = N->getMemoryVT().getSimpleVT();
19992   MVT IndexVT = Index.getSimpleValueType();
19993   MVT MaskVT = Mask.getSimpleValueType();
19994
19995   if (MemVT.getScalarSizeInBits() < VT.getScalarSizeInBits()) {
19996     // The v2i32 value was promoted to v2i64.
19997     // Now we "redo" the type legalizer's work and widen the original
19998     // v2i32 value to v4i32. The original v2i32 is retrieved from v2i64
19999     // with a shuffle.
20000     assert((MemVT == MVT::v2i32 && VT == MVT::v2i64) &&
20001            "Unexpected memory type");
20002     int ShuffleMask[] = {0, 2, -1, -1};
20003     Src = DAG.getVectorShuffle(MVT::v4i32, dl, DAG.getBitcast(MVT::v4i32, Src),
20004                                DAG.getUNDEF(MVT::v4i32), ShuffleMask);
20005     // Now we have 4 elements instead of 2.
20006     // Expand the index.
20007     MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), 4);
20008     Index = ExtendToType(Index, NewIndexVT, DAG);
20009
20010     // Expand the mask with zeroes
20011     // Mask may be <2 x i64> or <2 x i1> at this moment
20012     assert((MaskVT == MVT::v2i1 || MaskVT == MVT::v2i64) &&
20013            "Unexpected mask type");
20014     MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), 4);
20015     Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20016     VT = MVT::v4i32;
20017   }
20018
20019   unsigned NumElts = VT.getVectorNumElements();
20020   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20021       !Index.getSimpleValueType().is512BitVector()) {
20022     // AVX512F supports only 512-bit vectors. Or data or index should
20023     // be 512 bit wide. If now the both index and data are 256-bit, but
20024     // the vector contains 8 elements, we just sign-extend the index
20025     if (IndexVT == MVT::v8i32)
20026       // Just extend index
20027       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20028     else {
20029       // The minimal number of elts in scatter is 8
20030       NumElts = 8;
20031       // Index
20032       MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20033       // Use original index here, do not modify the index twice
20034       Index = ExtendToType(N->getIndex(), NewIndexVT, DAG);
20035       if (IndexVT.getScalarType() == MVT::i32)
20036         Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20037
20038       // Mask
20039       // At this point we have promoted mask operand
20040       assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20041       MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20042       // Use the original mask here, do not modify the mask twice
20043       Mask = ExtendToType(N->getMask(), ExtMaskVT, DAG, true);
20044
20045       // The value that should be stored
20046       MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20047       Src = ExtendToType(Src, NewVT, DAG);
20048     }
20049   }
20050   // If the mask is "wide" at this point - truncate it to i1 vector
20051   MVT BitMaskVT = MVT::getVectorVT(MVT::i1, NumElts);
20052   Mask = DAG.getNode(ISD::TRUNCATE, dl, BitMaskVT, Mask);
20053
20054   // The mask is killed by scatter, add it to the values
20055   SDVTList VTs = DAG.getVTList(BitMaskVT, MVT::Other);
20056   SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index};
20057   NewScatter = DAG.getMaskedScatter(VTs, N->getMemoryVT(), dl, Ops,
20058                                     N->getMemOperand());
20059   DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
20060   return SDValue(NewScatter.getNode(), 0);
20061 }
20062
20063 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget *Subtarget,
20064                           SelectionDAG &DAG) {
20065
20066   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
20067   MVT VT = Op.getSimpleValueType();
20068   SDValue Mask = N->getMask();
20069   SDLoc dl(Op);
20070
20071   if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20072       !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20073     // This operation is legal for targets with VLX, but without
20074     // VLX the vector should be widened to 512 bit
20075     unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20076     MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20077     MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20078     SDValue Src0 = N->getSrc0();
20079     Src0 = ExtendToType(Src0, WideDataVT, DAG);
20080     Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20081     SDValue NewLoad = DAG.getMaskedLoad(WideDataVT, dl, N->getChain(),
20082                                         N->getBasePtr(), Mask, Src0,
20083                                         N->getMemoryVT(), N->getMemOperand(),
20084                                         N->getExtensionType());
20085
20086     SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20087                                  NewLoad.getValue(0),
20088                                  DAG.getIntPtrConstant(0, dl));
20089     SDValue RetOps[] = {Exract, NewLoad.getValue(1)};
20090     return DAG.getMergeValues(RetOps, dl);
20091   }
20092   return Op;
20093 }
20094
20095 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget *Subtarget,
20096                            SelectionDAG &DAG) {
20097   MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
20098   SDValue DataToStore = N->getValue();
20099   MVT VT = DataToStore.getSimpleValueType();
20100   SDValue Mask = N->getMask();
20101   SDLoc dl(Op);
20102
20103   if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20104       !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20105     // This operation is legal for targets with VLX, but without
20106     // VLX the vector should be widened to 512 bit
20107     unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20108     MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20109     MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20110     DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
20111     Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20112     return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
20113                               Mask, N->getMemoryVT(), N->getMemOperand(),
20114                               N->isTruncatingStore());
20115   }
20116   return Op;
20117 }
20118
20119 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
20120                             SelectionDAG &DAG) {
20121   assert(Subtarget->hasAVX512() &&
20122          "MGATHER/MSCATTER are supported on AVX-512 arch only");
20123
20124   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
20125   SDLoc dl(Op);
20126   MVT VT = Op.getSimpleValueType();
20127   SDValue Index = N->getIndex();
20128   SDValue Mask = N->getMask();
20129   SDValue Src0 = N->getValue();
20130   MVT IndexVT = Index.getSimpleValueType();
20131   MVT MaskVT = Mask.getSimpleValueType();
20132
20133   unsigned NumElts = VT.getVectorNumElements();
20134   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
20135
20136   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20137       !Index.getSimpleValueType().is512BitVector()) {
20138     // AVX512F supports only 512-bit vectors. Or data or index should
20139     // be 512 bit wide. If now the both index and data are 256-bit, but
20140     // the vector contains 8 elements, we just sign-extend the index
20141     if (NumElts == 8) {
20142       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20143       SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
20144                         N->getOperand(3), Index };
20145       DAG.UpdateNodeOperands(N, Ops);
20146       return Op;
20147     }
20148
20149     // Minimal number of elements in Gather
20150     NumElts = 8;
20151     // Index
20152     MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20153     Index = ExtendToType(Index, NewIndexVT, DAG);
20154     if (IndexVT.getScalarType() == MVT::i32)
20155       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20156
20157     // Mask
20158     MVT MaskBitVT = MVT::getVectorVT(MVT::i1, NumElts);
20159     // At this point we have promoted mask operand
20160     assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20161     MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20162     Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20163     Mask = DAG.getNode(ISD::TRUNCATE, dl, MaskBitVT, Mask);
20164
20165     // The pass-thru value
20166     MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20167     Src0 = ExtendToType(Src0, NewVT, DAG);
20168
20169     SDValue Ops[] = { N->getChain(), Src0, Mask, N->getBasePtr(), Index };
20170     SDValue NewGather = DAG.getMaskedGather(DAG.getVTList(NewVT, MVT::Other),
20171                                             N->getMemoryVT(), dl, Ops,
20172                                             N->getMemOperand());
20173     SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20174                                  NewGather.getValue(0),
20175                                  DAG.getIntPtrConstant(0, dl));
20176     SDValue RetOps[] = {Exract, NewGather.getValue(1)};
20177     return DAG.getMergeValues(RetOps, dl);
20178   }
20179   return Op;
20180 }
20181
20182 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
20183                                                     SelectionDAG &DAG) const {
20184   // TODO: Eventually, the lowering of these nodes should be informed by or
20185   // deferred to the GC strategy for the function in which they appear. For
20186   // now, however, they must be lowered to something. Since they are logically
20187   // no-ops in the case of a null GC strategy (or a GC strategy which does not
20188   // require special handling for these nodes), lower them as literal NOOPs for
20189   // the time being.
20190   SmallVector<SDValue, 2> Ops;
20191
20192   Ops.push_back(Op.getOperand(0));
20193   if (Op->getGluedNode())
20194     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20195
20196   SDLoc OpDL(Op);
20197   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20198   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20199
20200   return NOOP;
20201 }
20202
20203 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
20204                                                   SelectionDAG &DAG) const {
20205   // TODO: Eventually, the lowering of these nodes should be informed by or
20206   // deferred to the GC strategy for the function in which they appear. For
20207   // now, however, they must be lowered to something. Since they are logically
20208   // no-ops in the case of a null GC strategy (or a GC strategy which does not
20209   // require special handling for these nodes), lower them as literal NOOPs for
20210   // the time being.
20211   SmallVector<SDValue, 2> Ops;
20212
20213   Ops.push_back(Op.getOperand(0));
20214   if (Op->getGluedNode())
20215     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20216
20217   SDLoc OpDL(Op);
20218   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20219   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20220
20221   return NOOP;
20222 }
20223
20224 /// LowerOperation - Provide custom lowering hooks for some operations.
20225 ///
20226 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
20227   switch (Op.getOpcode()) {
20228   default: llvm_unreachable("Should not custom lower this!");
20229   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
20230   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
20231     return LowerCMP_SWAP(Op, Subtarget, DAG);
20232   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
20233   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
20234   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
20235   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
20236   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
20237   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
20238   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
20239   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
20240   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
20241   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
20242   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
20243   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
20244   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
20245   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
20246   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
20247   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
20248   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
20249   case ISD::SHL_PARTS:
20250   case ISD::SRA_PARTS:
20251   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
20252   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
20253   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
20254   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
20255   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
20256   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
20257   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
20258   case ISD::SIGN_EXTEND_VECTOR_INREG:
20259     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
20260   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
20261   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
20262   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
20263   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
20264   case ISD::FABS:
20265   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
20266   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
20267   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
20268   case ISD::SETCC:              return LowerSETCC(Op, DAG);
20269   case ISD::SETCCE:             return LowerSETCCE(Op, DAG);
20270   case ISD::SELECT:             return LowerSELECT(Op, DAG);
20271   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
20272   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
20273   case ISD::VASTART:            return LowerVASTART(Op, DAG);
20274   case ISD::VAARG:              return LowerVAARG(Op, DAG);
20275   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
20276   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
20277   case ISD::INTRINSIC_VOID:
20278   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
20279   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
20280   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
20281   case ISD::FRAME_TO_ARGS_OFFSET:
20282                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
20283   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
20284   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
20285   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
20286   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
20287   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
20288   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
20289   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
20290   case ISD::CTLZ:               return LowerCTLZ(Op, Subtarget, DAG);
20291   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
20292   case ISD::CTTZ:
20293   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
20294   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
20295   case ISD::UMUL_LOHI:
20296   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
20297   case ISD::ROTL:               return LowerRotate(Op, Subtarget, DAG);
20298   case ISD::SRA:
20299   case ISD::SRL:
20300   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
20301   case ISD::SADDO:
20302   case ISD::UADDO:
20303   case ISD::SSUBO:
20304   case ISD::USUBO:
20305   case ISD::SMULO:
20306   case ISD::UMULO:              return LowerXALUO(Op, DAG);
20307   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
20308   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
20309   case ISD::ADDC:
20310   case ISD::ADDE:
20311   case ISD::SUBC:
20312   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
20313   case ISD::ADD:                return LowerADD(Op, DAG);
20314   case ISD::SUB:                return LowerSUB(Op, DAG);
20315   case ISD::SMAX:
20316   case ISD::SMIN:
20317   case ISD::UMAX:
20318   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
20319   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
20320   case ISD::MLOAD:              return LowerMLOAD(Op, Subtarget, DAG);
20321   case ISD::MSTORE:             return LowerMSTORE(Op, Subtarget, DAG);
20322   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
20323   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
20324   case ISD::GC_TRANSITION_START:
20325                                 return LowerGC_TRANSITION_START(Op, DAG);
20326   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
20327   }
20328 }
20329
20330 /// ReplaceNodeResults - Replace a node with an illegal result type
20331 /// with a new node built out of custom code.
20332 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
20333                                            SmallVectorImpl<SDValue>&Results,
20334                                            SelectionDAG &DAG) const {
20335   SDLoc dl(N);
20336   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20337   switch (N->getOpcode()) {
20338   default:
20339     llvm_unreachable("Do not know how to custom type legalize this operation!");
20340   case X86ISD::AVG: {
20341     // Legalize types for X86ISD::AVG by expanding vectors.
20342     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20343
20344     auto InVT = N->getValueType(0);
20345     auto InVTSize = InVT.getSizeInBits();
20346     const unsigned RegSize =
20347         (InVTSize > 128) ? ((InVTSize > 256) ? 512 : 256) : 128;
20348     assert((!Subtarget->hasAVX512() || RegSize < 512) &&
20349            "512-bit vector requires AVX512");
20350     assert((!Subtarget->hasAVX2() || RegSize < 256) &&
20351            "256-bit vector requires AVX2");
20352
20353     auto ElemVT = InVT.getVectorElementType();
20354     auto RegVT = EVT::getVectorVT(*DAG.getContext(), ElemVT,
20355                                   RegSize / ElemVT.getSizeInBits());
20356     assert(RegSize % InVT.getSizeInBits() == 0);
20357     unsigned NumConcat = RegSize / InVT.getSizeInBits();
20358
20359     SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
20360     Ops[0] = N->getOperand(0);
20361     SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20362     Ops[0] = N->getOperand(1);
20363     SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20364
20365     SDValue Res = DAG.getNode(X86ISD::AVG, dl, RegVT, InVec0, InVec1);
20366     Results.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InVT, Res,
20367                                   DAG.getIntPtrConstant(0, dl)));
20368     return;
20369   }
20370   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
20371   case X86ISD::FMINC:
20372   case X86ISD::FMIN:
20373   case X86ISD::FMAXC:
20374   case X86ISD::FMAX: {
20375     EVT VT = N->getValueType(0);
20376     assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
20377     SDValue UNDEF = DAG.getUNDEF(VT);
20378     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20379                               N->getOperand(0), UNDEF);
20380     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20381                               N->getOperand(1), UNDEF);
20382     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
20383     return;
20384   }
20385   case ISD::SIGN_EXTEND_INREG:
20386   case ISD::ADDC:
20387   case ISD::ADDE:
20388   case ISD::SUBC:
20389   case ISD::SUBE:
20390     // We don't want to expand or promote these.
20391     return;
20392   case ISD::SDIV:
20393   case ISD::UDIV:
20394   case ISD::SREM:
20395   case ISD::UREM:
20396   case ISD::SDIVREM:
20397   case ISD::UDIVREM: {
20398     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
20399     Results.push_back(V);
20400     return;
20401   }
20402   case ISD::FP_TO_SINT:
20403   case ISD::FP_TO_UINT: {
20404     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
20405
20406     std::pair<SDValue,SDValue> Vals =
20407         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
20408     SDValue FIST = Vals.first, StackSlot = Vals.second;
20409     if (FIST.getNode()) {
20410       EVT VT = N->getValueType(0);
20411       // Return a load from the stack slot.
20412       if (StackSlot.getNode())
20413         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
20414                                       MachinePointerInfo(),
20415                                       false, false, false, 0));
20416       else
20417         Results.push_back(FIST);
20418     }
20419     return;
20420   }
20421   case ISD::UINT_TO_FP: {
20422     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20423     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
20424         N->getValueType(0) != MVT::v2f32)
20425       return;
20426     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
20427                                  N->getOperand(0));
20428     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
20429                                      MVT::f64);
20430     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
20431     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
20432                              DAG.getBitcast(MVT::v2i64, VBias));
20433     Or = DAG.getBitcast(MVT::v2f64, Or);
20434     // TODO: Are there any fast-math-flags to propagate here?
20435     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
20436     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
20437     return;
20438   }
20439   case ISD::FP_ROUND: {
20440     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
20441         return;
20442     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
20443     Results.push_back(V);
20444     return;
20445   }
20446   case ISD::FP_EXTEND: {
20447     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
20448     // No other ValueType for FP_EXTEND should reach this point.
20449     assert(N->getValueType(0) == MVT::v2f32 &&
20450            "Do not know how to legalize this Node");
20451     return;
20452   }
20453   case ISD::INTRINSIC_W_CHAIN: {
20454     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
20455     switch (IntNo) {
20456     default : llvm_unreachable("Do not know how to custom type "
20457                                "legalize this intrinsic operation!");
20458     case Intrinsic::x86_rdtsc:
20459       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20460                                      Results);
20461     case Intrinsic::x86_rdtscp:
20462       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
20463                                      Results);
20464     case Intrinsic::x86_rdpmc:
20465       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
20466     }
20467   }
20468   case ISD::INTRINSIC_WO_CHAIN: {
20469     if (SDValue V = LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), Subtarget, DAG))
20470       Results.push_back(V);
20471     return;
20472   }
20473   case ISD::READCYCLECOUNTER: {
20474     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20475                                    Results);
20476   }
20477   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
20478     EVT T = N->getValueType(0);
20479     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
20480     bool Regs64bit = T == MVT::i128;
20481     MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
20482     SDValue cpInL, cpInH;
20483     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20484                         DAG.getConstant(0, dl, HalfT));
20485     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20486                         DAG.getConstant(1, dl, HalfT));
20487     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
20488                              Regs64bit ? X86::RAX : X86::EAX,
20489                              cpInL, SDValue());
20490     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
20491                              Regs64bit ? X86::RDX : X86::EDX,
20492                              cpInH, cpInL.getValue(1));
20493     SDValue swapInL, swapInH;
20494     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20495                           DAG.getConstant(0, dl, HalfT));
20496     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20497                           DAG.getConstant(1, dl, HalfT));
20498     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
20499                                Regs64bit ? X86::RBX : X86::EBX,
20500                                swapInL, cpInH.getValue(1));
20501     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
20502                                Regs64bit ? X86::RCX : X86::ECX,
20503                                swapInH, swapInL.getValue(1));
20504     SDValue Ops[] = { swapInH.getValue(0),
20505                       N->getOperand(1),
20506                       swapInH.getValue(1) };
20507     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
20508     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
20509     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
20510                                   X86ISD::LCMPXCHG8_DAG;
20511     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
20512     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
20513                                         Regs64bit ? X86::RAX : X86::EAX,
20514                                         HalfT, Result.getValue(1));
20515     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
20516                                         Regs64bit ? X86::RDX : X86::EDX,
20517                                         HalfT, cpOutL.getValue(2));
20518     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
20519
20520     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
20521                                         MVT::i32, cpOutH.getValue(2));
20522     SDValue Success =
20523         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
20524                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
20525     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
20526
20527     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
20528     Results.push_back(Success);
20529     Results.push_back(EFLAGS.getValue(1));
20530     return;
20531   }
20532   case ISD::ATOMIC_SWAP:
20533   case ISD::ATOMIC_LOAD_ADD:
20534   case ISD::ATOMIC_LOAD_SUB:
20535   case ISD::ATOMIC_LOAD_AND:
20536   case ISD::ATOMIC_LOAD_OR:
20537   case ISD::ATOMIC_LOAD_XOR:
20538   case ISD::ATOMIC_LOAD_NAND:
20539   case ISD::ATOMIC_LOAD_MIN:
20540   case ISD::ATOMIC_LOAD_MAX:
20541   case ISD::ATOMIC_LOAD_UMIN:
20542   case ISD::ATOMIC_LOAD_UMAX:
20543   case ISD::ATOMIC_LOAD: {
20544     // Delegate to generic TypeLegalization. Situations we can really handle
20545     // should have already been dealt with by AtomicExpandPass.cpp.
20546     break;
20547   }
20548   case ISD::BITCAST: {
20549     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20550     EVT DstVT = N->getValueType(0);
20551     EVT SrcVT = N->getOperand(0)->getValueType(0);
20552
20553     if (SrcVT != MVT::f64 ||
20554         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
20555       return;
20556
20557     unsigned NumElts = DstVT.getVectorNumElements();
20558     EVT SVT = DstVT.getVectorElementType();
20559     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
20560     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
20561                                    MVT::v2f64, N->getOperand(0));
20562     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
20563
20564     if (ExperimentalVectorWideningLegalization) {
20565       // If we are legalizing vectors by widening, we already have the desired
20566       // legal vector type, just return it.
20567       Results.push_back(ToVecInt);
20568       return;
20569     }
20570
20571     SmallVector<SDValue, 8> Elts;
20572     for (unsigned i = 0, e = NumElts; i != e; ++i)
20573       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
20574                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
20575
20576     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
20577   }
20578   }
20579 }
20580
20581 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
20582   switch ((X86ISD::NodeType)Opcode) {
20583   case X86ISD::FIRST_NUMBER:       break;
20584   case X86ISD::BSF:                return "X86ISD::BSF";
20585   case X86ISD::BSR:                return "X86ISD::BSR";
20586   case X86ISD::SHLD:               return "X86ISD::SHLD";
20587   case X86ISD::SHRD:               return "X86ISD::SHRD";
20588   case X86ISD::FAND:               return "X86ISD::FAND";
20589   case X86ISD::FANDN:              return "X86ISD::FANDN";
20590   case X86ISD::FOR:                return "X86ISD::FOR";
20591   case X86ISD::FXOR:               return "X86ISD::FXOR";
20592   case X86ISD::FILD:               return "X86ISD::FILD";
20593   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
20594   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
20595   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
20596   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
20597   case X86ISD::FLD:                return "X86ISD::FLD";
20598   case X86ISD::FST:                return "X86ISD::FST";
20599   case X86ISD::CALL:               return "X86ISD::CALL";
20600   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
20601   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
20602   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
20603   case X86ISD::BT:                 return "X86ISD::BT";
20604   case X86ISD::CMP:                return "X86ISD::CMP";
20605   case X86ISD::COMI:               return "X86ISD::COMI";
20606   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
20607   case X86ISD::CMPM:               return "X86ISD::CMPM";
20608   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
20609   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
20610   case X86ISD::SETCC:              return "X86ISD::SETCC";
20611   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
20612   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
20613   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
20614   case X86ISD::CMOV:               return "X86ISD::CMOV";
20615   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
20616   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
20617   case X86ISD::IRET:               return "X86ISD::IRET";
20618   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
20619   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
20620   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
20621   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
20622   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
20623   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
20624   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
20625   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
20626   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
20627   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
20628   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
20629   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
20630   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
20631   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
20632   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
20633   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
20634   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
20635   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
20636   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
20637   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
20638   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
20639   case X86ISD::HADD:               return "X86ISD::HADD";
20640   case X86ISD::HSUB:               return "X86ISD::HSUB";
20641   case X86ISD::FHADD:              return "X86ISD::FHADD";
20642   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
20643   case X86ISD::ABS:                return "X86ISD::ABS";
20644   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
20645   case X86ISD::FMAX:               return "X86ISD::FMAX";
20646   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
20647   case X86ISD::FMIN:               return "X86ISD::FMIN";
20648   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
20649   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
20650   case X86ISD::FMINC:              return "X86ISD::FMINC";
20651   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
20652   case X86ISD::FRCP:               return "X86ISD::FRCP";
20653   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
20654   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
20655   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
20656   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
20657   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
20658   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
20659   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
20660   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
20661   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
20662   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
20663   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
20664   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
20665   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
20666   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
20667   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
20668   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
20669   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
20670   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
20671   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
20672   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
20673   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
20674   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
20675   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
20676   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
20677   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
20678   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
20679   case X86ISD::CVT2MASK:           return "X86ISD::CVT2MASK";
20680   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
20681   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
20682   case X86ISD::VSHL:               return "X86ISD::VSHL";
20683   case X86ISD::VSRL:               return "X86ISD::VSRL";
20684   case X86ISD::VSRA:               return "X86ISD::VSRA";
20685   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
20686   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
20687   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
20688   case X86ISD::CMPP:               return "X86ISD::CMPP";
20689   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
20690   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
20691   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
20692   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
20693   case X86ISD::ADD:                return "X86ISD::ADD";
20694   case X86ISD::SUB:                return "X86ISD::SUB";
20695   case X86ISD::ADC:                return "X86ISD::ADC";
20696   case X86ISD::SBB:                return "X86ISD::SBB";
20697   case X86ISD::SMUL:               return "X86ISD::SMUL";
20698   case X86ISD::UMUL:               return "X86ISD::UMUL";
20699   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
20700   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
20701   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20702   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20703   case X86ISD::INC:                return "X86ISD::INC";
20704   case X86ISD::DEC:                return "X86ISD::DEC";
20705   case X86ISD::OR:                 return "X86ISD::OR";
20706   case X86ISD::XOR:                return "X86ISD::XOR";
20707   case X86ISD::AND:                return "X86ISD::AND";
20708   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
20709   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
20710   case X86ISD::PTEST:              return "X86ISD::PTEST";
20711   case X86ISD::TESTP:              return "X86ISD::TESTP";
20712   case X86ISD::TESTM:              return "X86ISD::TESTM";
20713   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
20714   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
20715   case X86ISD::KTEST:              return "X86ISD::KTEST";
20716   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
20717   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
20718   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
20719   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
20720   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
20721   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
20722   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
20723   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
20724   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
20725   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
20726   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
20727   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
20728   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
20729   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
20730   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
20731   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
20732   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
20733   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
20734   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
20735   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
20736   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
20737   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
20738   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
20739   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
20740   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
20741   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
20742   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
20743   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
20744   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
20745   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
20746   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
20747   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
20748   case X86ISD::VPTERNLOG:          return "X86ISD::VPTERNLOG";
20749   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
20750   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
20751   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
20752   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
20753   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
20754   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
20755   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20756   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
20757   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
20758   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
20759   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
20760   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
20761   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
20762   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
20763   case X86ISD::SAHF:               return "X86ISD::SAHF";
20764   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
20765   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
20766   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
20767   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
20768   case X86ISD::VPROT:              return "X86ISD::VPROT";
20769   case X86ISD::VPROTI:             return "X86ISD::VPROTI";
20770   case X86ISD::VPSHA:              return "X86ISD::VPSHA";
20771   case X86ISD::VPSHL:              return "X86ISD::VPSHL";
20772   case X86ISD::VPCOM:              return "X86ISD::VPCOM";
20773   case X86ISD::VPCOMU:             return "X86ISD::VPCOMU";
20774   case X86ISD::FMADD:              return "X86ISD::FMADD";
20775   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
20776   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
20777   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
20778   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
20779   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
20780   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
20781   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
20782   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
20783   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
20784   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
20785   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
20786   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
20787   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
20788   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
20789   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
20790   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
20791   case X86ISD::XTEST:              return "X86ISD::XTEST";
20792   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
20793   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
20794   case X86ISD::SELECT:             return "X86ISD::SELECT";
20795   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
20796   case X86ISD::RCP28:              return "X86ISD::RCP28";
20797   case X86ISD::EXP2:               return "X86ISD::EXP2";
20798   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
20799   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
20800   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
20801   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
20802   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
20803   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
20804   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
20805   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
20806   case X86ISD::ADDS:               return "X86ISD::ADDS";
20807   case X86ISD::SUBS:               return "X86ISD::SUBS";
20808   case X86ISD::AVG:                return "X86ISD::AVG";
20809   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
20810   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
20811   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
20812   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
20813   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
20814   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
20815   case X86ISD::VFPCLASSS:          return "X86ISD::VFPCLASSS";
20816   }
20817   return nullptr;
20818 }
20819
20820 // isLegalAddressingMode - Return true if the addressing mode represented
20821 // by AM is legal for this target, for a load/store of the specified type.
20822 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20823                                               const AddrMode &AM, Type *Ty,
20824                                               unsigned AS) const {
20825   // X86 supports extremely general addressing modes.
20826   CodeModel::Model M = getTargetMachine().getCodeModel();
20827   Reloc::Model R = getTargetMachine().getRelocationModel();
20828
20829   // X86 allows a sign-extended 32-bit immediate field as a displacement.
20830   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20831     return false;
20832
20833   if (AM.BaseGV) {
20834     unsigned GVFlags =
20835       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20836
20837     // If a reference to this global requires an extra load, we can't fold it.
20838     if (isGlobalStubReference(GVFlags))
20839       return false;
20840
20841     // If BaseGV requires a register for the PIC base, we cannot also have a
20842     // BaseReg specified.
20843     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20844       return false;
20845
20846     // If lower 4G is not available, then we must use rip-relative addressing.
20847     if ((M != CodeModel::Small || R != Reloc::Static) &&
20848         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20849       return false;
20850   }
20851
20852   switch (AM.Scale) {
20853   case 0:
20854   case 1:
20855   case 2:
20856   case 4:
20857   case 8:
20858     // These scales always work.
20859     break;
20860   case 3:
20861   case 5:
20862   case 9:
20863     // These scales are formed with basereg+scalereg.  Only accept if there is
20864     // no basereg yet.
20865     if (AM.HasBaseReg)
20866       return false;
20867     break;
20868   default:  // Other stuff never works.
20869     return false;
20870   }
20871
20872   return true;
20873 }
20874
20875 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20876   unsigned Bits = Ty->getScalarSizeInBits();
20877
20878   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20879   // particularly cheaper than those without.
20880   if (Bits == 8)
20881     return false;
20882
20883   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20884   // variable shifts just as cheap as scalar ones.
20885   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20886     return false;
20887
20888   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20889   // fully general vector.
20890   return true;
20891 }
20892
20893 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20894   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20895     return false;
20896   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20897   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20898   return NumBits1 > NumBits2;
20899 }
20900
20901 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20902   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20903     return false;
20904
20905   if (!isTypeLegal(EVT::getEVT(Ty1)))
20906     return false;
20907
20908   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20909
20910   // Assuming the caller doesn't have a zeroext or signext return parameter,
20911   // truncation all the way down to i1 is valid.
20912   return true;
20913 }
20914
20915 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20916   return isInt<32>(Imm);
20917 }
20918
20919 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20920   // Can also use sub to handle negated immediates.
20921   return isInt<32>(Imm);
20922 }
20923
20924 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20925   if (!VT1.isInteger() || !VT2.isInteger())
20926     return false;
20927   unsigned NumBits1 = VT1.getSizeInBits();
20928   unsigned NumBits2 = VT2.getSizeInBits();
20929   return NumBits1 > NumBits2;
20930 }
20931
20932 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20933   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20934   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20935 }
20936
20937 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20938   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20939   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20940 }
20941
20942 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20943   EVT VT1 = Val.getValueType();
20944   if (isZExtFree(VT1, VT2))
20945     return true;
20946
20947   if (Val.getOpcode() != ISD::LOAD)
20948     return false;
20949
20950   if (!VT1.isSimple() || !VT1.isInteger() ||
20951       !VT2.isSimple() || !VT2.isInteger())
20952     return false;
20953
20954   switch (VT1.getSimpleVT().SimpleTy) {
20955   default: break;
20956   case MVT::i8:
20957   case MVT::i16:
20958   case MVT::i32:
20959     // X86 has 8, 16, and 32-bit zero-extending loads.
20960     return true;
20961   }
20962
20963   return false;
20964 }
20965
20966 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
20967
20968 bool
20969 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20970   if (!Subtarget->hasAnyFMA())
20971     return false;
20972
20973   VT = VT.getScalarType();
20974
20975   if (!VT.isSimple())
20976     return false;
20977
20978   switch (VT.getSimpleVT().SimpleTy) {
20979   case MVT::f32:
20980   case MVT::f64:
20981     return true;
20982   default:
20983     break;
20984   }
20985
20986   return false;
20987 }
20988
20989 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20990   // i16 instructions are longer (0x66 prefix) and potentially slower.
20991   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20992 }
20993
20994 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20995 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20996 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20997 /// are assumed to be legal.
20998 bool
20999 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
21000                                       EVT VT) const {
21001   if (!VT.isSimple())
21002     return false;
21003
21004   // Not for i1 vectors
21005   if (VT.getSimpleVT().getScalarType() == MVT::i1)
21006     return false;
21007
21008   // Very little shuffling can be done for 64-bit vectors right now.
21009   if (VT.getSimpleVT().getSizeInBits() == 64)
21010     return false;
21011
21012   // We only care that the types being shuffled are legal. The lowering can
21013   // handle any possible shuffle mask that results.
21014   return isTypeLegal(VT.getSimpleVT());
21015 }
21016
21017 bool
21018 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
21019                                           EVT VT) const {
21020   // Just delegate to the generic legality, clear masks aren't special.
21021   return isShuffleMaskLegal(Mask, VT);
21022 }
21023
21024 //===----------------------------------------------------------------------===//
21025 //                           X86 Scheduler Hooks
21026 //===----------------------------------------------------------------------===//
21027
21028 /// Utility function to emit xbegin specifying the start of an RTM region.
21029 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
21030                                      const TargetInstrInfo *TII) {
21031   DebugLoc DL = MI->getDebugLoc();
21032
21033   const BasicBlock *BB = MBB->getBasicBlock();
21034   MachineFunction::iterator I = ++MBB->getIterator();
21035
21036   // For the v = xbegin(), we generate
21037   //
21038   // thisMBB:
21039   //  xbegin sinkMBB
21040   //
21041   // mainMBB:
21042   //  eax = -1
21043   //
21044   // sinkMBB:
21045   //  v = eax
21046
21047   MachineBasicBlock *thisMBB = MBB;
21048   MachineFunction *MF = MBB->getParent();
21049   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21050   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21051   MF->insert(I, mainMBB);
21052   MF->insert(I, sinkMBB);
21053
21054   // Transfer the remainder of BB and its successor edges to sinkMBB.
21055   sinkMBB->splice(sinkMBB->begin(), MBB,
21056                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21057   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21058
21059   // thisMBB:
21060   //  xbegin sinkMBB
21061   //  # fallthrough to mainMBB
21062   //  # abortion to sinkMBB
21063   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
21064   thisMBB->addSuccessor(mainMBB);
21065   thisMBB->addSuccessor(sinkMBB);
21066
21067   // mainMBB:
21068   //  EAX = -1
21069   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
21070   mainMBB->addSuccessor(sinkMBB);
21071
21072   // sinkMBB:
21073   // EAX is live into the sinkMBB
21074   sinkMBB->addLiveIn(X86::EAX);
21075   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21076           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21077     .addReg(X86::EAX);
21078
21079   MI->eraseFromParent();
21080   return sinkMBB;
21081 }
21082
21083 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
21084 // or XMM0_V32I8 in AVX all of this code can be replaced with that
21085 // in the .td file.
21086 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
21087                                        const TargetInstrInfo *TII) {
21088   unsigned Opc;
21089   switch (MI->getOpcode()) {
21090   default: llvm_unreachable("illegal opcode!");
21091   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
21092   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
21093   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
21094   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
21095   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
21096   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
21097   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
21098   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
21099   }
21100
21101   DebugLoc dl = MI->getDebugLoc();
21102   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21103
21104   unsigned NumArgs = MI->getNumOperands();
21105   for (unsigned i = 1; i < NumArgs; ++i) {
21106     MachineOperand &Op = MI->getOperand(i);
21107     if (!(Op.isReg() && Op.isImplicit()))
21108       MIB.addOperand(Op);
21109   }
21110   if (MI->hasOneMemOperand())
21111     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21112
21113   BuildMI(*BB, MI, dl,
21114     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21115     .addReg(X86::XMM0);
21116
21117   MI->eraseFromParent();
21118   return BB;
21119 }
21120
21121 // FIXME: Custom handling because TableGen doesn't support multiple implicit
21122 // defs in an instruction pattern
21123 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
21124                                        const TargetInstrInfo *TII) {
21125   unsigned Opc;
21126   switch (MI->getOpcode()) {
21127   default: llvm_unreachable("illegal opcode!");
21128   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
21129   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
21130   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
21131   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
21132   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
21133   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
21134   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
21135   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
21136   }
21137
21138   DebugLoc dl = MI->getDebugLoc();
21139   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21140
21141   unsigned NumArgs = MI->getNumOperands(); // remove the results
21142   for (unsigned i = 1; i < NumArgs; ++i) {
21143     MachineOperand &Op = MI->getOperand(i);
21144     if (!(Op.isReg() && Op.isImplicit()))
21145       MIB.addOperand(Op);
21146   }
21147   if (MI->hasOneMemOperand())
21148     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21149
21150   BuildMI(*BB, MI, dl,
21151     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21152     .addReg(X86::ECX);
21153
21154   MI->eraseFromParent();
21155   return BB;
21156 }
21157
21158 static MachineBasicBlock *EmitWRPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21159                                      const X86Subtarget *Subtarget) {
21160   DebugLoc dl = MI->getDebugLoc();
21161   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21162
21163   // insert input VAL into EAX
21164   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
21165                            .addReg(MI->getOperand(0).getReg());
21166   // insert zero to ECX
21167   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21168                            .addReg(X86::ECX)
21169                            .addReg(X86::ECX);
21170   // insert zero to EDX
21171   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::EDX)
21172                            .addReg(X86::EDX)
21173                            .addReg(X86::EDX);
21174   // insert WRPKRU instruction
21175   BuildMI(*BB, MI, dl, TII->get(X86::WRPKRUr));
21176
21177   MI->eraseFromParent(); // The pseudo is gone now.
21178   return BB;
21179 }
21180
21181 static MachineBasicBlock *EmitRDPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21182                                      const X86Subtarget *Subtarget) {
21183   DebugLoc dl = MI->getDebugLoc();
21184   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21185
21186   // insert zero to ECX
21187   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21188                            .addReg(X86::ECX)
21189                            .addReg(X86::ECX);
21190   // insert RDPKRU instruction
21191   BuildMI(*BB, MI, dl, TII->get(X86::RDPKRUr));
21192   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21193                            .addReg(X86::EAX);
21194
21195   MI->eraseFromParent(); // The pseudo is gone now.
21196   return BB;
21197 }
21198
21199 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
21200                                       const X86Subtarget *Subtarget) {
21201   DebugLoc dl = MI->getDebugLoc();
21202   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21203   // Address into RAX/EAX, other two args into ECX, EDX.
21204   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
21205   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
21206   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
21207   for (int i = 0; i < X86::AddrNumOperands; ++i)
21208     MIB.addOperand(MI->getOperand(i));
21209
21210   unsigned ValOps = X86::AddrNumOperands;
21211   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
21212     .addReg(MI->getOperand(ValOps).getReg());
21213   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
21214     .addReg(MI->getOperand(ValOps+1).getReg());
21215
21216   // The instruction doesn't actually take any operands though.
21217   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
21218
21219   MI->eraseFromParent(); // The pseudo is gone now.
21220   return BB;
21221 }
21222
21223 MachineBasicBlock *
21224 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
21225                                                  MachineBasicBlock *MBB) const {
21226   // Emit va_arg instruction on X86-64.
21227
21228   // Operands to this pseudo-instruction:
21229   // 0  ) Output        : destination address (reg)
21230   // 1-5) Input         : va_list address (addr, i64mem)
21231   // 6  ) ArgSize       : Size (in bytes) of vararg type
21232   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
21233   // 8  ) Align         : Alignment of type
21234   // 9  ) EFLAGS (implicit-def)
21235
21236   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
21237   static_assert(X86::AddrNumOperands == 5,
21238                 "VAARG_64 assumes 5 address operands");
21239
21240   unsigned DestReg = MI->getOperand(0).getReg();
21241   MachineOperand &Base = MI->getOperand(1);
21242   MachineOperand &Scale = MI->getOperand(2);
21243   MachineOperand &Index = MI->getOperand(3);
21244   MachineOperand &Disp = MI->getOperand(4);
21245   MachineOperand &Segment = MI->getOperand(5);
21246   unsigned ArgSize = MI->getOperand(6).getImm();
21247   unsigned ArgMode = MI->getOperand(7).getImm();
21248   unsigned Align = MI->getOperand(8).getImm();
21249
21250   // Memory Reference
21251   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
21252   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21253   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21254
21255   // Machine Information
21256   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21257   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
21258   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
21259   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
21260   DebugLoc DL = MI->getDebugLoc();
21261
21262   // struct va_list {
21263   //   i32   gp_offset
21264   //   i32   fp_offset
21265   //   i64   overflow_area (address)
21266   //   i64   reg_save_area (address)
21267   // }
21268   // sizeof(va_list) = 24
21269   // alignment(va_list) = 8
21270
21271   unsigned TotalNumIntRegs = 6;
21272   unsigned TotalNumXMMRegs = 8;
21273   bool UseGPOffset = (ArgMode == 1);
21274   bool UseFPOffset = (ArgMode == 2);
21275   unsigned MaxOffset = TotalNumIntRegs * 8 +
21276                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
21277
21278   /* Align ArgSize to a multiple of 8 */
21279   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
21280   bool NeedsAlign = (Align > 8);
21281
21282   MachineBasicBlock *thisMBB = MBB;
21283   MachineBasicBlock *overflowMBB;
21284   MachineBasicBlock *offsetMBB;
21285   MachineBasicBlock *endMBB;
21286
21287   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
21288   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
21289   unsigned OffsetReg = 0;
21290
21291   if (!UseGPOffset && !UseFPOffset) {
21292     // If we only pull from the overflow region, we don't create a branch.
21293     // We don't need to alter control flow.
21294     OffsetDestReg = 0; // unused
21295     OverflowDestReg = DestReg;
21296
21297     offsetMBB = nullptr;
21298     overflowMBB = thisMBB;
21299     endMBB = thisMBB;
21300   } else {
21301     // First emit code to check if gp_offset (or fp_offset) is below the bound.
21302     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
21303     // If not, pull from overflow_area. (branch to overflowMBB)
21304     //
21305     //       thisMBB
21306     //         |     .
21307     //         |        .
21308     //     offsetMBB   overflowMBB
21309     //         |        .
21310     //         |     .
21311     //        endMBB
21312
21313     // Registers for the PHI in endMBB
21314     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
21315     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
21316
21317     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21318     MachineFunction *MF = MBB->getParent();
21319     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21320     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21321     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21322
21323     MachineFunction::iterator MBBIter = ++MBB->getIterator();
21324
21325     // Insert the new basic blocks
21326     MF->insert(MBBIter, offsetMBB);
21327     MF->insert(MBBIter, overflowMBB);
21328     MF->insert(MBBIter, endMBB);
21329
21330     // Transfer the remainder of MBB and its successor edges to endMBB.
21331     endMBB->splice(endMBB->begin(), thisMBB,
21332                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
21333     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
21334
21335     // Make offsetMBB and overflowMBB successors of thisMBB
21336     thisMBB->addSuccessor(offsetMBB);
21337     thisMBB->addSuccessor(overflowMBB);
21338
21339     // endMBB is a successor of both offsetMBB and overflowMBB
21340     offsetMBB->addSuccessor(endMBB);
21341     overflowMBB->addSuccessor(endMBB);
21342
21343     // Load the offset value into a register
21344     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21345     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
21346       .addOperand(Base)
21347       .addOperand(Scale)
21348       .addOperand(Index)
21349       .addDisp(Disp, UseFPOffset ? 4 : 0)
21350       .addOperand(Segment)
21351       .setMemRefs(MMOBegin, MMOEnd);
21352
21353     // Check if there is enough room left to pull this argument.
21354     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
21355       .addReg(OffsetReg)
21356       .addImm(MaxOffset + 8 - ArgSizeA8);
21357
21358     // Branch to "overflowMBB" if offset >= max
21359     // Fall through to "offsetMBB" otherwise
21360     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
21361       .addMBB(overflowMBB);
21362   }
21363
21364   // In offsetMBB, emit code to use the reg_save_area.
21365   if (offsetMBB) {
21366     assert(OffsetReg != 0);
21367
21368     // Read the reg_save_area address.
21369     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
21370     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
21371       .addOperand(Base)
21372       .addOperand(Scale)
21373       .addOperand(Index)
21374       .addDisp(Disp, 16)
21375       .addOperand(Segment)
21376       .setMemRefs(MMOBegin, MMOEnd);
21377
21378     // Zero-extend the offset
21379     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
21380       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
21381         .addImm(0)
21382         .addReg(OffsetReg)
21383         .addImm(X86::sub_32bit);
21384
21385     // Add the offset to the reg_save_area to get the final address.
21386     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
21387       .addReg(OffsetReg64)
21388       .addReg(RegSaveReg);
21389
21390     // Compute the offset for the next argument
21391     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21392     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
21393       .addReg(OffsetReg)
21394       .addImm(UseFPOffset ? 16 : 8);
21395
21396     // Store it back into the va_list.
21397     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
21398       .addOperand(Base)
21399       .addOperand(Scale)
21400       .addOperand(Index)
21401       .addDisp(Disp, UseFPOffset ? 4 : 0)
21402       .addOperand(Segment)
21403       .addReg(NextOffsetReg)
21404       .setMemRefs(MMOBegin, MMOEnd);
21405
21406     // Jump to endMBB
21407     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
21408       .addMBB(endMBB);
21409   }
21410
21411   //
21412   // Emit code to use overflow area
21413   //
21414
21415   // Load the overflow_area address into a register.
21416   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
21417   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
21418     .addOperand(Base)
21419     .addOperand(Scale)
21420     .addOperand(Index)
21421     .addDisp(Disp, 8)
21422     .addOperand(Segment)
21423     .setMemRefs(MMOBegin, MMOEnd);
21424
21425   // If we need to align it, do so. Otherwise, just copy the address
21426   // to OverflowDestReg.
21427   if (NeedsAlign) {
21428     // Align the overflow address
21429     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
21430     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
21431
21432     // aligned_addr = (addr + (align-1)) & ~(align-1)
21433     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
21434       .addReg(OverflowAddrReg)
21435       .addImm(Align-1);
21436
21437     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
21438       .addReg(TmpReg)
21439       .addImm(~(uint64_t)(Align-1));
21440   } else {
21441     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
21442       .addReg(OverflowAddrReg);
21443   }
21444
21445   // Compute the next overflow address after this argument.
21446   // (the overflow address should be kept 8-byte aligned)
21447   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
21448   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
21449     .addReg(OverflowDestReg)
21450     .addImm(ArgSizeA8);
21451
21452   // Store the new overflow address.
21453   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
21454     .addOperand(Base)
21455     .addOperand(Scale)
21456     .addOperand(Index)
21457     .addDisp(Disp, 8)
21458     .addOperand(Segment)
21459     .addReg(NextAddrReg)
21460     .setMemRefs(MMOBegin, MMOEnd);
21461
21462   // If we branched, emit the PHI to the front of endMBB.
21463   if (offsetMBB) {
21464     BuildMI(*endMBB, endMBB->begin(), DL,
21465             TII->get(X86::PHI), DestReg)
21466       .addReg(OffsetDestReg).addMBB(offsetMBB)
21467       .addReg(OverflowDestReg).addMBB(overflowMBB);
21468   }
21469
21470   // Erase the pseudo instruction
21471   MI->eraseFromParent();
21472
21473   return endMBB;
21474 }
21475
21476 MachineBasicBlock *
21477 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
21478                                                  MachineInstr *MI,
21479                                                  MachineBasicBlock *MBB) const {
21480   // Emit code to save XMM registers to the stack. The ABI says that the
21481   // number of registers to save is given in %al, so it's theoretically
21482   // possible to do an indirect jump trick to avoid saving all of them,
21483   // however this code takes a simpler approach and just executes all
21484   // of the stores if %al is non-zero. It's less code, and it's probably
21485   // easier on the hardware branch predictor, and stores aren't all that
21486   // expensive anyway.
21487
21488   // Create the new basic blocks. One block contains all the XMM stores,
21489   // and one block is the final destination regardless of whether any
21490   // stores were performed.
21491   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21492   MachineFunction *F = MBB->getParent();
21493   MachineFunction::iterator MBBIter = ++MBB->getIterator();
21494   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
21495   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
21496   F->insert(MBBIter, XMMSaveMBB);
21497   F->insert(MBBIter, EndMBB);
21498
21499   // Transfer the remainder of MBB and its successor edges to EndMBB.
21500   EndMBB->splice(EndMBB->begin(), MBB,
21501                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21502   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
21503
21504   // The original block will now fall through to the XMM save block.
21505   MBB->addSuccessor(XMMSaveMBB);
21506   // The XMMSaveMBB will fall through to the end block.
21507   XMMSaveMBB->addSuccessor(EndMBB);
21508
21509   // Now add the instructions.
21510   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21511   DebugLoc DL = MI->getDebugLoc();
21512
21513   unsigned CountReg = MI->getOperand(0).getReg();
21514   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
21515   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
21516
21517   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
21518     // If %al is 0, branch around the XMM save block.
21519     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
21520     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
21521     MBB->addSuccessor(EndMBB);
21522   }
21523
21524   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
21525   // that was just emitted, but clearly shouldn't be "saved".
21526   assert((MI->getNumOperands() <= 3 ||
21527           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
21528           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
21529          && "Expected last argument to be EFLAGS");
21530   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
21531   // In the XMM save block, save all the XMM argument registers.
21532   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
21533     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
21534     MachineMemOperand *MMO = F->getMachineMemOperand(
21535         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
21536         MachineMemOperand::MOStore,
21537         /*Size=*/16, /*Align=*/16);
21538     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
21539       .addFrameIndex(RegSaveFrameIndex)
21540       .addImm(/*Scale=*/1)
21541       .addReg(/*IndexReg=*/0)
21542       .addImm(/*Disp=*/Offset)
21543       .addReg(/*Segment=*/0)
21544       .addReg(MI->getOperand(i).getReg())
21545       .addMemOperand(MMO);
21546   }
21547
21548   MI->eraseFromParent();   // The pseudo instruction is gone now.
21549
21550   return EndMBB;
21551 }
21552
21553 // The EFLAGS operand of SelectItr might be missing a kill marker
21554 // because there were multiple uses of EFLAGS, and ISel didn't know
21555 // which to mark. Figure out whether SelectItr should have had a
21556 // kill marker, and set it if it should. Returns the correct kill
21557 // marker value.
21558 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
21559                                      MachineBasicBlock* BB,
21560                                      const TargetRegisterInfo* TRI) {
21561   // Scan forward through BB for a use/def of EFLAGS.
21562   MachineBasicBlock::iterator miI(std::next(SelectItr));
21563   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
21564     const MachineInstr& mi = *miI;
21565     if (mi.readsRegister(X86::EFLAGS))
21566       return false;
21567     if (mi.definesRegister(X86::EFLAGS))
21568       break; // Should have kill-flag - update below.
21569   }
21570
21571   // If we hit the end of the block, check whether EFLAGS is live into a
21572   // successor.
21573   if (miI == BB->end()) {
21574     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
21575                                           sEnd = BB->succ_end();
21576          sItr != sEnd; ++sItr) {
21577       MachineBasicBlock* succ = *sItr;
21578       if (succ->isLiveIn(X86::EFLAGS))
21579         return false;
21580     }
21581   }
21582
21583   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
21584   // out. SelectMI should have a kill flag on EFLAGS.
21585   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
21586   return true;
21587 }
21588
21589 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
21590 // together with other CMOV pseudo-opcodes into a single basic-block with
21591 // conditional jump around it.
21592 static bool isCMOVPseudo(MachineInstr *MI) {
21593   switch (MI->getOpcode()) {
21594   case X86::CMOV_FR32:
21595   case X86::CMOV_FR64:
21596   case X86::CMOV_GR8:
21597   case X86::CMOV_GR16:
21598   case X86::CMOV_GR32:
21599   case X86::CMOV_RFP32:
21600   case X86::CMOV_RFP64:
21601   case X86::CMOV_RFP80:
21602   case X86::CMOV_V2F64:
21603   case X86::CMOV_V2I64:
21604   case X86::CMOV_V4F32:
21605   case X86::CMOV_V4F64:
21606   case X86::CMOV_V4I64:
21607   case X86::CMOV_V16F32:
21608   case X86::CMOV_V8F32:
21609   case X86::CMOV_V8F64:
21610   case X86::CMOV_V8I64:
21611   case X86::CMOV_V8I1:
21612   case X86::CMOV_V16I1:
21613   case X86::CMOV_V32I1:
21614   case X86::CMOV_V64I1:
21615     return true;
21616
21617   default:
21618     return false;
21619   }
21620 }
21621
21622 MachineBasicBlock *
21623 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
21624                                      MachineBasicBlock *BB) const {
21625   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21626   DebugLoc DL = MI->getDebugLoc();
21627
21628   // To "insert" a SELECT_CC instruction, we actually have to insert the
21629   // diamond control-flow pattern.  The incoming instruction knows the
21630   // destination vreg to set, the condition code register to branch on, the
21631   // true/false values to select between, and a branch opcode to use.
21632   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21633   MachineFunction::iterator It = ++BB->getIterator();
21634
21635   //  thisMBB:
21636   //  ...
21637   //   TrueVal = ...
21638   //   cmpTY ccX, r1, r2
21639   //   bCC copy1MBB
21640   //   fallthrough --> copy0MBB
21641   MachineBasicBlock *thisMBB = BB;
21642   MachineFunction *F = BB->getParent();
21643
21644   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
21645   // as described above, by inserting a BB, and then making a PHI at the join
21646   // point to select the true and false operands of the CMOV in the PHI.
21647   //
21648   // The code also handles two different cases of multiple CMOV opcodes
21649   // in a row.
21650   //
21651   // Case 1:
21652   // In this case, there are multiple CMOVs in a row, all which are based on
21653   // the same condition setting (or the exact opposite condition setting).
21654   // In this case we can lower all the CMOVs using a single inserted BB, and
21655   // then make a number of PHIs at the join point to model the CMOVs. The only
21656   // trickiness here, is that in a case like:
21657   //
21658   // t2 = CMOV cond1 t1, f1
21659   // t3 = CMOV cond1 t2, f2
21660   //
21661   // when rewriting this into PHIs, we have to perform some renaming on the
21662   // temps since you cannot have a PHI operand refer to a PHI result earlier
21663   // in the same block.  The "simple" but wrong lowering would be:
21664   //
21665   // t2 = PHI t1(BB1), f1(BB2)
21666   // t3 = PHI t2(BB1), f2(BB2)
21667   //
21668   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
21669   // renaming is to note that on the path through BB1, t2 is really just a
21670   // copy of t1, and do that renaming, properly generating:
21671   //
21672   // t2 = PHI t1(BB1), f1(BB2)
21673   // t3 = PHI t1(BB1), f2(BB2)
21674   //
21675   // Case 2, we lower cascaded CMOVs such as
21676   //
21677   //   (CMOV (CMOV F, T, cc1), T, cc2)
21678   //
21679   // to two successives branches.  For that, we look for another CMOV as the
21680   // following instruction.
21681   //
21682   // Without this, we would add a PHI between the two jumps, which ends up
21683   // creating a few copies all around. For instance, for
21684   //
21685   //    (sitofp (zext (fcmp une)))
21686   //
21687   // we would generate:
21688   //
21689   //         ucomiss %xmm1, %xmm0
21690   //         movss  <1.0f>, %xmm0
21691   //         movaps  %xmm0, %xmm1
21692   //         jne     .LBB5_2
21693   //         xorps   %xmm1, %xmm1
21694   // .LBB5_2:
21695   //         jp      .LBB5_4
21696   //         movaps  %xmm1, %xmm0
21697   // .LBB5_4:
21698   //         retq
21699   //
21700   // because this custom-inserter would have generated:
21701   //
21702   //   A
21703   //   | \
21704   //   |  B
21705   //   | /
21706   //   C
21707   //   | \
21708   //   |  D
21709   //   | /
21710   //   E
21711   //
21712   // A: X = ...; Y = ...
21713   // B: empty
21714   // C: Z = PHI [X, A], [Y, B]
21715   // D: empty
21716   // E: PHI [X, C], [Z, D]
21717   //
21718   // If we lower both CMOVs in a single step, we can instead generate:
21719   //
21720   //   A
21721   //   | \
21722   //   |  C
21723   //   | /|
21724   //   |/ |
21725   //   |  |
21726   //   |  D
21727   //   | /
21728   //   E
21729   //
21730   // A: X = ...; Y = ...
21731   // D: empty
21732   // E: PHI [X, A], [X, C], [Y, D]
21733   //
21734   // Which, in our sitofp/fcmp example, gives us something like:
21735   //
21736   //         ucomiss %xmm1, %xmm0
21737   //         movss  <1.0f>, %xmm0
21738   //         jne     .LBB5_4
21739   //         jp      .LBB5_4
21740   //         xorps   %xmm0, %xmm0
21741   // .LBB5_4:
21742   //         retq
21743   //
21744   MachineInstr *CascadedCMOV = nullptr;
21745   MachineInstr *LastCMOV = MI;
21746   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21747   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21748   MachineBasicBlock::iterator NextMIIt =
21749       std::next(MachineBasicBlock::iterator(MI));
21750
21751   // Check for case 1, where there are multiple CMOVs with the same condition
21752   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
21753   // number of jumps the most.
21754
21755   if (isCMOVPseudo(MI)) {
21756     // See if we have a string of CMOVS with the same condition.
21757     while (NextMIIt != BB->end() &&
21758            isCMOVPseudo(NextMIIt) &&
21759            (NextMIIt->getOperand(3).getImm() == CC ||
21760             NextMIIt->getOperand(3).getImm() == OppCC)) {
21761       LastCMOV = &*NextMIIt;
21762       ++NextMIIt;
21763     }
21764   }
21765
21766   // This checks for case 2, but only do this if we didn't already find
21767   // case 1, as indicated by LastCMOV == MI.
21768   if (LastCMOV == MI &&
21769       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21770       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21771       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
21772     CascadedCMOV = &*NextMIIt;
21773   }
21774
21775   MachineBasicBlock *jcc1MBB = nullptr;
21776
21777   // If we have a cascaded CMOV, we lower it to two successive branches to
21778   // the same block.  EFLAGS is used by both, so mark it as live in the second.
21779   if (CascadedCMOV) {
21780     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21781     F->insert(It, jcc1MBB);
21782     jcc1MBB->addLiveIn(X86::EFLAGS);
21783   }
21784
21785   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21786   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21787   F->insert(It, copy0MBB);
21788   F->insert(It, sinkMBB);
21789
21790   // If the EFLAGS register isn't dead in the terminator, then claim that it's
21791   // live into the sink and copy blocks.
21792   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21793
21794   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21795   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21796       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21797     copy0MBB->addLiveIn(X86::EFLAGS);
21798     sinkMBB->addLiveIn(X86::EFLAGS);
21799   }
21800
21801   // Transfer the remainder of BB and its successor edges to sinkMBB.
21802   sinkMBB->splice(sinkMBB->begin(), BB,
21803                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21804   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21805
21806   // Add the true and fallthrough blocks as its successors.
21807   if (CascadedCMOV) {
21808     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21809     BB->addSuccessor(jcc1MBB);
21810
21811     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21812     // jump to the sinkMBB.
21813     jcc1MBB->addSuccessor(copy0MBB);
21814     jcc1MBB->addSuccessor(sinkMBB);
21815   } else {
21816     BB->addSuccessor(copy0MBB);
21817   }
21818
21819   // The true block target of the first (or only) branch is always sinkMBB.
21820   BB->addSuccessor(sinkMBB);
21821
21822   // Create the conditional branch instruction.
21823   unsigned Opc = X86::GetCondBranchFromCond(CC);
21824   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21825
21826   if (CascadedCMOV) {
21827     unsigned Opc2 = X86::GetCondBranchFromCond(
21828         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21829     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21830   }
21831
21832   //  copy0MBB:
21833   //   %FalseValue = ...
21834   //   # fallthrough to sinkMBB
21835   copy0MBB->addSuccessor(sinkMBB);
21836
21837   //  sinkMBB:
21838   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21839   //  ...
21840   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21841   MachineBasicBlock::iterator MIItEnd =
21842     std::next(MachineBasicBlock::iterator(LastCMOV));
21843   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21844   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21845   MachineInstrBuilder MIB;
21846
21847   // As we are creating the PHIs, we have to be careful if there is more than
21848   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
21849   // PHIs have to reference the individual true/false inputs from earlier PHIs.
21850   // That also means that PHI construction must work forward from earlier to
21851   // later, and that the code must maintain a mapping from earlier PHI's
21852   // destination registers, and the registers that went into the PHI.
21853
21854   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21855     unsigned DestReg = MIIt->getOperand(0).getReg();
21856     unsigned Op1Reg = MIIt->getOperand(1).getReg();
21857     unsigned Op2Reg = MIIt->getOperand(2).getReg();
21858
21859     // If this CMOV we are generating is the opposite condition from
21860     // the jump we generated, then we have to swap the operands for the
21861     // PHI that is going to be generated.
21862     if (MIIt->getOperand(3).getImm() == OppCC)
21863         std::swap(Op1Reg, Op2Reg);
21864
21865     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21866       Op1Reg = RegRewriteTable[Op1Reg].first;
21867
21868     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21869       Op2Reg = RegRewriteTable[Op2Reg].second;
21870
21871     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21872                   TII->get(X86::PHI), DestReg)
21873           .addReg(Op1Reg).addMBB(copy0MBB)
21874           .addReg(Op2Reg).addMBB(thisMBB);
21875
21876     // Add this PHI to the rewrite table.
21877     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21878   }
21879
21880   // If we have a cascaded CMOV, the second Jcc provides the same incoming
21881   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21882   if (CascadedCMOV) {
21883     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21884     // Copy the PHI result to the register defined by the second CMOV.
21885     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21886             DL, TII->get(TargetOpcode::COPY),
21887             CascadedCMOV->getOperand(0).getReg())
21888         .addReg(MI->getOperand(0).getReg());
21889     CascadedCMOV->eraseFromParent();
21890   }
21891
21892   // Now remove the CMOV(s).
21893   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
21894     (MIIt++)->eraseFromParent();
21895
21896   return sinkMBB;
21897 }
21898
21899 MachineBasicBlock *
21900 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
21901                                        MachineBasicBlock *BB) const {
21902   // Combine the following atomic floating-point modification pattern:
21903   //   a.store(reg OP a.load(acquire), release)
21904   // Transform them into:
21905   //   OPss (%gpr), %xmm
21906   //   movss %xmm, (%gpr)
21907   // Or sd equivalent for 64-bit operations.
21908   unsigned MOp, FOp;
21909   switch (MI->getOpcode()) {
21910   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
21911   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
21912   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
21913   }
21914   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21915   DebugLoc DL = MI->getDebugLoc();
21916   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
21917   MachineOperand MSrc = MI->getOperand(0);
21918   unsigned VSrc = MI->getOperand(5).getReg();
21919   const MachineOperand &Disp = MI->getOperand(3);
21920   MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
21921   bool hasDisp = Disp.isGlobal() || Disp.isImm();
21922   if (hasDisp && MSrc.isReg())
21923     MSrc.setIsKill(false);
21924   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
21925                                 .addOperand(/*Base=*/MSrc)
21926                                 .addImm(/*Scale=*/1)
21927                                 .addReg(/*Index=*/0)
21928                                 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21929                                 .addReg(0);
21930   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
21931                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
21932                           .addReg(VSrc)
21933                           .addOperand(/*Base=*/MSrc)
21934                           .addImm(/*Scale=*/1)
21935                           .addReg(/*Index=*/0)
21936                           .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21937                           .addReg(/*Segment=*/0);
21938   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
21939   MI->eraseFromParent(); // The pseudo instruction is gone now.
21940   return BB;
21941 }
21942
21943 MachineBasicBlock *
21944 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
21945                                         MachineBasicBlock *BB) const {
21946   MachineFunction *MF = BB->getParent();
21947   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21948   DebugLoc DL = MI->getDebugLoc();
21949   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21950
21951   assert(MF->shouldSplitStack());
21952
21953   const bool Is64Bit = Subtarget->is64Bit();
21954   const bool IsLP64 = Subtarget->isTarget64BitLP64();
21955
21956   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
21957   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
21958
21959   // BB:
21960   //  ... [Till the alloca]
21961   // If stacklet is not large enough, jump to mallocMBB
21962   //
21963   // bumpMBB:
21964   //  Allocate by subtracting from RSP
21965   //  Jump to continueMBB
21966   //
21967   // mallocMBB:
21968   //  Allocate by call to runtime
21969   //
21970   // continueMBB:
21971   //  ...
21972   //  [rest of original BB]
21973   //
21974
21975   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21976   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21977   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21978
21979   MachineRegisterInfo &MRI = MF->getRegInfo();
21980   const TargetRegisterClass *AddrRegClass =
21981       getRegClassFor(getPointerTy(MF->getDataLayout()));
21982
21983   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21984     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21985     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
21986     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
21987     sizeVReg = MI->getOperand(1).getReg(),
21988     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
21989
21990   MachineFunction::iterator MBBIter = ++BB->getIterator();
21991
21992   MF->insert(MBBIter, bumpMBB);
21993   MF->insert(MBBIter, mallocMBB);
21994   MF->insert(MBBIter, continueMBB);
21995
21996   continueMBB->splice(continueMBB->begin(), BB,
21997                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
21998   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
21999
22000   // Add code to the main basic block to check if the stack limit has been hit,
22001   // and if so, jump to mallocMBB otherwise to bumpMBB.
22002   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
22003   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
22004     .addReg(tmpSPVReg).addReg(sizeVReg);
22005   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
22006     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
22007     .addReg(SPLimitVReg);
22008   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
22009
22010   // bumpMBB simply decreases the stack pointer, since we know the current
22011   // stacklet has enough space.
22012   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
22013     .addReg(SPLimitVReg);
22014   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
22015     .addReg(SPLimitVReg);
22016   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22017
22018   // Calls into a routine in libgcc to allocate more space from the heap.
22019   const uint32_t *RegMask =
22020       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
22021   if (IsLP64) {
22022     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
22023       .addReg(sizeVReg);
22024     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22025       .addExternalSymbol("__morestack_allocate_stack_space")
22026       .addRegMask(RegMask)
22027       .addReg(X86::RDI, RegState::Implicit)
22028       .addReg(X86::RAX, RegState::ImplicitDefine);
22029   } else if (Is64Bit) {
22030     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
22031       .addReg(sizeVReg);
22032     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22033       .addExternalSymbol("__morestack_allocate_stack_space")
22034       .addRegMask(RegMask)
22035       .addReg(X86::EDI, RegState::Implicit)
22036       .addReg(X86::EAX, RegState::ImplicitDefine);
22037   } else {
22038     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
22039       .addImm(12);
22040     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
22041     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
22042       .addExternalSymbol("__morestack_allocate_stack_space")
22043       .addRegMask(RegMask)
22044       .addReg(X86::EAX, RegState::ImplicitDefine);
22045   }
22046
22047   if (!Is64Bit)
22048     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
22049       .addImm(16);
22050
22051   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
22052     .addReg(IsLP64 ? X86::RAX : X86::EAX);
22053   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22054
22055   // Set up the CFG correctly.
22056   BB->addSuccessor(bumpMBB);
22057   BB->addSuccessor(mallocMBB);
22058   mallocMBB->addSuccessor(continueMBB);
22059   bumpMBB->addSuccessor(continueMBB);
22060
22061   // Take care of the PHI nodes.
22062   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
22063           MI->getOperand(0).getReg())
22064     .addReg(mallocPtrVReg).addMBB(mallocMBB)
22065     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
22066
22067   // Delete the original pseudo instruction.
22068   MI->eraseFromParent();
22069
22070   // And we're done.
22071   return continueMBB;
22072 }
22073
22074 MachineBasicBlock *
22075 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
22076                                         MachineBasicBlock *BB) const {
22077   assert(!Subtarget->isTargetMachO());
22078   DebugLoc DL = MI->getDebugLoc();
22079   MachineInstr *ResumeMI = Subtarget->getFrameLowering()->emitStackProbe(
22080       *BB->getParent(), *BB, MI, DL, false);
22081   MachineBasicBlock *ResumeBB = ResumeMI->getParent();
22082   MI->eraseFromParent(); // The pseudo instruction is gone now.
22083   return ResumeBB;
22084 }
22085
22086 MachineBasicBlock *
22087 X86TargetLowering::EmitLoweredCatchRet(MachineInstr *MI,
22088                                        MachineBasicBlock *BB) const {
22089   MachineFunction *MF = BB->getParent();
22090   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22091   MachineBasicBlock *TargetMBB = MI->getOperand(0).getMBB();
22092   DebugLoc DL = MI->getDebugLoc();
22093
22094   assert(!isAsynchronousEHPersonality(
22095              classifyEHPersonality(MF->getFunction()->getPersonalityFn())) &&
22096          "SEH does not use catchret!");
22097
22098   // Only 32-bit EH needs to worry about manually restoring stack pointers.
22099   if (!Subtarget->is32Bit())
22100     return BB;
22101
22102   // C++ EH creates a new target block to hold the restore code, and wires up
22103   // the new block to the return destination with a normal JMP_4.
22104   MachineBasicBlock *RestoreMBB =
22105       MF->CreateMachineBasicBlock(BB->getBasicBlock());
22106   assert(BB->succ_size() == 1);
22107   MF->insert(std::next(BB->getIterator()), RestoreMBB);
22108   RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
22109   BB->addSuccessor(RestoreMBB);
22110   MI->getOperand(0).setMBB(RestoreMBB);
22111
22112   auto RestoreMBBI = RestoreMBB->begin();
22113   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
22114   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
22115   return BB;
22116 }
22117
22118 MachineBasicBlock *
22119 X86TargetLowering::EmitLoweredCatchPad(MachineInstr *MI,
22120                                        MachineBasicBlock *BB) const {
22121   MachineFunction *MF = BB->getParent();
22122   const Constant *PerFn = MF->getFunction()->getPersonalityFn();
22123   bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
22124   // Only 32-bit SEH requires special handling for catchpad.
22125   if (IsSEH && Subtarget->is32Bit()) {
22126     const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22127     DebugLoc DL = MI->getDebugLoc();
22128     BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
22129   }
22130   MI->eraseFromParent();
22131   return BB;
22132 }
22133
22134 MachineBasicBlock *
22135 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
22136                                       MachineBasicBlock *BB) const {
22137   // This is pretty easy.  We're taking the value that we received from
22138   // our load from the relocation, sticking it in either RDI (x86-64)
22139   // or EAX and doing an indirect call.  The return value will then
22140   // be in the normal return register.
22141   MachineFunction *F = BB->getParent();
22142   const X86InstrInfo *TII = Subtarget->getInstrInfo();
22143   DebugLoc DL = MI->getDebugLoc();
22144
22145   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
22146   assert(MI->getOperand(3).isGlobal() && "This should be a global");
22147
22148   // Get a register mask for the lowered call.
22149   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
22150   // proper register mask.
22151   const uint32_t *RegMask =
22152       Subtarget->is64Bit() ?
22153       Subtarget->getRegisterInfo()->getDarwinTLSCallPreservedMask() :
22154       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
22155   if (Subtarget->is64Bit()) {
22156     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22157                                       TII->get(X86::MOV64rm), X86::RDI)
22158     .addReg(X86::RIP)
22159     .addImm(0).addReg(0)
22160     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22161                       MI->getOperand(3).getTargetFlags())
22162     .addReg(0);
22163     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
22164     addDirectMem(MIB, X86::RDI);
22165     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
22166   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
22167     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22168                                       TII->get(X86::MOV32rm), X86::EAX)
22169     .addReg(0)
22170     .addImm(0).addReg(0)
22171     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22172                       MI->getOperand(3).getTargetFlags())
22173     .addReg(0);
22174     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22175     addDirectMem(MIB, X86::EAX);
22176     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22177   } else {
22178     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22179                                       TII->get(X86::MOV32rm), X86::EAX)
22180     .addReg(TII->getGlobalBaseReg(F))
22181     .addImm(0).addReg(0)
22182     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22183                       MI->getOperand(3).getTargetFlags())
22184     .addReg(0);
22185     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22186     addDirectMem(MIB, X86::EAX);
22187     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22188   }
22189
22190   MI->eraseFromParent(); // The pseudo instruction is gone now.
22191   return BB;
22192 }
22193
22194 MachineBasicBlock *
22195 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
22196                                     MachineBasicBlock *MBB) const {
22197   DebugLoc DL = MI->getDebugLoc();
22198   MachineFunction *MF = MBB->getParent();
22199   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22200   MachineRegisterInfo &MRI = MF->getRegInfo();
22201
22202   const BasicBlock *BB = MBB->getBasicBlock();
22203   MachineFunction::iterator I = ++MBB->getIterator();
22204
22205   // Memory Reference
22206   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22207   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22208
22209   unsigned DstReg;
22210   unsigned MemOpndSlot = 0;
22211
22212   unsigned CurOp = 0;
22213
22214   DstReg = MI->getOperand(CurOp++).getReg();
22215   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
22216   assert(RC->hasType(MVT::i32) && "Invalid destination!");
22217   unsigned mainDstReg = MRI.createVirtualRegister(RC);
22218   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
22219
22220   MemOpndSlot = CurOp;
22221
22222   MVT PVT = getPointerTy(MF->getDataLayout());
22223   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22224          "Invalid Pointer Size!");
22225
22226   // For v = setjmp(buf), we generate
22227   //
22228   // thisMBB:
22229   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
22230   //  SjLjSetup restoreMBB
22231   //
22232   // mainMBB:
22233   //  v_main = 0
22234   //
22235   // sinkMBB:
22236   //  v = phi(main, restore)
22237   //
22238   // restoreMBB:
22239   //  if base pointer being used, load it from frame
22240   //  v_restore = 1
22241
22242   MachineBasicBlock *thisMBB = MBB;
22243   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
22244   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
22245   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
22246   MF->insert(I, mainMBB);
22247   MF->insert(I, sinkMBB);
22248   MF->push_back(restoreMBB);
22249   restoreMBB->setHasAddressTaken();
22250
22251   MachineInstrBuilder MIB;
22252
22253   // Transfer the remainder of BB and its successor edges to sinkMBB.
22254   sinkMBB->splice(sinkMBB->begin(), MBB,
22255                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
22256   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
22257
22258   // thisMBB:
22259   unsigned PtrStoreOpc = 0;
22260   unsigned LabelReg = 0;
22261   const int64_t LabelOffset = 1 * PVT.getStoreSize();
22262   Reloc::Model RM = MF->getTarget().getRelocationModel();
22263   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
22264                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
22265
22266   // Prepare IP either in reg or imm.
22267   if (!UseImmLabel) {
22268     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
22269     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
22270     LabelReg = MRI.createVirtualRegister(PtrRC);
22271     if (Subtarget->is64Bit()) {
22272       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
22273               .addReg(X86::RIP)
22274               .addImm(0)
22275               .addReg(0)
22276               .addMBB(restoreMBB)
22277               .addReg(0);
22278     } else {
22279       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
22280       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
22281               .addReg(XII->getGlobalBaseReg(MF))
22282               .addImm(0)
22283               .addReg(0)
22284               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
22285               .addReg(0);
22286     }
22287   } else
22288     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
22289   // Store IP
22290   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
22291   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22292     if (i == X86::AddrDisp)
22293       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
22294     else
22295       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
22296   }
22297   if (!UseImmLabel)
22298     MIB.addReg(LabelReg);
22299   else
22300     MIB.addMBB(restoreMBB);
22301   MIB.setMemRefs(MMOBegin, MMOEnd);
22302   // Setup
22303   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
22304           .addMBB(restoreMBB);
22305
22306   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22307   MIB.addRegMask(RegInfo->getNoPreservedMask());
22308   thisMBB->addSuccessor(mainMBB);
22309   thisMBB->addSuccessor(restoreMBB);
22310
22311   // mainMBB:
22312   //  EAX = 0
22313   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
22314   mainMBB->addSuccessor(sinkMBB);
22315
22316   // sinkMBB:
22317   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
22318           TII->get(X86::PHI), DstReg)
22319     .addReg(mainDstReg).addMBB(mainMBB)
22320     .addReg(restoreDstReg).addMBB(restoreMBB);
22321
22322   // restoreMBB:
22323   if (RegInfo->hasBasePointer(*MF)) {
22324     const bool Uses64BitFramePtr =
22325         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
22326     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
22327     X86FI->setRestoreBasePointer(MF);
22328     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
22329     unsigned BasePtr = RegInfo->getBaseRegister();
22330     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
22331     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
22332                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
22333       .setMIFlag(MachineInstr::FrameSetup);
22334   }
22335   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
22336   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
22337   restoreMBB->addSuccessor(sinkMBB);
22338
22339   MI->eraseFromParent();
22340   return sinkMBB;
22341 }
22342
22343 MachineBasicBlock *
22344 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
22345                                      MachineBasicBlock *MBB) const {
22346   DebugLoc DL = MI->getDebugLoc();
22347   MachineFunction *MF = MBB->getParent();
22348   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22349   MachineRegisterInfo &MRI = MF->getRegInfo();
22350
22351   // Memory Reference
22352   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22353   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22354
22355   MVT PVT = getPointerTy(MF->getDataLayout());
22356   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22357          "Invalid Pointer Size!");
22358
22359   const TargetRegisterClass *RC =
22360     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
22361   unsigned Tmp = MRI.createVirtualRegister(RC);
22362   // Since FP is only updated here but NOT referenced, it's treated as GPR.
22363   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22364   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
22365   unsigned SP = RegInfo->getStackRegister();
22366
22367   MachineInstrBuilder MIB;
22368
22369   const int64_t LabelOffset = 1 * PVT.getStoreSize();
22370   const int64_t SPOffset = 2 * PVT.getStoreSize();
22371
22372   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
22373   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
22374
22375   // Reload FP
22376   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
22377   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
22378     MIB.addOperand(MI->getOperand(i));
22379   MIB.setMemRefs(MMOBegin, MMOEnd);
22380   // Reload IP
22381   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
22382   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22383     if (i == X86::AddrDisp)
22384       MIB.addDisp(MI->getOperand(i), LabelOffset);
22385     else
22386       MIB.addOperand(MI->getOperand(i));
22387   }
22388   MIB.setMemRefs(MMOBegin, MMOEnd);
22389   // Reload SP
22390   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
22391   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22392     if (i == X86::AddrDisp)
22393       MIB.addDisp(MI->getOperand(i), SPOffset);
22394     else
22395       MIB.addOperand(MI->getOperand(i));
22396   }
22397   MIB.setMemRefs(MMOBegin, MMOEnd);
22398   // Jump
22399   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
22400
22401   MI->eraseFromParent();
22402   return MBB;
22403 }
22404
22405 // Replace 213-type (isel default) FMA3 instructions with 231-type for
22406 // accumulator loops. Writing back to the accumulator allows the coalescer
22407 // to remove extra copies in the loop.
22408 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
22409 MachineBasicBlock *
22410 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
22411                                  MachineBasicBlock *MBB) const {
22412   MachineOperand &AddendOp = MI->getOperand(3);
22413
22414   // Bail out early if the addend isn't a register - we can't switch these.
22415   if (!AddendOp.isReg())
22416     return MBB;
22417
22418   MachineFunction &MF = *MBB->getParent();
22419   MachineRegisterInfo &MRI = MF.getRegInfo();
22420
22421   // Check whether the addend is defined by a PHI:
22422   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
22423   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
22424   if (!AddendDef.isPHI())
22425     return MBB;
22426
22427   // Look for the following pattern:
22428   // loop:
22429   //   %addend = phi [%entry, 0], [%loop, %result]
22430   //   ...
22431   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
22432
22433   // Replace with:
22434   //   loop:
22435   //   %addend = phi [%entry, 0], [%loop, %result]
22436   //   ...
22437   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
22438
22439   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
22440     assert(AddendDef.getOperand(i).isReg());
22441     MachineOperand PHISrcOp = AddendDef.getOperand(i);
22442     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
22443     if (&PHISrcInst == MI) {
22444       // Found a matching instruction.
22445       unsigned NewFMAOpc = 0;
22446       switch (MI->getOpcode()) {
22447         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
22448         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
22449         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
22450         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
22451         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
22452         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
22453         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
22454         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
22455         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
22456         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
22457         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
22458         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
22459         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
22460         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
22461         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
22462         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
22463         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
22464         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
22465         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
22466         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
22467
22468         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
22469         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
22470         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
22471         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
22472         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
22473         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
22474         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
22475         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
22476         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
22477         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
22478         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
22479         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
22480         default: llvm_unreachable("Unrecognized FMA variant.");
22481       }
22482
22483       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22484       MachineInstrBuilder MIB =
22485         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
22486         .addOperand(MI->getOperand(0))
22487         .addOperand(MI->getOperand(3))
22488         .addOperand(MI->getOperand(2))
22489         .addOperand(MI->getOperand(1));
22490       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
22491       MI->eraseFromParent();
22492     }
22493   }
22494
22495   return MBB;
22496 }
22497
22498 MachineBasicBlock *
22499 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
22500                                                MachineBasicBlock *BB) const {
22501   switch (MI->getOpcode()) {
22502   default: llvm_unreachable("Unexpected instr type to insert");
22503   case X86::TAILJMPd64:
22504   case X86::TAILJMPr64:
22505   case X86::TAILJMPm64:
22506   case X86::TAILJMPd64_REX:
22507   case X86::TAILJMPr64_REX:
22508   case X86::TAILJMPm64_REX:
22509     llvm_unreachable("TAILJMP64 would not be touched here.");
22510   case X86::TCRETURNdi64:
22511   case X86::TCRETURNri64:
22512   case X86::TCRETURNmi64:
22513     return BB;
22514   case X86::WIN_ALLOCA:
22515     return EmitLoweredWinAlloca(MI, BB);
22516   case X86::CATCHRET:
22517     return EmitLoweredCatchRet(MI, BB);
22518   case X86::CATCHPAD:
22519     return EmitLoweredCatchPad(MI, BB);
22520   case X86::SEG_ALLOCA_32:
22521   case X86::SEG_ALLOCA_64:
22522     return EmitLoweredSegAlloca(MI, BB);
22523   case X86::TLSCall_32:
22524   case X86::TLSCall_64:
22525     return EmitLoweredTLSCall(MI, BB);
22526   case X86::CMOV_FR32:
22527   case X86::CMOV_FR64:
22528   case X86::CMOV_FR128:
22529   case X86::CMOV_GR8:
22530   case X86::CMOV_GR16:
22531   case X86::CMOV_GR32:
22532   case X86::CMOV_RFP32:
22533   case X86::CMOV_RFP64:
22534   case X86::CMOV_RFP80:
22535   case X86::CMOV_V2F64:
22536   case X86::CMOV_V2I64:
22537   case X86::CMOV_V4F32:
22538   case X86::CMOV_V4F64:
22539   case X86::CMOV_V4I64:
22540   case X86::CMOV_V16F32:
22541   case X86::CMOV_V8F32:
22542   case X86::CMOV_V8F64:
22543   case X86::CMOV_V8I64:
22544   case X86::CMOV_V8I1:
22545   case X86::CMOV_V16I1:
22546   case X86::CMOV_V32I1:
22547   case X86::CMOV_V64I1:
22548     return EmitLoweredSelect(MI, BB);
22549
22550   case X86::RDFLAGS32:
22551   case X86::RDFLAGS64: {
22552     DebugLoc DL = MI->getDebugLoc();
22553     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22554     unsigned PushF =
22555         MI->getOpcode() == X86::RDFLAGS32 ? X86::PUSHF32 : X86::PUSHF64;
22556     unsigned Pop =
22557         MI->getOpcode() == X86::RDFLAGS32 ? X86::POP32r : X86::POP64r;
22558     BuildMI(*BB, MI, DL, TII->get(PushF));
22559     BuildMI(*BB, MI, DL, TII->get(Pop), MI->getOperand(0).getReg());
22560
22561     MI->eraseFromParent(); // The pseudo is gone now.
22562     return BB;
22563   }
22564
22565   case X86::WRFLAGS32:
22566   case X86::WRFLAGS64: {
22567     DebugLoc DL = MI->getDebugLoc();
22568     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22569     unsigned Push =
22570         MI->getOpcode() == X86::WRFLAGS32 ? X86::PUSH32r : X86::PUSH64r;
22571     unsigned PopF =
22572         MI->getOpcode() == X86::WRFLAGS32 ? X86::POPF32 : X86::POPF64;
22573     BuildMI(*BB, MI, DL, TII->get(Push)).addReg(MI->getOperand(0).getReg());
22574     BuildMI(*BB, MI, DL, TII->get(PopF));
22575
22576     MI->eraseFromParent(); // The pseudo is gone now.
22577     return BB;
22578   }
22579
22580   case X86::RELEASE_FADD32mr:
22581   case X86::RELEASE_FADD64mr:
22582     return EmitLoweredAtomicFP(MI, BB);
22583
22584   case X86::FP32_TO_INT16_IN_MEM:
22585   case X86::FP32_TO_INT32_IN_MEM:
22586   case X86::FP32_TO_INT64_IN_MEM:
22587   case X86::FP64_TO_INT16_IN_MEM:
22588   case X86::FP64_TO_INT32_IN_MEM:
22589   case X86::FP64_TO_INT64_IN_MEM:
22590   case X86::FP80_TO_INT16_IN_MEM:
22591   case X86::FP80_TO_INT32_IN_MEM:
22592   case X86::FP80_TO_INT64_IN_MEM: {
22593     MachineFunction *F = BB->getParent();
22594     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22595     DebugLoc DL = MI->getDebugLoc();
22596
22597     // Change the floating point control register to use "round towards zero"
22598     // mode when truncating to an integer value.
22599     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
22600     addFrameReference(BuildMI(*BB, MI, DL,
22601                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
22602
22603     // Load the old value of the high byte of the control word...
22604     unsigned OldCW =
22605       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
22606     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
22607                       CWFrameIdx);
22608
22609     // Set the high part to be round to zero...
22610     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
22611       .addImm(0xC7F);
22612
22613     // Reload the modified control word now...
22614     addFrameReference(BuildMI(*BB, MI, DL,
22615                               TII->get(X86::FLDCW16m)), CWFrameIdx);
22616
22617     // Restore the memory image of control word to original value
22618     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
22619       .addReg(OldCW);
22620
22621     // Get the X86 opcode to use.
22622     unsigned Opc;
22623     switch (MI->getOpcode()) {
22624     default: llvm_unreachable("illegal opcode!");
22625     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
22626     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
22627     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
22628     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
22629     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
22630     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
22631     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
22632     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
22633     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
22634     }
22635
22636     X86AddressMode AM;
22637     MachineOperand &Op = MI->getOperand(0);
22638     if (Op.isReg()) {
22639       AM.BaseType = X86AddressMode::RegBase;
22640       AM.Base.Reg = Op.getReg();
22641     } else {
22642       AM.BaseType = X86AddressMode::FrameIndexBase;
22643       AM.Base.FrameIndex = Op.getIndex();
22644     }
22645     Op = MI->getOperand(1);
22646     if (Op.isImm())
22647       AM.Scale = Op.getImm();
22648     Op = MI->getOperand(2);
22649     if (Op.isImm())
22650       AM.IndexReg = Op.getImm();
22651     Op = MI->getOperand(3);
22652     if (Op.isGlobal()) {
22653       AM.GV = Op.getGlobal();
22654     } else {
22655       AM.Disp = Op.getImm();
22656     }
22657     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
22658                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
22659
22660     // Reload the original control word now.
22661     addFrameReference(BuildMI(*BB, MI, DL,
22662                               TII->get(X86::FLDCW16m)), CWFrameIdx);
22663
22664     MI->eraseFromParent();   // The pseudo instruction is gone now.
22665     return BB;
22666   }
22667     // String/text processing lowering.
22668   case X86::PCMPISTRM128REG:
22669   case X86::VPCMPISTRM128REG:
22670   case X86::PCMPISTRM128MEM:
22671   case X86::VPCMPISTRM128MEM:
22672   case X86::PCMPESTRM128REG:
22673   case X86::VPCMPESTRM128REG:
22674   case X86::PCMPESTRM128MEM:
22675   case X86::VPCMPESTRM128MEM:
22676     assert(Subtarget->hasSSE42() &&
22677            "Target must have SSE4.2 or AVX features enabled");
22678     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
22679
22680   // String/text processing lowering.
22681   case X86::PCMPISTRIREG:
22682   case X86::VPCMPISTRIREG:
22683   case X86::PCMPISTRIMEM:
22684   case X86::VPCMPISTRIMEM:
22685   case X86::PCMPESTRIREG:
22686   case X86::VPCMPESTRIREG:
22687   case X86::PCMPESTRIMEM:
22688   case X86::VPCMPESTRIMEM:
22689     assert(Subtarget->hasSSE42() &&
22690            "Target must have SSE4.2 or AVX features enabled");
22691     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
22692
22693   // Thread synchronization.
22694   case X86::MONITOR:
22695     return EmitMonitor(MI, BB, Subtarget);
22696   // PKU feature
22697   case X86::WRPKRU:
22698     return EmitWRPKRU(MI, BB, Subtarget);
22699   case X86::RDPKRU:
22700     return EmitRDPKRU(MI, BB, Subtarget);
22701   // xbegin
22702   case X86::XBEGIN:
22703     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
22704
22705   case X86::VASTART_SAVE_XMM_REGS:
22706     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
22707
22708   case X86::VAARG_64:
22709     return EmitVAARG64WithCustomInserter(MI, BB);
22710
22711   case X86::EH_SjLj_SetJmp32:
22712   case X86::EH_SjLj_SetJmp64:
22713     return emitEHSjLjSetJmp(MI, BB);
22714
22715   case X86::EH_SjLj_LongJmp32:
22716   case X86::EH_SjLj_LongJmp64:
22717     return emitEHSjLjLongJmp(MI, BB);
22718
22719   case TargetOpcode::STATEPOINT:
22720     // As an implementation detail, STATEPOINT shares the STACKMAP format at
22721     // this point in the process.  We diverge later.
22722     return emitPatchPoint(MI, BB);
22723
22724   case TargetOpcode::STACKMAP:
22725   case TargetOpcode::PATCHPOINT:
22726     return emitPatchPoint(MI, BB);
22727
22728   case X86::VFMADDPDr213r:
22729   case X86::VFMADDPSr213r:
22730   case X86::VFMADDSDr213r:
22731   case X86::VFMADDSSr213r:
22732   case X86::VFMSUBPDr213r:
22733   case X86::VFMSUBPSr213r:
22734   case X86::VFMSUBSDr213r:
22735   case X86::VFMSUBSSr213r:
22736   case X86::VFNMADDPDr213r:
22737   case X86::VFNMADDPSr213r:
22738   case X86::VFNMADDSDr213r:
22739   case X86::VFNMADDSSr213r:
22740   case X86::VFNMSUBPDr213r:
22741   case X86::VFNMSUBPSr213r:
22742   case X86::VFNMSUBSDr213r:
22743   case X86::VFNMSUBSSr213r:
22744   case X86::VFMADDSUBPDr213r:
22745   case X86::VFMADDSUBPSr213r:
22746   case X86::VFMSUBADDPDr213r:
22747   case X86::VFMSUBADDPSr213r:
22748   case X86::VFMADDPDr213rY:
22749   case X86::VFMADDPSr213rY:
22750   case X86::VFMSUBPDr213rY:
22751   case X86::VFMSUBPSr213rY:
22752   case X86::VFNMADDPDr213rY:
22753   case X86::VFNMADDPSr213rY:
22754   case X86::VFNMSUBPDr213rY:
22755   case X86::VFNMSUBPSr213rY:
22756   case X86::VFMADDSUBPDr213rY:
22757   case X86::VFMADDSUBPSr213rY:
22758   case X86::VFMSUBADDPDr213rY:
22759   case X86::VFMSUBADDPSr213rY:
22760     return emitFMA3Instr(MI, BB);
22761   }
22762 }
22763
22764 //===----------------------------------------------------------------------===//
22765 //                           X86 Optimization Hooks
22766 //===----------------------------------------------------------------------===//
22767
22768 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
22769                                                       APInt &KnownZero,
22770                                                       APInt &KnownOne,
22771                                                       const SelectionDAG &DAG,
22772                                                       unsigned Depth) const {
22773   unsigned BitWidth = KnownZero.getBitWidth();
22774   unsigned Opc = Op.getOpcode();
22775   assert((Opc >= ISD::BUILTIN_OP_END ||
22776           Opc == ISD::INTRINSIC_WO_CHAIN ||
22777           Opc == ISD::INTRINSIC_W_CHAIN ||
22778           Opc == ISD::INTRINSIC_VOID) &&
22779          "Should use MaskedValueIsZero if you don't know whether Op"
22780          " is a target node!");
22781
22782   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
22783   switch (Opc) {
22784   default: break;
22785   case X86ISD::ADD:
22786   case X86ISD::SUB:
22787   case X86ISD::ADC:
22788   case X86ISD::SBB:
22789   case X86ISD::SMUL:
22790   case X86ISD::UMUL:
22791   case X86ISD::INC:
22792   case X86ISD::DEC:
22793   case X86ISD::OR:
22794   case X86ISD::XOR:
22795   case X86ISD::AND:
22796     // These nodes' second result is a boolean.
22797     if (Op.getResNo() == 0)
22798       break;
22799     // Fallthrough
22800   case X86ISD::SETCC:
22801     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
22802     break;
22803   case ISD::INTRINSIC_WO_CHAIN: {
22804     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22805     unsigned NumLoBits = 0;
22806     switch (IntId) {
22807     default: break;
22808     case Intrinsic::x86_sse_movmsk_ps:
22809     case Intrinsic::x86_avx_movmsk_ps_256:
22810     case Intrinsic::x86_sse2_movmsk_pd:
22811     case Intrinsic::x86_avx_movmsk_pd_256:
22812     case Intrinsic::x86_mmx_pmovmskb:
22813     case Intrinsic::x86_sse2_pmovmskb_128:
22814     case Intrinsic::x86_avx2_pmovmskb: {
22815       // High bits of movmskp{s|d}, pmovmskb are known zero.
22816       switch (IntId) {
22817         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
22818         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
22819         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
22820         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
22821         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
22822         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
22823         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
22824         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
22825       }
22826       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22827       break;
22828     }
22829     }
22830     break;
22831   }
22832   }
22833 }
22834
22835 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22836   SDValue Op,
22837   const SelectionDAG &,
22838   unsigned Depth) const {
22839   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22840   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22841     return Op.getValueType().getScalarSizeInBits();
22842
22843   // Fallback case.
22844   return 1;
22845 }
22846
22847 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22848 /// node is a GlobalAddress + offset.
22849 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22850                                        const GlobalValue* &GA,
22851                                        int64_t &Offset) const {
22852   if (N->getOpcode() == X86ISD::Wrapper) {
22853     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22854       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22855       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22856       return true;
22857     }
22858   }
22859   return TargetLowering::isGAPlusOffset(N, GA, Offset);
22860 }
22861
22862 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22863 /// FIXME: This could be expanded to support 512 bit vectors as well.
22864 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22865                                         TargetLowering::DAGCombinerInfo &DCI,
22866                                         const X86Subtarget* Subtarget) {
22867   SDLoc dl(N);
22868   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22869   SDValue V1 = SVOp->getOperand(0);
22870   SDValue V2 = SVOp->getOperand(1);
22871   MVT VT = SVOp->getSimpleValueType(0);
22872   unsigned NumElems = VT.getVectorNumElements();
22873
22874   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22875       V2.getOpcode() == ISD::CONCAT_VECTORS) {
22876     //
22877     //                   0,0,0,...
22878     //                      |
22879     //    V      UNDEF    BUILD_VECTOR    UNDEF
22880     //     \      /           \           /
22881     //  CONCAT_VECTOR         CONCAT_VECTOR
22882     //         \                  /
22883     //          \                /
22884     //          RESULT: V + zero extended
22885     //
22886     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22887         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22888         V1.getOperand(1).getOpcode() != ISD::UNDEF)
22889       return SDValue();
22890
22891     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
22892       return SDValue();
22893
22894     // To match the shuffle mask, the first half of the mask should
22895     // be exactly the first vector, and all the rest a splat with the
22896     // first element of the second one.
22897     for (unsigned i = 0; i != NumElems/2; ++i)
22898       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
22899           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
22900         return SDValue();
22901
22902     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
22903     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
22904       if (Ld->hasNUsesOfValue(1, 0)) {
22905         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
22906         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
22907         SDValue ResNode =
22908           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
22909                                   Ld->getMemoryVT(),
22910                                   Ld->getPointerInfo(),
22911                                   Ld->getAlignment(),
22912                                   false/*isVolatile*/, true/*ReadMem*/,
22913                                   false/*WriteMem*/);
22914
22915         // Make sure the newly-created LOAD is in the same position as Ld in
22916         // terms of dependency. We create a TokenFactor for Ld and ResNode,
22917         // and update uses of Ld's output chain to use the TokenFactor.
22918         if (Ld->hasAnyUseOfValue(1)) {
22919           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22920                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
22921           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
22922           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
22923                                  SDValue(ResNode.getNode(), 1));
22924         }
22925
22926         return DAG.getBitcast(VT, ResNode);
22927       }
22928     }
22929
22930     // Emit a zeroed vector and insert the desired subvector on its
22931     // first half.
22932     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
22933     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
22934     return DCI.CombineTo(N, InsV);
22935   }
22936
22937   return SDValue();
22938 }
22939
22940 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
22941 /// possible.
22942 ///
22943 /// This is the leaf of the recursive combinine below. When we have found some
22944 /// chain of single-use x86 shuffle instructions and accumulated the combined
22945 /// shuffle mask represented by them, this will try to pattern match that mask
22946 /// into either a single instruction if there is a special purpose instruction
22947 /// for this operation, or into a PSHUFB instruction which is a fully general
22948 /// instruction but should only be used to replace chains over a certain depth.
22949 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
22950                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
22951                                    TargetLowering::DAGCombinerInfo &DCI,
22952                                    const X86Subtarget *Subtarget) {
22953   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
22954
22955   // Find the operand that enters the chain. Note that multiple uses are OK
22956   // here, we're not going to remove the operand we find.
22957   SDValue Input = Op.getOperand(0);
22958   while (Input.getOpcode() == ISD::BITCAST)
22959     Input = Input.getOperand(0);
22960
22961   MVT VT = Input.getSimpleValueType();
22962   MVT RootVT = Root.getSimpleValueType();
22963   SDLoc DL(Root);
22964
22965   if (Mask.size() == 1) {
22966     int Index = Mask[0];
22967     assert((Index >= 0 || Index == SM_SentinelUndef ||
22968             Index == SM_SentinelZero) &&
22969            "Invalid shuffle index found!");
22970
22971     // We may end up with an accumulated mask of size 1 as a result of
22972     // widening of shuffle operands (see function canWidenShuffleElements).
22973     // If the only shuffle index is equal to SM_SentinelZero then propagate
22974     // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
22975     // mask, and therefore the entire chain of shuffles can be folded away.
22976     if (Index == SM_SentinelZero)
22977       DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
22978     else
22979       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
22980                     /*AddTo*/ true);
22981     return true;
22982   }
22983
22984   // Use the float domain if the operand type is a floating point type.
22985   bool FloatDomain = VT.isFloatingPoint();
22986
22987   // For floating point shuffles, we don't have free copies in the shuffle
22988   // instructions or the ability to load as part of the instruction, so
22989   // canonicalize their shuffles to UNPCK or MOV variants.
22990   //
22991   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
22992   // vectors because it can have a load folded into it that UNPCK cannot. This
22993   // doesn't preclude something switching to the shorter encoding post-RA.
22994   //
22995   // FIXME: Should teach these routines about AVX vector widths.
22996   if (FloatDomain && VT.is128BitVector()) {
22997     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
22998       bool Lo = Mask.equals({0, 0});
22999       unsigned Shuffle;
23000       MVT ShuffleVT;
23001       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
23002       // is no slower than UNPCKLPD but has the option to fold the input operand
23003       // into even an unaligned memory load.
23004       if (Lo && Subtarget->hasSSE3()) {
23005         Shuffle = X86ISD::MOVDDUP;
23006         ShuffleVT = MVT::v2f64;
23007       } else {
23008         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
23009         // than the UNPCK variants.
23010         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
23011         ShuffleVT = MVT::v4f32;
23012       }
23013       if (Depth == 1 && Root->getOpcode() == Shuffle)
23014         return false; // Nothing to do!
23015       Op = DAG.getBitcast(ShuffleVT, Input);
23016       DCI.AddToWorklist(Op.getNode());
23017       if (Shuffle == X86ISD::MOVDDUP)
23018         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23019       else
23020         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23021       DCI.AddToWorklist(Op.getNode());
23022       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23023                     /*AddTo*/ true);
23024       return true;
23025     }
23026     if (Subtarget->hasSSE3() &&
23027         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
23028       bool Lo = Mask.equals({0, 0, 2, 2});
23029       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
23030       MVT ShuffleVT = MVT::v4f32;
23031       if (Depth == 1 && Root->getOpcode() == Shuffle)
23032         return false; // Nothing to do!
23033       Op = DAG.getBitcast(ShuffleVT, Input);
23034       DCI.AddToWorklist(Op.getNode());
23035       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23036       DCI.AddToWorklist(Op.getNode());
23037       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23038                     /*AddTo*/ true);
23039       return true;
23040     }
23041     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
23042       bool Lo = Mask.equals({0, 0, 1, 1});
23043       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23044       MVT ShuffleVT = MVT::v4f32;
23045       if (Depth == 1 && Root->getOpcode() == Shuffle)
23046         return false; // Nothing to do!
23047       Op = DAG.getBitcast(ShuffleVT, Input);
23048       DCI.AddToWorklist(Op.getNode());
23049       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23050       DCI.AddToWorklist(Op.getNode());
23051       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23052                     /*AddTo*/ true);
23053       return true;
23054     }
23055   }
23056
23057   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
23058   // variants as none of these have single-instruction variants that are
23059   // superior to the UNPCK formulation.
23060   if (!FloatDomain && VT.is128BitVector() &&
23061       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23062        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
23063        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
23064        Mask.equals(
23065            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
23066     bool Lo = Mask[0] == 0;
23067     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23068     if (Depth == 1 && Root->getOpcode() == Shuffle)
23069       return false; // Nothing to do!
23070     MVT ShuffleVT;
23071     switch (Mask.size()) {
23072     case 8:
23073       ShuffleVT = MVT::v8i16;
23074       break;
23075     case 16:
23076       ShuffleVT = MVT::v16i8;
23077       break;
23078     default:
23079       llvm_unreachable("Impossible mask size!");
23080     };
23081     Op = DAG.getBitcast(ShuffleVT, Input);
23082     DCI.AddToWorklist(Op.getNode());
23083     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23084     DCI.AddToWorklist(Op.getNode());
23085     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23086                   /*AddTo*/ true);
23087     return true;
23088   }
23089
23090   // Don't try to re-form single instruction chains under any circumstances now
23091   // that we've done encoding canonicalization for them.
23092   if (Depth < 2)
23093     return false;
23094
23095   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
23096   // can replace them with a single PSHUFB instruction profitably. Intel's
23097   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
23098   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
23099   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
23100     SmallVector<SDValue, 16> PSHUFBMask;
23101     int NumBytes = VT.getSizeInBits() / 8;
23102     int Ratio = NumBytes / Mask.size();
23103     for (int i = 0; i < NumBytes; ++i) {
23104       if (Mask[i / Ratio] == SM_SentinelUndef) {
23105         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
23106         continue;
23107       }
23108       int M = Mask[i / Ratio] != SM_SentinelZero
23109                   ? Ratio * Mask[i / Ratio] + i % Ratio
23110                   : 255;
23111       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
23112     }
23113     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
23114     Op = DAG.getBitcast(ByteVT, Input);
23115     DCI.AddToWorklist(Op.getNode());
23116     SDValue PSHUFBMaskOp =
23117         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
23118     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
23119     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
23120     DCI.AddToWorklist(Op.getNode());
23121     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23122                   /*AddTo*/ true);
23123     return true;
23124   }
23125
23126   // Failed to find any combines.
23127   return false;
23128 }
23129
23130 /// \brief Fully generic combining of x86 shuffle instructions.
23131 ///
23132 /// This should be the last combine run over the x86 shuffle instructions. Once
23133 /// they have been fully optimized, this will recursively consider all chains
23134 /// of single-use shuffle instructions, build a generic model of the cumulative
23135 /// shuffle operation, and check for simpler instructions which implement this
23136 /// operation. We use this primarily for two purposes:
23137 ///
23138 /// 1) Collapse generic shuffles to specialized single instructions when
23139 ///    equivalent. In most cases, this is just an encoding size win, but
23140 ///    sometimes we will collapse multiple generic shuffles into a single
23141 ///    special-purpose shuffle.
23142 /// 2) Look for sequences of shuffle instructions with 3 or more total
23143 ///    instructions, and replace them with the slightly more expensive SSSE3
23144 ///    PSHUFB instruction if available. We do this as the last combining step
23145 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
23146 ///    a suitable short sequence of other instructions. The PHUFB will either
23147 ///    use a register or have to read from memory and so is slightly (but only
23148 ///    slightly) more expensive than the other shuffle instructions.
23149 ///
23150 /// Because this is inherently a quadratic operation (for each shuffle in
23151 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
23152 /// This should never be an issue in practice as the shuffle lowering doesn't
23153 /// produce sequences of more than 8 instructions.
23154 ///
23155 /// FIXME: We will currently miss some cases where the redundant shuffling
23156 /// would simplify under the threshold for PSHUFB formation because of
23157 /// combine-ordering. To fix this, we should do the redundant instruction
23158 /// combining in this recursive walk.
23159 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
23160                                           ArrayRef<int> RootMask,
23161                                           int Depth, bool HasPSHUFB,
23162                                           SelectionDAG &DAG,
23163                                           TargetLowering::DAGCombinerInfo &DCI,
23164                                           const X86Subtarget *Subtarget) {
23165   // Bound the depth of our recursive combine because this is ultimately
23166   // quadratic in nature.
23167   if (Depth > 8)
23168     return false;
23169
23170   // Directly rip through bitcasts to find the underlying operand.
23171   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
23172     Op = Op.getOperand(0);
23173
23174   MVT VT = Op.getSimpleValueType();
23175   if (!VT.isVector())
23176     return false; // Bail if we hit a non-vector.
23177
23178   assert(Root.getSimpleValueType().isVector() &&
23179          "Shuffles operate on vector types!");
23180   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
23181          "Can only combine shuffles of the same vector register size.");
23182
23183   if (!isTargetShuffle(Op.getOpcode()))
23184     return false;
23185   SmallVector<int, 16> OpMask;
23186   bool IsUnary;
23187   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
23188   // We only can combine unary shuffles which we can decode the mask for.
23189   if (!HaveMask || !IsUnary)
23190     return false;
23191
23192   assert(VT.getVectorNumElements() == OpMask.size() &&
23193          "Different mask size from vector size!");
23194   assert(((RootMask.size() > OpMask.size() &&
23195            RootMask.size() % OpMask.size() == 0) ||
23196           (OpMask.size() > RootMask.size() &&
23197            OpMask.size() % RootMask.size() == 0) ||
23198           OpMask.size() == RootMask.size()) &&
23199          "The smaller number of elements must divide the larger.");
23200   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
23201   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
23202   assert(((RootRatio == 1 && OpRatio == 1) ||
23203           (RootRatio == 1) != (OpRatio == 1)) &&
23204          "Must not have a ratio for both incoming and op masks!");
23205
23206   SmallVector<int, 16> Mask;
23207   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
23208
23209   // Merge this shuffle operation's mask into our accumulated mask. Note that
23210   // this shuffle's mask will be the first applied to the input, followed by the
23211   // root mask to get us all the way to the root value arrangement. The reason
23212   // for this order is that we are recursing up the operation chain.
23213   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
23214     int RootIdx = i / RootRatio;
23215     if (RootMask[RootIdx] < 0) {
23216       // This is a zero or undef lane, we're done.
23217       Mask.push_back(RootMask[RootIdx]);
23218       continue;
23219     }
23220
23221     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
23222     int OpIdx = RootMaskedIdx / OpRatio;
23223     if (OpMask[OpIdx] < 0) {
23224       // The incoming lanes are zero or undef, it doesn't matter which ones we
23225       // are using.
23226       Mask.push_back(OpMask[OpIdx]);
23227       continue;
23228     }
23229
23230     // Ok, we have non-zero lanes, map them through.
23231     Mask.push_back(OpMask[OpIdx] * OpRatio +
23232                    RootMaskedIdx % OpRatio);
23233   }
23234
23235   // See if we can recurse into the operand to combine more things.
23236   switch (Op.getOpcode()) {
23237   case X86ISD::PSHUFB:
23238     HasPSHUFB = true;
23239   case X86ISD::PSHUFD:
23240   case X86ISD::PSHUFHW:
23241   case X86ISD::PSHUFLW:
23242     if (Op.getOperand(0).hasOneUse() &&
23243         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23244                                       HasPSHUFB, DAG, DCI, Subtarget))
23245       return true;
23246     break;
23247
23248   case X86ISD::UNPCKL:
23249   case X86ISD::UNPCKH:
23250     assert(Op.getOperand(0) == Op.getOperand(1) &&
23251            "We only combine unary shuffles!");
23252     // We can't check for single use, we have to check that this shuffle is the
23253     // only user.
23254     if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
23255         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23256                                       HasPSHUFB, DAG, DCI, Subtarget))
23257       return true;
23258     break;
23259   }
23260
23261   // Minor canonicalization of the accumulated shuffle mask to make it easier
23262   // to match below. All this does is detect masks with squential pairs of
23263   // elements, and shrink them to the half-width mask. It does this in a loop
23264   // so it will reduce the size of the mask to the minimal width mask which
23265   // performs an equivalent shuffle.
23266   SmallVector<int, 16> WidenedMask;
23267   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
23268     Mask = std::move(WidenedMask);
23269     WidenedMask.clear();
23270   }
23271
23272   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
23273                                 Subtarget);
23274 }
23275
23276 /// \brief Get the PSHUF-style mask from PSHUF node.
23277 ///
23278 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
23279 /// PSHUF-style masks that can be reused with such instructions.
23280 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
23281   MVT VT = N.getSimpleValueType();
23282   SmallVector<int, 4> Mask;
23283   bool IsUnary;
23284   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
23285   (void)HaveMask;
23286   assert(HaveMask);
23287
23288   // If we have more than 128-bits, only the low 128-bits of shuffle mask
23289   // matter. Check that the upper masks are repeats and remove them.
23290   if (VT.getSizeInBits() > 128) {
23291     int LaneElts = 128 / VT.getScalarSizeInBits();
23292 #ifndef NDEBUG
23293     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
23294       for (int j = 0; j < LaneElts; ++j)
23295         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
23296                "Mask doesn't repeat in high 128-bit lanes!");
23297 #endif
23298     Mask.resize(LaneElts);
23299   }
23300
23301   switch (N.getOpcode()) {
23302   case X86ISD::PSHUFD:
23303     return Mask;
23304   case X86ISD::PSHUFLW:
23305     Mask.resize(4);
23306     return Mask;
23307   case X86ISD::PSHUFHW:
23308     Mask.erase(Mask.begin(), Mask.begin() + 4);
23309     for (int &M : Mask)
23310       M -= 4;
23311     return Mask;
23312   default:
23313     llvm_unreachable("No valid shuffle instruction found!");
23314   }
23315 }
23316
23317 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
23318 ///
23319 /// We walk up the chain and look for a combinable shuffle, skipping over
23320 /// shuffles that we could hoist this shuffle's transformation past without
23321 /// altering anything.
23322 static SDValue
23323 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
23324                              SelectionDAG &DAG,
23325                              TargetLowering::DAGCombinerInfo &DCI) {
23326   assert(N.getOpcode() == X86ISD::PSHUFD &&
23327          "Called with something other than an x86 128-bit half shuffle!");
23328   SDLoc DL(N);
23329
23330   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
23331   // of the shuffles in the chain so that we can form a fresh chain to replace
23332   // this one.
23333   SmallVector<SDValue, 8> Chain;
23334   SDValue V = N.getOperand(0);
23335   for (; V.hasOneUse(); V = V.getOperand(0)) {
23336     switch (V.getOpcode()) {
23337     default:
23338       return SDValue(); // Nothing combined!
23339
23340     case ISD::BITCAST:
23341       // Skip bitcasts as we always know the type for the target specific
23342       // instructions.
23343       continue;
23344
23345     case X86ISD::PSHUFD:
23346       // Found another dword shuffle.
23347       break;
23348
23349     case X86ISD::PSHUFLW:
23350       // Check that the low words (being shuffled) are the identity in the
23351       // dword shuffle, and the high words are self-contained.
23352       if (Mask[0] != 0 || Mask[1] != 1 ||
23353           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
23354         return SDValue();
23355
23356       Chain.push_back(V);
23357       continue;
23358
23359     case X86ISD::PSHUFHW:
23360       // Check that the high words (being shuffled) are the identity in the
23361       // dword shuffle, and the low words are self-contained.
23362       if (Mask[2] != 2 || Mask[3] != 3 ||
23363           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
23364         return SDValue();
23365
23366       Chain.push_back(V);
23367       continue;
23368
23369     case X86ISD::UNPCKL:
23370     case X86ISD::UNPCKH:
23371       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
23372       // shuffle into a preceding word shuffle.
23373       if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
23374           V.getSimpleValueType().getVectorElementType() != MVT::i16)
23375         return SDValue();
23376
23377       // Search for a half-shuffle which we can combine with.
23378       unsigned CombineOp =
23379           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
23380       if (V.getOperand(0) != V.getOperand(1) ||
23381           !V->isOnlyUserOf(V.getOperand(0).getNode()))
23382         return SDValue();
23383       Chain.push_back(V);
23384       V = V.getOperand(0);
23385       do {
23386         switch (V.getOpcode()) {
23387         default:
23388           return SDValue(); // Nothing to combine.
23389
23390         case X86ISD::PSHUFLW:
23391         case X86ISD::PSHUFHW:
23392           if (V.getOpcode() == CombineOp)
23393             break;
23394
23395           Chain.push_back(V);
23396
23397           // Fallthrough!
23398         case ISD::BITCAST:
23399           V = V.getOperand(0);
23400           continue;
23401         }
23402         break;
23403       } while (V.hasOneUse());
23404       break;
23405     }
23406     // Break out of the loop if we break out of the switch.
23407     break;
23408   }
23409
23410   if (!V.hasOneUse())
23411     // We fell out of the loop without finding a viable combining instruction.
23412     return SDValue();
23413
23414   // Merge this node's mask and our incoming mask.
23415   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23416   for (int &M : Mask)
23417     M = VMask[M];
23418   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
23419                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23420
23421   // Rebuild the chain around this new shuffle.
23422   while (!Chain.empty()) {
23423     SDValue W = Chain.pop_back_val();
23424
23425     if (V.getValueType() != W.getOperand(0).getValueType())
23426       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
23427
23428     switch (W.getOpcode()) {
23429     default:
23430       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
23431
23432     case X86ISD::UNPCKL:
23433     case X86ISD::UNPCKH:
23434       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
23435       break;
23436
23437     case X86ISD::PSHUFD:
23438     case X86ISD::PSHUFLW:
23439     case X86ISD::PSHUFHW:
23440       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
23441       break;
23442     }
23443   }
23444   if (V.getValueType() != N.getValueType())
23445     V = DAG.getBitcast(N.getValueType(), V);
23446
23447   // Return the new chain to replace N.
23448   return V;
23449 }
23450
23451 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
23452 /// pshufhw.
23453 ///
23454 /// We walk up the chain, skipping shuffles of the other half and looking
23455 /// through shuffles which switch halves trying to find a shuffle of the same
23456 /// pair of dwords.
23457 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
23458                                         SelectionDAG &DAG,
23459                                         TargetLowering::DAGCombinerInfo &DCI) {
23460   assert(
23461       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
23462       "Called with something other than an x86 128-bit half shuffle!");
23463   SDLoc DL(N);
23464   unsigned CombineOpcode = N.getOpcode();
23465
23466   // Walk up a single-use chain looking for a combinable shuffle.
23467   SDValue V = N.getOperand(0);
23468   for (; V.hasOneUse(); V = V.getOperand(0)) {
23469     switch (V.getOpcode()) {
23470     default:
23471       return false; // Nothing combined!
23472
23473     case ISD::BITCAST:
23474       // Skip bitcasts as we always know the type for the target specific
23475       // instructions.
23476       continue;
23477
23478     case X86ISD::PSHUFLW:
23479     case X86ISD::PSHUFHW:
23480       if (V.getOpcode() == CombineOpcode)
23481         break;
23482
23483       // Other-half shuffles are no-ops.
23484       continue;
23485     }
23486     // Break out of the loop if we break out of the switch.
23487     break;
23488   }
23489
23490   if (!V.hasOneUse())
23491     // We fell out of the loop without finding a viable combining instruction.
23492     return false;
23493
23494   // Combine away the bottom node as its shuffle will be accumulated into
23495   // a preceding shuffle.
23496   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23497
23498   // Record the old value.
23499   SDValue Old = V;
23500
23501   // Merge this node's mask and our incoming mask (adjusted to account for all
23502   // the pshufd instructions encountered).
23503   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23504   for (int &M : Mask)
23505     M = VMask[M];
23506   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
23507                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23508
23509   // Check that the shuffles didn't cancel each other out. If not, we need to
23510   // combine to the new one.
23511   if (Old != V)
23512     // Replace the combinable shuffle with the combined one, updating all users
23513     // so that we re-evaluate the chain here.
23514     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
23515
23516   return true;
23517 }
23518
23519 /// \brief Try to combine x86 target specific shuffles.
23520 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
23521                                            TargetLowering::DAGCombinerInfo &DCI,
23522                                            const X86Subtarget *Subtarget) {
23523   SDLoc DL(N);
23524   MVT VT = N.getSimpleValueType();
23525   SmallVector<int, 4> Mask;
23526
23527   switch (N.getOpcode()) {
23528   case X86ISD::PSHUFD:
23529   case X86ISD::PSHUFLW:
23530   case X86ISD::PSHUFHW:
23531     Mask = getPSHUFShuffleMask(N);
23532     assert(Mask.size() == 4);
23533     break;
23534   case X86ISD::UNPCKL: {
23535     // Combine X86ISD::UNPCKL and ISD::VECTOR_SHUFFLE into X86ISD::UNPCKH, in
23536     // which X86ISD::UNPCKL has a ISD::UNDEF operand, and ISD::VECTOR_SHUFFLE
23537     // moves upper half elements into the lower half part. For example:
23538     //
23539     // t2: v16i8 = vector_shuffle<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> t1,
23540     //     undef:v16i8
23541     // t3: v16i8 = X86ISD::UNPCKL undef:v16i8, t2
23542     //
23543     // will be combined to:
23544     //
23545     // t3: v16i8 = X86ISD::UNPCKH undef:v16i8, t1
23546
23547     // This is only for 128-bit vectors. From SSE4.1 onward this combine may not
23548     // happen due to advanced instructions.
23549     if (!VT.is128BitVector())
23550       return SDValue();
23551
23552     auto Op0 = N.getOperand(0);
23553     auto Op1 = N.getOperand(1);
23554     if (Op0.getOpcode() == ISD::UNDEF &&
23555         Op1.getNode()->getOpcode() == ISD::VECTOR_SHUFFLE) {
23556       ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op1.getNode())->getMask();
23557
23558       unsigned NumElts = VT.getVectorNumElements();
23559       SmallVector<int, 8> ExpectedMask(NumElts, -1);
23560       std::iota(ExpectedMask.begin(), ExpectedMask.begin() + NumElts / 2,
23561                 NumElts / 2);
23562
23563       auto ShufOp = Op1.getOperand(0);
23564       if (isShuffleEquivalent(Op1, ShufOp, Mask, ExpectedMask))
23565         return DAG.getNode(X86ISD::UNPCKH, DL, VT, N.getOperand(0), ShufOp);
23566     }
23567     return SDValue();
23568   }
23569   case X86ISD::BLENDI: {
23570     SDValue V0 = N->getOperand(0);
23571     SDValue V1 = N->getOperand(1);
23572     assert(VT == V0.getSimpleValueType() && VT == V1.getSimpleValueType() &&
23573            "Unexpected input vector types");
23574
23575     // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23576     // operands and changing the mask to 1. This saves us a bunch of
23577     // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23578     // x86InstrInfo knows how to commute this back after instruction selection
23579     // if it would help register allocation.
23580
23581     // TODO: If optimizing for size or a processor that doesn't suffer from
23582     // partial register update stalls, this should be transformed into a MOVSD
23583     // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23584
23585     if (VT == MVT::v2f64)
23586       if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23587         if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23588           SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23589           return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23590         }
23591
23592     return SDValue();
23593   }
23594   default:
23595     return SDValue();
23596   }
23597
23598   // Nuke no-op shuffles that show up after combining.
23599   if (isNoopShuffleMask(Mask))
23600     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23601
23602   // Look for simplifications involving one or two shuffle instructions.
23603   SDValue V = N.getOperand(0);
23604   switch (N.getOpcode()) {
23605   default:
23606     break;
23607   case X86ISD::PSHUFLW:
23608   case X86ISD::PSHUFHW:
23609     assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
23610
23611     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
23612       return SDValue(); // We combined away this shuffle, so we're done.
23613
23614     // See if this reduces to a PSHUFD which is no more expensive and can
23615     // combine with more operations. Note that it has to at least flip the
23616     // dwords as otherwise it would have been removed as a no-op.
23617     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
23618       int DMask[] = {0, 1, 2, 3};
23619       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
23620       DMask[DOffset + 0] = DOffset + 1;
23621       DMask[DOffset + 1] = DOffset + 0;
23622       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
23623       V = DAG.getBitcast(DVT, V);
23624       DCI.AddToWorklist(V.getNode());
23625       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
23626                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
23627       DCI.AddToWorklist(V.getNode());
23628       return DAG.getBitcast(VT, V);
23629     }
23630
23631     // Look for shuffle patterns which can be implemented as a single unpack.
23632     // FIXME: This doesn't handle the location of the PSHUFD generically, and
23633     // only works when we have a PSHUFD followed by two half-shuffles.
23634     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
23635         (V.getOpcode() == X86ISD::PSHUFLW ||
23636          V.getOpcode() == X86ISD::PSHUFHW) &&
23637         V.getOpcode() != N.getOpcode() &&
23638         V.hasOneUse()) {
23639       SDValue D = V.getOperand(0);
23640       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
23641         D = D.getOperand(0);
23642       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
23643         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23644         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
23645         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23646         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23647         int WordMask[8];
23648         for (int i = 0; i < 4; ++i) {
23649           WordMask[i + NOffset] = Mask[i] + NOffset;
23650           WordMask[i + VOffset] = VMask[i] + VOffset;
23651         }
23652         // Map the word mask through the DWord mask.
23653         int MappedMask[8];
23654         for (int i = 0; i < 8; ++i)
23655           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
23656         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23657             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
23658           // We can replace all three shuffles with an unpack.
23659           V = DAG.getBitcast(VT, D.getOperand(0));
23660           DCI.AddToWorklist(V.getNode());
23661           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
23662                                                 : X86ISD::UNPCKH,
23663                              DL, VT, V, V);
23664         }
23665       }
23666     }
23667
23668     break;
23669
23670   case X86ISD::PSHUFD:
23671     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
23672       return NewN;
23673
23674     break;
23675   }
23676
23677   return SDValue();
23678 }
23679
23680 /// \brief Try to combine a shuffle into a target-specific add-sub node.
23681 ///
23682 /// We combine this directly on the abstract vector shuffle nodes so it is
23683 /// easier to generically match. We also insert dummy vector shuffle nodes for
23684 /// the operands which explicitly discard the lanes which are unused by this
23685 /// operation to try to flow through the rest of the combiner the fact that
23686 /// they're unused.
23687 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
23688   SDLoc DL(N);
23689   EVT VT = N->getValueType(0);
23690
23691   // We only handle target-independent shuffles.
23692   // FIXME: It would be easy and harmless to use the target shuffle mask
23693   // extraction tool to support more.
23694   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
23695     return SDValue();
23696
23697   auto *SVN = cast<ShuffleVectorSDNode>(N);
23698   SmallVector<int, 8> Mask;
23699   for (int M : SVN->getMask())
23700     Mask.push_back(M);
23701
23702   SDValue V1 = N->getOperand(0);
23703   SDValue V2 = N->getOperand(1);
23704
23705   // We require the first shuffle operand to be the FSUB node, and the second to
23706   // be the FADD node.
23707   if (V1.getOpcode() == ISD::FADD && V2.getOpcode() == ISD::FSUB) {
23708     ShuffleVectorSDNode::commuteMask(Mask);
23709     std::swap(V1, V2);
23710   } else if (V1.getOpcode() != ISD::FSUB || V2.getOpcode() != ISD::FADD)
23711     return SDValue();
23712
23713   // If there are other uses of these operations we can't fold them.
23714   if (!V1->hasOneUse() || !V2->hasOneUse())
23715     return SDValue();
23716
23717   // Ensure that both operations have the same operands. Note that we can
23718   // commute the FADD operands.
23719   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
23720   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
23721       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
23722     return SDValue();
23723
23724   // We're looking for blends between FADD and FSUB nodes. We insist on these
23725   // nodes being lined up in a specific expected pattern.
23726   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
23727         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
23728         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
23729     return SDValue();
23730
23731   // Only specific types are legal at this point, assert so we notice if and
23732   // when these change.
23733   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
23734           VT == MVT::v4f64) &&
23735          "Unknown vector type encountered!");
23736
23737   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
23738 }
23739
23740 /// PerformShuffleCombine - Performs several different shuffle combines.
23741 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
23742                                      TargetLowering::DAGCombinerInfo &DCI,
23743                                      const X86Subtarget *Subtarget) {
23744   SDLoc dl(N);
23745   SDValue N0 = N->getOperand(0);
23746   SDValue N1 = N->getOperand(1);
23747   EVT VT = N->getValueType(0);
23748
23749   // Don't create instructions with illegal types after legalize types has run.
23750   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23751   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
23752     return SDValue();
23753
23754   // If we have legalized the vector types, look for blends of FADD and FSUB
23755   // nodes that we can fuse into an ADDSUB node.
23756   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
23757     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
23758       return AddSub;
23759
23760   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
23761   if (TLI.isTypeLegal(VT) && Subtarget->hasFp256() && VT.is256BitVector() &&
23762       N->getOpcode() == ISD::VECTOR_SHUFFLE)
23763     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
23764
23765   // During Type Legalization, when promoting illegal vector types,
23766   // the backend might introduce new shuffle dag nodes and bitcasts.
23767   //
23768   // This code performs the following transformation:
23769   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
23770   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
23771   //
23772   // We do this only if both the bitcast and the BINOP dag nodes have
23773   // one use. Also, perform this transformation only if the new binary
23774   // operation is legal. This is to avoid introducing dag nodes that
23775   // potentially need to be further expanded (or custom lowered) into a
23776   // less optimal sequence of dag nodes.
23777   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
23778       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
23779       N0.getOpcode() == ISD::BITCAST) {
23780     SDValue BC0 = N0.getOperand(0);
23781     EVT SVT = BC0.getValueType();
23782     unsigned Opcode = BC0.getOpcode();
23783     unsigned NumElts = VT.getVectorNumElements();
23784
23785     if (BC0.hasOneUse() && SVT.isVector() &&
23786         SVT.getVectorNumElements() * 2 == NumElts &&
23787         TLI.isOperationLegal(Opcode, VT)) {
23788       bool CanFold = false;
23789       switch (Opcode) {
23790       default : break;
23791       case ISD::ADD :
23792       case ISD::FADD :
23793       case ISD::SUB :
23794       case ISD::FSUB :
23795       case ISD::MUL :
23796       case ISD::FMUL :
23797         CanFold = true;
23798       }
23799
23800       unsigned SVTNumElts = SVT.getVectorNumElements();
23801       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
23802       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
23803         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
23804       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
23805         CanFold = SVOp->getMaskElt(i) < 0;
23806
23807       if (CanFold) {
23808         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
23809         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
23810         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
23811         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
23812       }
23813     }
23814   }
23815
23816   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
23817   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
23818   // consecutive, non-overlapping, and in the right order.
23819   SmallVector<SDValue, 16> Elts;
23820   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23821     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23822
23823   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23824     return LD;
23825
23826   if (isTargetShuffle(N->getOpcode())) {
23827     SDValue Shuffle =
23828         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23829     if (Shuffle.getNode())
23830       return Shuffle;
23831
23832     // Try recursively combining arbitrary sequences of x86 shuffle
23833     // instructions into higher-order shuffles. We do this after combining
23834     // specific PSHUF instruction sequences into their minimal form so that we
23835     // can evaluate how many specialized shuffle instructions are involved in
23836     // a particular chain.
23837     SmallVector<int, 1> NonceMask; // Just a placeholder.
23838     NonceMask.push_back(0);
23839     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23840                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23841                                       DCI, Subtarget))
23842       return SDValue(); // This routine will use CombineTo to replace N.
23843   }
23844
23845   return SDValue();
23846 }
23847
23848 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23849 /// specific shuffle of a load can be folded into a single element load.
23850 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23851 /// shuffles have been custom lowered so we need to handle those here.
23852 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23853                                          TargetLowering::DAGCombinerInfo &DCI) {
23854   if (DCI.isBeforeLegalizeOps())
23855     return SDValue();
23856
23857   SDValue InVec = N->getOperand(0);
23858   SDValue EltNo = N->getOperand(1);
23859
23860   if (!isa<ConstantSDNode>(EltNo))
23861     return SDValue();
23862
23863   EVT OriginalVT = InVec.getValueType();
23864
23865   if (InVec.getOpcode() == ISD::BITCAST) {
23866     // Don't duplicate a load with other uses.
23867     if (!InVec.hasOneUse())
23868       return SDValue();
23869     EVT BCVT = InVec.getOperand(0).getValueType();
23870     if (!BCVT.isVector() ||
23871         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23872       return SDValue();
23873     InVec = InVec.getOperand(0);
23874   }
23875
23876   EVT CurrentVT = InVec.getValueType();
23877
23878   if (!isTargetShuffle(InVec.getOpcode()))
23879     return SDValue();
23880
23881   // Don't duplicate a load with other uses.
23882   if (!InVec.hasOneUse())
23883     return SDValue();
23884
23885   SmallVector<int, 16> ShuffleMask;
23886   bool UnaryShuffle;
23887   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
23888                             ShuffleMask, UnaryShuffle))
23889     return SDValue();
23890
23891   // Select the input vector, guarding against out of range extract vector.
23892   unsigned NumElems = CurrentVT.getVectorNumElements();
23893   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
23894   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
23895   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
23896                                          : InVec.getOperand(1);
23897
23898   // If inputs to shuffle are the same for both ops, then allow 2 uses
23899   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
23900                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
23901
23902   if (LdNode.getOpcode() == ISD::BITCAST) {
23903     // Don't duplicate a load with other uses.
23904     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
23905       return SDValue();
23906
23907     AllowedUses = 1; // only allow 1 load use if we have a bitcast
23908     LdNode = LdNode.getOperand(0);
23909   }
23910
23911   if (!ISD::isNormalLoad(LdNode.getNode()))
23912     return SDValue();
23913
23914   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
23915
23916   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
23917     return SDValue();
23918
23919   EVT EltVT = N->getValueType(0);
23920   // If there's a bitcast before the shuffle, check if the load type and
23921   // alignment is valid.
23922   unsigned Align = LN0->getAlignment();
23923   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23924   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
23925       EltVT.getTypeForEVT(*DAG.getContext()));
23926
23927   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
23928     return SDValue();
23929
23930   // All checks match so transform back to vector_shuffle so that DAG combiner
23931   // can finish the job
23932   SDLoc dl(N);
23933
23934   // Create shuffle node taking into account the case that its a unary shuffle
23935   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
23936                                    : InVec.getOperand(1);
23937   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
23938                                  InVec.getOperand(0), Shuffle,
23939                                  &ShuffleMask[0]);
23940   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
23941   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
23942                      EltNo);
23943 }
23944
23945 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
23946                                      const X86Subtarget *Subtarget) {
23947   SDValue N0 = N->getOperand(0);
23948   EVT VT = N->getValueType(0);
23949
23950   // Detect bitcasts between i32 to x86mmx low word. Since MMX types are
23951   // special and don't usually play with other vector types, it's better to
23952   // handle them early to be sure we emit efficient code by avoiding
23953   // store-load conversions.
23954   if (VT == MVT::x86mmx && N0.getOpcode() == ISD::BUILD_VECTOR &&
23955       N0.getValueType() == MVT::v2i32 &&
23956       isNullConstant(N0.getOperand(1))) {
23957     SDValue N00 = N0->getOperand(0);
23958     if (N00.getValueType() == MVT::i32)
23959       return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(N00), VT, N00);
23960   }
23961
23962   // Convert a bitcasted integer logic operation that has one bitcasted
23963   // floating-point operand and one constant operand into a floating-point
23964   // logic operation. This may create a load of the constant, but that is
23965   // cheaper than materializing the constant in an integer register and
23966   // transferring it to an SSE register or transferring the SSE operand to
23967   // integer register and back.
23968   unsigned FPOpcode;
23969   switch (N0.getOpcode()) {
23970     case ISD::AND: FPOpcode = X86ISD::FAND; break;
23971     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
23972     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
23973     default: return SDValue();
23974   }
23975   if (((Subtarget->hasSSE1() && VT == MVT::f32) ||
23976        (Subtarget->hasSSE2() && VT == MVT::f64)) &&
23977       isa<ConstantSDNode>(N0.getOperand(1)) &&
23978       N0.getOperand(0).getOpcode() == ISD::BITCAST &&
23979       N0.getOperand(0).getOperand(0).getValueType() == VT) {
23980     SDValue N000 = N0.getOperand(0).getOperand(0);
23981     SDValue FPConst = DAG.getBitcast(VT, N0.getOperand(1));
23982     return DAG.getNode(FPOpcode, SDLoc(N0), VT, N000, FPConst);
23983   }
23984
23985   return SDValue();
23986 }
23987
23988 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
23989 /// generation and convert it from being a bunch of shuffles and extracts
23990 /// into a somewhat faster sequence. For i686, the best sequence is apparently
23991 /// storing the value and loading scalars back, while for x64 we should
23992 /// use 64-bit extracts and shifts.
23993 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
23994                                          TargetLowering::DAGCombinerInfo &DCI) {
23995   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
23996     return NewOp;
23997
23998   SDValue InputVector = N->getOperand(0);
23999   SDLoc dl(InputVector);
24000   // Detect mmx to i32 conversion through a v2i32 elt extract.
24001   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
24002       N->getValueType(0) == MVT::i32 &&
24003       InputVector.getValueType() == MVT::v2i32) {
24004
24005     // The bitcast source is a direct mmx result.
24006     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
24007     if (MMXSrc.getValueType() == MVT::x86mmx)
24008       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
24009                          N->getValueType(0),
24010                          InputVector.getNode()->getOperand(0));
24011
24012     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
24013     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
24014         MMXSrc.getValueType() == MVT::i64) {
24015       SDValue MMXSrcOp = MMXSrc.getOperand(0);
24016       if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
24017           MMXSrcOp.getValueType() == MVT::v1i64 &&
24018           MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
24019         return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
24020                            N->getValueType(0), MMXSrcOp.getOperand(0));
24021     }
24022   }
24023
24024   EVT VT = N->getValueType(0);
24025
24026   if (VT == MVT::i1 && isa<ConstantSDNode>(N->getOperand(1)) &&
24027       InputVector.getOpcode() == ISD::BITCAST &&
24028       isa<ConstantSDNode>(InputVector.getOperand(0))) {
24029     uint64_t ExtractedElt =
24030         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
24031     uint64_t InputValue =
24032         cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
24033     uint64_t Res = (InputValue >> ExtractedElt) & 1;
24034     return DAG.getConstant(Res, dl, MVT::i1);
24035   }
24036   // Only operate on vectors of 4 elements, where the alternative shuffling
24037   // gets to be more expensive.
24038   if (InputVector.getValueType() != MVT::v4i32)
24039     return SDValue();
24040
24041   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
24042   // single use which is a sign-extend or zero-extend, and all elements are
24043   // used.
24044   SmallVector<SDNode *, 4> Uses;
24045   unsigned ExtractedElements = 0;
24046   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
24047        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
24048     if (UI.getUse().getResNo() != InputVector.getResNo())
24049       return SDValue();
24050
24051     SDNode *Extract = *UI;
24052     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
24053       return SDValue();
24054
24055     if (Extract->getValueType(0) != MVT::i32)
24056       return SDValue();
24057     if (!Extract->hasOneUse())
24058       return SDValue();
24059     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
24060         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
24061       return SDValue();
24062     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
24063       return SDValue();
24064
24065     // Record which element was extracted.
24066     ExtractedElements |=
24067       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
24068
24069     Uses.push_back(Extract);
24070   }
24071
24072   // If not all the elements were used, this may not be worthwhile.
24073   if (ExtractedElements != 15)
24074     return SDValue();
24075
24076   // Ok, we've now decided to do the transformation.
24077   // If 64-bit shifts are legal, use the extract-shift sequence,
24078   // otherwise bounce the vector off the cache.
24079   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24080   SDValue Vals[4];
24081
24082   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
24083     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
24084     auto &DL = DAG.getDataLayout();
24085     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
24086     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24087       DAG.getConstant(0, dl, VecIdxTy));
24088     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24089       DAG.getConstant(1, dl, VecIdxTy));
24090
24091     SDValue ShAmt = DAG.getConstant(
24092         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
24093     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
24094     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24095       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
24096     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
24097     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24098       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
24099   } else {
24100     // Store the value to a temporary stack slot.
24101     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
24102     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
24103       MachinePointerInfo(), false, false, 0);
24104
24105     EVT ElementType = InputVector.getValueType().getVectorElementType();
24106     unsigned EltSize = ElementType.getSizeInBits() / 8;
24107
24108     // Replace each use (extract) with a load of the appropriate element.
24109     for (unsigned i = 0; i < 4; ++i) {
24110       uint64_t Offset = EltSize * i;
24111       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
24112       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
24113
24114       SDValue ScalarAddr =
24115           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
24116
24117       // Load the scalar.
24118       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
24119                             ScalarAddr, MachinePointerInfo(),
24120                             false, false, false, 0);
24121
24122     }
24123   }
24124
24125   // Replace the extracts
24126   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
24127     UE = Uses.end(); UI != UE; ++UI) {
24128     SDNode *Extract = *UI;
24129
24130     SDValue Idx = Extract->getOperand(1);
24131     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
24132     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
24133   }
24134
24135   // The replacement was made in place; don't return anything.
24136   return SDValue();
24137 }
24138
24139 static SDValue
24140 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
24141                                       const X86Subtarget *Subtarget) {
24142   SDLoc dl(N);
24143   SDValue Cond = N->getOperand(0);
24144   SDValue LHS = N->getOperand(1);
24145   SDValue RHS = N->getOperand(2);
24146
24147   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
24148     SDValue CondSrc = Cond->getOperand(0);
24149     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
24150       Cond = CondSrc->getOperand(0);
24151   }
24152
24153   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
24154     return SDValue();
24155
24156   // A vselect where all conditions and data are constants can be optimized into
24157   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
24158   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
24159       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
24160     return SDValue();
24161
24162   unsigned MaskValue = 0;
24163   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
24164     return SDValue();
24165
24166   MVT VT = N->getSimpleValueType(0);
24167   unsigned NumElems = VT.getVectorNumElements();
24168   SmallVector<int, 8> ShuffleMask(NumElems, -1);
24169   for (unsigned i = 0; i < NumElems; ++i) {
24170     // Be sure we emit undef where we can.
24171     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
24172       ShuffleMask[i] = -1;
24173     else
24174       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
24175   }
24176
24177   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24178   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
24179     return SDValue();
24180   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
24181 }
24182
24183 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
24184 /// nodes.
24185 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
24186                                     TargetLowering::DAGCombinerInfo &DCI,
24187                                     const X86Subtarget *Subtarget) {
24188   SDLoc DL(N);
24189   SDValue Cond = N->getOperand(0);
24190   // Get the LHS/RHS of the select.
24191   SDValue LHS = N->getOperand(1);
24192   SDValue RHS = N->getOperand(2);
24193   EVT VT = LHS.getValueType();
24194   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24195
24196   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
24197   // instructions match the semantics of the common C idiom x<y?x:y but not
24198   // x<=y?x:y, because of how they handle negative zero (which can be
24199   // ignored in unsafe-math mode).
24200   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
24201   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
24202       VT != MVT::f80 && VT != MVT::f128 &&
24203       (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
24204       (Subtarget->hasSSE2() ||
24205        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
24206     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24207
24208     unsigned Opcode = 0;
24209     // Check for x CC y ? x : y.
24210     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24211         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24212       switch (CC) {
24213       default: break;
24214       case ISD::SETULT:
24215         // Converting this to a min would handle NaNs incorrectly, and swapping
24216         // the operands would cause it to handle comparisons between positive
24217         // and negative zero incorrectly.
24218         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24219           if (!DAG.getTarget().Options.UnsafeFPMath &&
24220               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24221             break;
24222           std::swap(LHS, RHS);
24223         }
24224         Opcode = X86ISD::FMIN;
24225         break;
24226       case ISD::SETOLE:
24227         // Converting this to a min would handle comparisons between positive
24228         // and negative zero incorrectly.
24229         if (!DAG.getTarget().Options.UnsafeFPMath &&
24230             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24231           break;
24232         Opcode = X86ISD::FMIN;
24233         break;
24234       case ISD::SETULE:
24235         // Converting this to a min would handle both negative zeros and NaNs
24236         // incorrectly, but we can swap the operands to fix both.
24237         std::swap(LHS, RHS);
24238       case ISD::SETOLT:
24239       case ISD::SETLT:
24240       case ISD::SETLE:
24241         Opcode = X86ISD::FMIN;
24242         break;
24243
24244       case ISD::SETOGE:
24245         // Converting this to a max would handle comparisons between positive
24246         // and negative zero incorrectly.
24247         if (!DAG.getTarget().Options.UnsafeFPMath &&
24248             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24249           break;
24250         Opcode = X86ISD::FMAX;
24251         break;
24252       case ISD::SETUGT:
24253         // Converting this to a max would handle NaNs incorrectly, and swapping
24254         // the operands would cause it to handle comparisons between positive
24255         // and negative zero incorrectly.
24256         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24257           if (!DAG.getTarget().Options.UnsafeFPMath &&
24258               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24259             break;
24260           std::swap(LHS, RHS);
24261         }
24262         Opcode = X86ISD::FMAX;
24263         break;
24264       case ISD::SETUGE:
24265         // Converting this to a max would handle both negative zeros and NaNs
24266         // incorrectly, but we can swap the operands to fix both.
24267         std::swap(LHS, RHS);
24268       case ISD::SETOGT:
24269       case ISD::SETGT:
24270       case ISD::SETGE:
24271         Opcode = X86ISD::FMAX;
24272         break;
24273       }
24274     // Check for x CC y ? y : x -- a min/max with reversed arms.
24275     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
24276                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
24277       switch (CC) {
24278       default: break;
24279       case ISD::SETOGE:
24280         // Converting this to a min would handle comparisons between positive
24281         // and negative zero incorrectly, and swapping the operands would
24282         // cause it to handle NaNs incorrectly.
24283         if (!DAG.getTarget().Options.UnsafeFPMath &&
24284             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
24285           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24286             break;
24287           std::swap(LHS, RHS);
24288         }
24289         Opcode = X86ISD::FMIN;
24290         break;
24291       case ISD::SETUGT:
24292         // Converting this to a min would handle NaNs incorrectly.
24293         if (!DAG.getTarget().Options.UnsafeFPMath &&
24294             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
24295           break;
24296         Opcode = X86ISD::FMIN;
24297         break;
24298       case ISD::SETUGE:
24299         // Converting this to a min would handle both negative zeros and NaNs
24300         // incorrectly, but we can swap the operands to fix both.
24301         std::swap(LHS, RHS);
24302       case ISD::SETOGT:
24303       case ISD::SETGT:
24304       case ISD::SETGE:
24305         Opcode = X86ISD::FMIN;
24306         break;
24307
24308       case ISD::SETULT:
24309         // Converting this to a max would handle NaNs incorrectly.
24310         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24311           break;
24312         Opcode = X86ISD::FMAX;
24313         break;
24314       case ISD::SETOLE:
24315         // Converting this to a max would handle comparisons between positive
24316         // and negative zero incorrectly, and swapping the operands would
24317         // cause it to handle NaNs incorrectly.
24318         if (!DAG.getTarget().Options.UnsafeFPMath &&
24319             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
24320           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24321             break;
24322           std::swap(LHS, RHS);
24323         }
24324         Opcode = X86ISD::FMAX;
24325         break;
24326       case ISD::SETULE:
24327         // Converting this to a max would handle both negative zeros and NaNs
24328         // incorrectly, but we can swap the operands to fix both.
24329         std::swap(LHS, RHS);
24330       case ISD::SETOLT:
24331       case ISD::SETLT:
24332       case ISD::SETLE:
24333         Opcode = X86ISD::FMAX;
24334         break;
24335       }
24336     }
24337
24338     if (Opcode)
24339       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
24340   }
24341
24342   EVT CondVT = Cond.getValueType();
24343   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
24344       CondVT.getVectorElementType() == MVT::i1) {
24345     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
24346     // lowering on KNL. In this case we convert it to
24347     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
24348     // The same situation for all 128 and 256-bit vectors of i8 and i16.
24349     // Since SKX these selects have a proper lowering.
24350     EVT OpVT = LHS.getValueType();
24351     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
24352         (OpVT.getVectorElementType() == MVT::i8 ||
24353          OpVT.getVectorElementType() == MVT::i16) &&
24354         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
24355       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
24356       DCI.AddToWorklist(Cond.getNode());
24357       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
24358     }
24359   }
24360   // If this is a select between two integer constants, try to do some
24361   // optimizations.
24362   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
24363     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
24364       // Don't do this for crazy integer types.
24365       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
24366         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
24367         // so that TrueC (the true value) is larger than FalseC.
24368         bool NeedsCondInvert = false;
24369
24370         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
24371             // Efficiently invertible.
24372             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
24373              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
24374               isa<ConstantSDNode>(Cond.getOperand(1))))) {
24375           NeedsCondInvert = true;
24376           std::swap(TrueC, FalseC);
24377         }
24378
24379         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
24380         if (FalseC->getAPIntValue() == 0 &&
24381             TrueC->getAPIntValue().isPowerOf2()) {
24382           if (NeedsCondInvert) // Invert the condition if needed.
24383             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24384                                DAG.getConstant(1, DL, Cond.getValueType()));
24385
24386           // Zero extend the condition if needed.
24387           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
24388
24389           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24390           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
24391                              DAG.getConstant(ShAmt, DL, MVT::i8));
24392         }
24393
24394         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
24395         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24396           if (NeedsCondInvert) // Invert the condition if needed.
24397             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24398                                DAG.getConstant(1, DL, Cond.getValueType()));
24399
24400           // Zero extend the condition if needed.
24401           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24402                              FalseC->getValueType(0), Cond);
24403           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24404                              SDValue(FalseC, 0));
24405         }
24406
24407         // Optimize cases that will turn into an LEA instruction.  This requires
24408         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24409         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24410           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24411           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24412
24413           bool isFastMultiplier = false;
24414           if (Diff < 10) {
24415             switch ((unsigned char)Diff) {
24416               default: break;
24417               case 1:  // result = add base, cond
24418               case 2:  // result = lea base(    , cond*2)
24419               case 3:  // result = lea base(cond, cond*2)
24420               case 4:  // result = lea base(    , cond*4)
24421               case 5:  // result = lea base(cond, cond*4)
24422               case 8:  // result = lea base(    , cond*8)
24423               case 9:  // result = lea base(cond, cond*8)
24424                 isFastMultiplier = true;
24425                 break;
24426             }
24427           }
24428
24429           if (isFastMultiplier) {
24430             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24431             if (NeedsCondInvert) // Invert the condition if needed.
24432               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24433                                  DAG.getConstant(1, DL, Cond.getValueType()));
24434
24435             // Zero extend the condition if needed.
24436             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24437                                Cond);
24438             // Scale the condition by the difference.
24439             if (Diff != 1)
24440               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24441                                  DAG.getConstant(Diff, DL,
24442                                                  Cond.getValueType()));
24443
24444             // Add the base if non-zero.
24445             if (FalseC->getAPIntValue() != 0)
24446               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24447                                  SDValue(FalseC, 0));
24448             return Cond;
24449           }
24450         }
24451       }
24452   }
24453
24454   // Canonicalize max and min:
24455   // (x > y) ? x : y -> (x >= y) ? x : y
24456   // (x < y) ? x : y -> (x <= y) ? x : y
24457   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
24458   // the need for an extra compare
24459   // against zero. e.g.
24460   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
24461   // subl   %esi, %edi
24462   // testl  %edi, %edi
24463   // movl   $0, %eax
24464   // cmovgl %edi, %eax
24465   // =>
24466   // xorl   %eax, %eax
24467   // subl   %esi, $edi
24468   // cmovsl %eax, %edi
24469   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
24470       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24471       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24472     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24473     switch (CC) {
24474     default: break;
24475     case ISD::SETLT:
24476     case ISD::SETGT: {
24477       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
24478       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
24479                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
24480       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
24481     }
24482     }
24483   }
24484
24485   // Early exit check
24486   if (!TLI.isTypeLegal(VT))
24487     return SDValue();
24488
24489   // Match VSELECTs into subs with unsigned saturation.
24490   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
24491       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
24492       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
24493        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
24494     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24495
24496     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
24497     // left side invert the predicate to simplify logic below.
24498     SDValue Other;
24499     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
24500       Other = RHS;
24501       CC = ISD::getSetCCInverse(CC, true);
24502     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
24503       Other = LHS;
24504     }
24505
24506     if (Other.getNode() && Other->getNumOperands() == 2 &&
24507         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
24508       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
24509       SDValue CondRHS = Cond->getOperand(1);
24510
24511       // Look for a general sub with unsigned saturation first.
24512       // x >= y ? x-y : 0 --> subus x, y
24513       // x >  y ? x-y : 0 --> subus x, y
24514       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
24515           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
24516         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
24517
24518       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
24519         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
24520           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
24521             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
24522               // If the RHS is a constant we have to reverse the const
24523               // canonicalization.
24524               // x > C-1 ? x+-C : 0 --> subus x, C
24525               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
24526                   CondRHSConst->getAPIntValue() ==
24527                       (-OpRHSConst->getAPIntValue() - 1))
24528                 return DAG.getNode(
24529                     X86ISD::SUBUS, DL, VT, OpLHS,
24530                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
24531
24532           // Another special case: If C was a sign bit, the sub has been
24533           // canonicalized into a xor.
24534           // FIXME: Would it be better to use computeKnownBits to determine
24535           //        whether it's safe to decanonicalize the xor?
24536           // x s< 0 ? x^C : 0 --> subus x, C
24537           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
24538               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
24539               OpRHSConst->getAPIntValue().isSignBit())
24540             // Note that we have to rebuild the RHS constant here to ensure we
24541             // don't rely on particular values of undef lanes.
24542             return DAG.getNode(
24543                 X86ISD::SUBUS, DL, VT, OpLHS,
24544                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
24545         }
24546     }
24547   }
24548
24549   // Simplify vector selection if condition value type matches vselect
24550   // operand type
24551   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
24552     assert(Cond.getValueType().isVector() &&
24553            "vector select expects a vector selector!");
24554
24555     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
24556     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
24557
24558     // Try invert the condition if true value is not all 1s and false value
24559     // is not all 0s.
24560     if (!TValIsAllOnes && !FValIsAllZeros &&
24561         // Check if the selector will be produced by CMPP*/PCMP*
24562         Cond.getOpcode() == ISD::SETCC &&
24563         // Check if SETCC has already been promoted
24564         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
24565             CondVT) {
24566       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
24567       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
24568
24569       if (TValIsAllZeros || FValIsAllOnes) {
24570         SDValue CC = Cond.getOperand(2);
24571         ISD::CondCode NewCC =
24572           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
24573                                Cond.getOperand(0).getValueType().isInteger());
24574         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
24575         std::swap(LHS, RHS);
24576         TValIsAllOnes = FValIsAllOnes;
24577         FValIsAllZeros = TValIsAllZeros;
24578       }
24579     }
24580
24581     if (TValIsAllOnes || FValIsAllZeros) {
24582       SDValue Ret;
24583
24584       if (TValIsAllOnes && FValIsAllZeros)
24585         Ret = Cond;
24586       else if (TValIsAllOnes)
24587         Ret =
24588             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
24589       else if (FValIsAllZeros)
24590         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
24591                           DAG.getBitcast(CondVT, LHS));
24592
24593       return DAG.getBitcast(VT, Ret);
24594     }
24595   }
24596
24597   // We should generate an X86ISD::BLENDI from a vselect if its argument
24598   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
24599   // constants. This specific pattern gets generated when we split a
24600   // selector for a 512 bit vector in a machine without AVX512 (but with
24601   // 256-bit vectors), during legalization:
24602   //
24603   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
24604   //
24605   // Iff we find this pattern and the build_vectors are built from
24606   // constants, we translate the vselect into a shuffle_vector that we
24607   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
24608   if ((N->getOpcode() == ISD::VSELECT ||
24609        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
24610       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
24611     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
24612     if (Shuffle.getNode())
24613       return Shuffle;
24614   }
24615
24616   // If this is a *dynamic* select (non-constant condition) and we can match
24617   // this node with one of the variable blend instructions, restructure the
24618   // condition so that the blends can use the high bit of each element and use
24619   // SimplifyDemandedBits to simplify the condition operand.
24620   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
24621       !DCI.isBeforeLegalize() &&
24622       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
24623     unsigned BitWidth = Cond.getValueType().getScalarSizeInBits();
24624
24625     // Don't optimize vector selects that map to mask-registers.
24626     if (BitWidth == 1)
24627       return SDValue();
24628
24629     // We can only handle the cases where VSELECT is directly legal on the
24630     // subtarget. We custom lower VSELECT nodes with constant conditions and
24631     // this makes it hard to see whether a dynamic VSELECT will correctly
24632     // lower, so we both check the operation's status and explicitly handle the
24633     // cases where a *dynamic* blend will fail even though a constant-condition
24634     // blend could be custom lowered.
24635     // FIXME: We should find a better way to handle this class of problems.
24636     // Potentially, we should combine constant-condition vselect nodes
24637     // pre-legalization into shuffles and not mark as many types as custom
24638     // lowered.
24639     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
24640       return SDValue();
24641     // FIXME: We don't support i16-element blends currently. We could and
24642     // should support them by making *all* the bits in the condition be set
24643     // rather than just the high bit and using an i8-element blend.
24644     if (VT.getVectorElementType() == MVT::i16)
24645       return SDValue();
24646     // Dynamic blending was only available from SSE4.1 onward.
24647     if (VT.is128BitVector() && !Subtarget->hasSSE41())
24648       return SDValue();
24649     // Byte blends are only available in AVX2
24650     if (VT == MVT::v32i8 && !Subtarget->hasAVX2())
24651       return SDValue();
24652
24653     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
24654     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
24655
24656     APInt KnownZero, KnownOne;
24657     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
24658                                           DCI.isBeforeLegalizeOps());
24659     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
24660         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
24661                                  TLO)) {
24662       // If we changed the computation somewhere in the DAG, this change
24663       // will affect all users of Cond.
24664       // Make sure it is fine and update all the nodes so that we do not
24665       // use the generic VSELECT anymore. Otherwise, we may perform
24666       // wrong optimizations as we messed up with the actual expectation
24667       // for the vector boolean values.
24668       if (Cond != TLO.Old) {
24669         // Check all uses of that condition operand to check whether it will be
24670         // consumed by non-BLEND instructions, which may depend on all bits are
24671         // set properly.
24672         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24673              I != E; ++I)
24674           if (I->getOpcode() != ISD::VSELECT)
24675             // TODO: Add other opcodes eventually lowered into BLEND.
24676             return SDValue();
24677
24678         // Update all the users of the condition, before committing the change,
24679         // so that the VSELECT optimizations that expect the correct vector
24680         // boolean value will not be triggered.
24681         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24682              I != E; ++I)
24683           DAG.ReplaceAllUsesOfValueWith(
24684               SDValue(*I, 0),
24685               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
24686                           Cond, I->getOperand(1), I->getOperand(2)));
24687         DCI.CommitTargetLoweringOpt(TLO);
24688         return SDValue();
24689       }
24690       // At this point, only Cond is changed. Change the condition
24691       // just for N to keep the opportunity to optimize all other
24692       // users their own way.
24693       DAG.ReplaceAllUsesOfValueWith(
24694           SDValue(N, 0),
24695           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
24696                       TLO.New, N->getOperand(1), N->getOperand(2)));
24697       return SDValue();
24698     }
24699   }
24700
24701   return SDValue();
24702 }
24703
24704 // Check whether a boolean test is testing a boolean value generated by
24705 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
24706 // code.
24707 //
24708 // Simplify the following patterns:
24709 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
24710 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
24711 // to (Op EFLAGS Cond)
24712 //
24713 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
24714 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
24715 // to (Op EFLAGS !Cond)
24716 //
24717 // where Op could be BRCOND or CMOV.
24718 //
24719 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
24720   // Quit if not CMP and SUB with its value result used.
24721   if (Cmp.getOpcode() != X86ISD::CMP &&
24722       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
24723       return SDValue();
24724
24725   // Quit if not used as a boolean value.
24726   if (CC != X86::COND_E && CC != X86::COND_NE)
24727     return SDValue();
24728
24729   // Check CMP operands. One of them should be 0 or 1 and the other should be
24730   // an SetCC or extended from it.
24731   SDValue Op1 = Cmp.getOperand(0);
24732   SDValue Op2 = Cmp.getOperand(1);
24733
24734   SDValue SetCC;
24735   const ConstantSDNode* C = nullptr;
24736   bool needOppositeCond = (CC == X86::COND_E);
24737   bool checkAgainstTrue = false; // Is it a comparison against 1?
24738
24739   if ((C = dyn_cast<ConstantSDNode>(Op1)))
24740     SetCC = Op2;
24741   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
24742     SetCC = Op1;
24743   else // Quit if all operands are not constants.
24744     return SDValue();
24745
24746   if (C->getZExtValue() == 1) {
24747     needOppositeCond = !needOppositeCond;
24748     checkAgainstTrue = true;
24749   } else if (C->getZExtValue() != 0)
24750     // Quit if the constant is neither 0 or 1.
24751     return SDValue();
24752
24753   bool truncatedToBoolWithAnd = false;
24754   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
24755   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
24756          SetCC.getOpcode() == ISD::TRUNCATE ||
24757          SetCC.getOpcode() == ISD::AND) {
24758     if (SetCC.getOpcode() == ISD::AND) {
24759       int OpIdx = -1;
24760       if (isOneConstant(SetCC.getOperand(0)))
24761         OpIdx = 1;
24762       if (isOneConstant(SetCC.getOperand(1)))
24763         OpIdx = 0;
24764       if (OpIdx == -1)
24765         break;
24766       SetCC = SetCC.getOperand(OpIdx);
24767       truncatedToBoolWithAnd = true;
24768     } else
24769       SetCC = SetCC.getOperand(0);
24770   }
24771
24772   switch (SetCC.getOpcode()) {
24773   case X86ISD::SETCC_CARRY:
24774     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
24775     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
24776     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
24777     // truncated to i1 using 'and'.
24778     if (checkAgainstTrue && !truncatedToBoolWithAnd)
24779       break;
24780     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
24781            "Invalid use of SETCC_CARRY!");
24782     // FALL THROUGH
24783   case X86ISD::SETCC:
24784     // Set the condition code or opposite one if necessary.
24785     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
24786     if (needOppositeCond)
24787       CC = X86::GetOppositeBranchCondition(CC);
24788     return SetCC.getOperand(1);
24789   case X86ISD::CMOV: {
24790     // Check whether false/true value has canonical one, i.e. 0 or 1.
24791     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
24792     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
24793     // Quit if true value is not a constant.
24794     if (!TVal)
24795       return SDValue();
24796     // Quit if false value is not a constant.
24797     if (!FVal) {
24798       SDValue Op = SetCC.getOperand(0);
24799       // Skip 'zext' or 'trunc' node.
24800       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
24801           Op.getOpcode() == ISD::TRUNCATE)
24802         Op = Op.getOperand(0);
24803       // A special case for rdrand/rdseed, where 0 is set if false cond is
24804       // found.
24805       if ((Op.getOpcode() != X86ISD::RDRAND &&
24806            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
24807         return SDValue();
24808     }
24809     // Quit if false value is not the constant 0 or 1.
24810     bool FValIsFalse = true;
24811     if (FVal && FVal->getZExtValue() != 0) {
24812       if (FVal->getZExtValue() != 1)
24813         return SDValue();
24814       // If FVal is 1, opposite cond is needed.
24815       needOppositeCond = !needOppositeCond;
24816       FValIsFalse = false;
24817     }
24818     // Quit if TVal is not the constant opposite of FVal.
24819     if (FValIsFalse && TVal->getZExtValue() != 1)
24820       return SDValue();
24821     if (!FValIsFalse && TVal->getZExtValue() != 0)
24822       return SDValue();
24823     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
24824     if (needOppositeCond)
24825       CC = X86::GetOppositeBranchCondition(CC);
24826     return SetCC.getOperand(3);
24827   }
24828   }
24829
24830   return SDValue();
24831 }
24832
24833 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
24834 /// Match:
24835 ///   (X86or (X86setcc) (X86setcc))
24836 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
24837 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
24838                                            X86::CondCode &CC1, SDValue &Flags,
24839                                            bool &isAnd) {
24840   if (Cond->getOpcode() == X86ISD::CMP) {
24841     if (!isNullConstant(Cond->getOperand(1)))
24842       return false;
24843
24844     Cond = Cond->getOperand(0);
24845   }
24846
24847   isAnd = false;
24848
24849   SDValue SetCC0, SetCC1;
24850   switch (Cond->getOpcode()) {
24851   default: return false;
24852   case ISD::AND:
24853   case X86ISD::AND:
24854     isAnd = true;
24855     // fallthru
24856   case ISD::OR:
24857   case X86ISD::OR:
24858     SetCC0 = Cond->getOperand(0);
24859     SetCC1 = Cond->getOperand(1);
24860     break;
24861   };
24862
24863   // Make sure we have SETCC nodes, using the same flags value.
24864   if (SetCC0.getOpcode() != X86ISD::SETCC ||
24865       SetCC1.getOpcode() != X86ISD::SETCC ||
24866       SetCC0->getOperand(1) != SetCC1->getOperand(1))
24867     return false;
24868
24869   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
24870   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
24871   Flags = SetCC0->getOperand(1);
24872   return true;
24873 }
24874
24875 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24876 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
24877                                   TargetLowering::DAGCombinerInfo &DCI,
24878                                   const X86Subtarget *Subtarget) {
24879   SDLoc DL(N);
24880
24881   // If the flag operand isn't dead, don't touch this CMOV.
24882   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
24883     return SDValue();
24884
24885   SDValue FalseOp = N->getOperand(0);
24886   SDValue TrueOp = N->getOperand(1);
24887   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
24888   SDValue Cond = N->getOperand(3);
24889
24890   if (CC == X86::COND_E || CC == X86::COND_NE) {
24891     switch (Cond.getOpcode()) {
24892     default: break;
24893     case X86ISD::BSR:
24894     case X86ISD::BSF:
24895       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
24896       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
24897         return (CC == X86::COND_E) ? FalseOp : TrueOp;
24898     }
24899   }
24900
24901   SDValue Flags;
24902
24903   Flags = checkBoolTestSetCCCombine(Cond, CC);
24904   if (Flags.getNode() &&
24905       // Extra check as FCMOV only supports a subset of X86 cond.
24906       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
24907     SDValue Ops[] = { FalseOp, TrueOp,
24908                       DAG.getConstant(CC, DL, MVT::i8), Flags };
24909     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24910   }
24911
24912   // If this is a select between two integer constants, try to do some
24913   // optimizations.  Note that the operands are ordered the opposite of SELECT
24914   // operands.
24915   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
24916     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
24917       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
24918       // larger than FalseC (the false value).
24919       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
24920         CC = X86::GetOppositeBranchCondition(CC);
24921         std::swap(TrueC, FalseC);
24922         std::swap(TrueOp, FalseOp);
24923       }
24924
24925       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
24926       // This is efficient for any integer data type (including i8/i16) and
24927       // shift amount.
24928       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
24929         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24930                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24931
24932         // Zero extend the condition if needed.
24933         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
24934
24935         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24936         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
24937                            DAG.getConstant(ShAmt, DL, MVT::i8));
24938         if (N->getNumValues() == 2)  // Dead flag value?
24939           return DCI.CombineTo(N, Cond, SDValue());
24940         return Cond;
24941       }
24942
24943       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
24944       // for any integer data type, including i8/i16.
24945       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24946         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24947                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24948
24949         // Zero extend the condition if needed.
24950         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24951                            FalseC->getValueType(0), Cond);
24952         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24953                            SDValue(FalseC, 0));
24954
24955         if (N->getNumValues() == 2)  // Dead flag value?
24956           return DCI.CombineTo(N, Cond, SDValue());
24957         return Cond;
24958       }
24959
24960       // Optimize cases that will turn into an LEA instruction.  This requires
24961       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24962       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24963         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24964         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24965
24966         bool isFastMultiplier = false;
24967         if (Diff < 10) {
24968           switch ((unsigned char)Diff) {
24969           default: break;
24970           case 1:  // result = add base, cond
24971           case 2:  // result = lea base(    , cond*2)
24972           case 3:  // result = lea base(cond, cond*2)
24973           case 4:  // result = lea base(    , cond*4)
24974           case 5:  // result = lea base(cond, cond*4)
24975           case 8:  // result = lea base(    , cond*8)
24976           case 9:  // result = lea base(cond, cond*8)
24977             isFastMultiplier = true;
24978             break;
24979           }
24980         }
24981
24982         if (isFastMultiplier) {
24983           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24984           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24985                              DAG.getConstant(CC, DL, MVT::i8), Cond);
24986           // Zero extend the condition if needed.
24987           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24988                              Cond);
24989           // Scale the condition by the difference.
24990           if (Diff != 1)
24991             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24992                                DAG.getConstant(Diff, DL, Cond.getValueType()));
24993
24994           // Add the base if non-zero.
24995           if (FalseC->getAPIntValue() != 0)
24996             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24997                                SDValue(FalseC, 0));
24998           if (N->getNumValues() == 2)  // Dead flag value?
24999             return DCI.CombineTo(N, Cond, SDValue());
25000           return Cond;
25001         }
25002       }
25003     }
25004   }
25005
25006   // Handle these cases:
25007   //   (select (x != c), e, c) -> select (x != c), e, x),
25008   //   (select (x == c), c, e) -> select (x == c), x, e)
25009   // where the c is an integer constant, and the "select" is the combination
25010   // of CMOV and CMP.
25011   //
25012   // The rationale for this change is that the conditional-move from a constant
25013   // needs two instructions, however, conditional-move from a register needs
25014   // only one instruction.
25015   //
25016   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
25017   //  some instruction-combining opportunities. This opt needs to be
25018   //  postponed as late as possible.
25019   //
25020   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
25021     // the DCI.xxxx conditions are provided to postpone the optimization as
25022     // late as possible.
25023
25024     ConstantSDNode *CmpAgainst = nullptr;
25025     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
25026         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
25027         !isa<ConstantSDNode>(Cond.getOperand(0))) {
25028
25029       if (CC == X86::COND_NE &&
25030           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
25031         CC = X86::GetOppositeBranchCondition(CC);
25032         std::swap(TrueOp, FalseOp);
25033       }
25034
25035       if (CC == X86::COND_E &&
25036           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
25037         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
25038                           DAG.getConstant(CC, DL, MVT::i8), Cond };
25039         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
25040       }
25041     }
25042   }
25043
25044   // Fold and/or of setcc's to double CMOV:
25045   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
25046   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
25047   //
25048   // This combine lets us generate:
25049   //   cmovcc1 (jcc1 if we don't have CMOV)
25050   //   cmovcc2 (same)
25051   // instead of:
25052   //   setcc1
25053   //   setcc2
25054   //   and/or
25055   //   cmovne (jne if we don't have CMOV)
25056   // When we can't use the CMOV instruction, it might increase branch
25057   // mispredicts.
25058   // When we can use CMOV, or when there is no mispredict, this improves
25059   // throughput and reduces register pressure.
25060   //
25061   if (CC == X86::COND_NE) {
25062     SDValue Flags;
25063     X86::CondCode CC0, CC1;
25064     bool isAndSetCC;
25065     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
25066       if (isAndSetCC) {
25067         std::swap(FalseOp, TrueOp);
25068         CC0 = X86::GetOppositeBranchCondition(CC0);
25069         CC1 = X86::GetOppositeBranchCondition(CC1);
25070       }
25071
25072       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
25073         Flags};
25074       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
25075       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
25076       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
25077       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
25078       return CMOV;
25079     }
25080   }
25081
25082   return SDValue();
25083 }
25084
25085 /// PerformMulCombine - Optimize a single multiply with constant into two
25086 /// in order to implement it with two cheaper instructions, e.g.
25087 /// LEA + SHL, LEA + LEA.
25088 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
25089                                  TargetLowering::DAGCombinerInfo &DCI) {
25090   // An imul is usually smaller than the alternative sequence.
25091   if (DAG.getMachineFunction().getFunction()->optForMinSize())
25092     return SDValue();
25093
25094   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
25095     return SDValue();
25096
25097   EVT VT = N->getValueType(0);
25098   if (VT != MVT::i64 && VT != MVT::i32)
25099     return SDValue();
25100
25101   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
25102   if (!C)
25103     return SDValue();
25104   uint64_t MulAmt = C->getZExtValue();
25105   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
25106     return SDValue();
25107
25108   uint64_t MulAmt1 = 0;
25109   uint64_t MulAmt2 = 0;
25110   if ((MulAmt % 9) == 0) {
25111     MulAmt1 = 9;
25112     MulAmt2 = MulAmt / 9;
25113   } else if ((MulAmt % 5) == 0) {
25114     MulAmt1 = 5;
25115     MulAmt2 = MulAmt / 5;
25116   } else if ((MulAmt % 3) == 0) {
25117     MulAmt1 = 3;
25118     MulAmt2 = MulAmt / 3;
25119   }
25120
25121   SDLoc DL(N);
25122   SDValue NewMul;
25123   if (MulAmt2 &&
25124       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
25125
25126     if (isPowerOf2_64(MulAmt2) &&
25127         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
25128       // If second multiplifer is pow2, issue it first. We want the multiply by
25129       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
25130       // is an add.
25131       std::swap(MulAmt1, MulAmt2);
25132
25133     if (isPowerOf2_64(MulAmt1))
25134       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25135                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
25136     else
25137       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
25138                            DAG.getConstant(MulAmt1, DL, VT));
25139
25140     if (isPowerOf2_64(MulAmt2))
25141       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
25142                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
25143     else
25144       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
25145                            DAG.getConstant(MulAmt2, DL, VT));
25146   }
25147
25148   if (!NewMul) {
25149     assert(MulAmt != 0 && MulAmt != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX)
25150            && "Both cases that could cause potential overflows should have "
25151               "already been handled.");
25152     if (isPowerOf2_64(MulAmt - 1))
25153       // (mul x, 2^N + 1) => (add (shl x, N), x)
25154       NewMul = DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
25155                                 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25156                                 DAG.getConstant(Log2_64(MulAmt - 1), DL,
25157                                 MVT::i8)));
25158
25159     else if (isPowerOf2_64(MulAmt + 1))
25160       // (mul x, 2^N - 1) => (sub (shl x, N), x)
25161       NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getNode(ISD::SHL, DL, VT,
25162                                 N->getOperand(0),
25163                                 DAG.getConstant(Log2_64(MulAmt + 1),
25164                                 DL, MVT::i8)), N->getOperand(0));
25165   }
25166
25167   if (NewMul)
25168     // Do not add new nodes to DAG combiner worklist.
25169     DCI.CombineTo(N, NewMul, false);
25170
25171   return SDValue();
25172 }
25173
25174 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
25175   SDValue N0 = N->getOperand(0);
25176   SDValue N1 = N->getOperand(1);
25177   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
25178   EVT VT = N0.getValueType();
25179
25180   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
25181   // since the result of setcc_c is all zero's or all ones.
25182   if (VT.isInteger() && !VT.isVector() &&
25183       N1C && N0.getOpcode() == ISD::AND &&
25184       N0.getOperand(1).getOpcode() == ISD::Constant) {
25185     SDValue N00 = N0.getOperand(0);
25186     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
25187     APInt ShAmt = N1C->getAPIntValue();
25188     Mask = Mask.shl(ShAmt);
25189     bool MaskOK = false;
25190     // We can handle cases concerning bit-widening nodes containing setcc_c if
25191     // we carefully interrogate the mask to make sure we are semantics
25192     // preserving.
25193     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
25194     // of the underlying setcc_c operation if the setcc_c was zero extended.
25195     // Consider the following example:
25196     //   zext(setcc_c)                 -> i32 0x0000FFFF
25197     //   c1                            -> i32 0x0000FFFF
25198     //   c2                            -> i32 0x00000001
25199     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
25200     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
25201     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25202       MaskOK = true;
25203     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
25204                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25205       MaskOK = true;
25206     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
25207                 N00.getOpcode() == ISD::ANY_EXTEND) &&
25208                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25209       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
25210     }
25211     if (MaskOK && Mask != 0) {
25212       SDLoc DL(N);
25213       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
25214     }
25215   }
25216
25217   // Hardware support for vector shifts is sparse which makes us scalarize the
25218   // vector operations in many cases. Also, on sandybridge ADD is faster than
25219   // shl.
25220   // (shl V, 1) -> add V,V
25221   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
25222     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
25223       assert(N0.getValueType().isVector() && "Invalid vector shift type");
25224       // We shift all of the values by one. In many cases we do not have
25225       // hardware support for this operation. This is better expressed as an ADD
25226       // of two values.
25227       if (N1SplatC->getAPIntValue() == 1)
25228         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
25229     }
25230
25231   return SDValue();
25232 }
25233
25234 static SDValue PerformSRACombine(SDNode *N, SelectionDAG &DAG) {
25235   SDValue N0 = N->getOperand(0);
25236   SDValue N1 = N->getOperand(1);
25237   EVT VT = N0.getValueType();
25238   unsigned Size = VT.getSizeInBits();
25239
25240   // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
25241   // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
25242   // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
25243   // depending on sign of (SarConst - [56,48,32,24,16])
25244
25245   // sexts in X86 are MOVs. The MOVs have the same code size
25246   // as above SHIFTs (only SHIFT on 1 has lower code size).
25247   // However the MOVs have 2 advantages to a SHIFT:
25248   // 1. MOVs can write to a register that differs from source
25249   // 2. MOVs accept memory operands
25250
25251   if (!VT.isInteger() || VT.isVector() || N1.getOpcode() != ISD::Constant ||
25252       N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
25253       N0.getOperand(1).getOpcode() != ISD::Constant)
25254     return SDValue();
25255
25256   SDValue N00 = N0.getOperand(0);
25257   SDValue N01 = N0.getOperand(1);
25258   APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
25259   APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
25260   EVT CVT = N1.getValueType();
25261
25262   if (SarConst.isNegative())
25263     return SDValue();
25264
25265   for (MVT SVT : MVT::integer_valuetypes()) {
25266     unsigned ShiftSize = SVT.getSizeInBits();
25267     // skipping types without corresponding sext/zext and
25268     // ShlConst that is not one of [56,48,32,24,16]
25269     if (ShiftSize < 8 || ShiftSize > 64 || ShlConst != Size - ShiftSize)
25270       continue;
25271     SDLoc DL(N);
25272     SDValue NN =
25273         DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
25274     SarConst = SarConst - (Size - ShiftSize);
25275     if (SarConst == 0)
25276       return NN;
25277     else if (SarConst.isNegative())
25278       return DAG.getNode(ISD::SHL, DL, VT, NN,
25279                          DAG.getConstant(-SarConst, DL, CVT));
25280     else
25281       return DAG.getNode(ISD::SRA, DL, VT, NN,
25282                          DAG.getConstant(SarConst, DL, CVT));
25283   }
25284   return SDValue();
25285 }
25286
25287 /// \brief Returns a vector of 0s if the node in input is a vector logical
25288 /// shift by a constant amount which is known to be bigger than or equal
25289 /// to the vector element size in bits.
25290 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
25291                                       const X86Subtarget *Subtarget) {
25292   EVT VT = N->getValueType(0);
25293
25294   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
25295       (!Subtarget->hasInt256() ||
25296        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
25297     return SDValue();
25298
25299   SDValue Amt = N->getOperand(1);
25300   SDLoc DL(N);
25301   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
25302     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
25303       APInt ShiftAmt = AmtSplat->getAPIntValue();
25304       unsigned MaxAmount =
25305         VT.getSimpleVT().getVectorElementType().getSizeInBits();
25306
25307       // SSE2/AVX2 logical shifts always return a vector of 0s
25308       // if the shift amount is bigger than or equal to
25309       // the element size. The constant shift amount will be
25310       // encoded as a 8-bit immediate.
25311       if (ShiftAmt.trunc(8).uge(MaxAmount))
25312         return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, DL);
25313     }
25314
25315   return SDValue();
25316 }
25317
25318 /// PerformShiftCombine - Combine shifts.
25319 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
25320                                    TargetLowering::DAGCombinerInfo &DCI,
25321                                    const X86Subtarget *Subtarget) {
25322   if (N->getOpcode() == ISD::SHL)
25323     if (SDValue V = PerformSHLCombine(N, DAG))
25324       return V;
25325
25326   if (N->getOpcode() == ISD::SRA)
25327     if (SDValue V = PerformSRACombine(N, DAG))
25328       return V;
25329
25330   // Try to fold this logical shift into a zero vector.
25331   if (N->getOpcode() != ISD::SRA)
25332     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
25333       return V;
25334
25335   return SDValue();
25336 }
25337
25338 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
25339 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
25340 // and friends.  Likewise for OR -> CMPNEQSS.
25341 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
25342                             TargetLowering::DAGCombinerInfo &DCI,
25343                             const X86Subtarget *Subtarget) {
25344   unsigned opcode;
25345
25346   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
25347   // we're requiring SSE2 for both.
25348   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
25349     SDValue N0 = N->getOperand(0);
25350     SDValue N1 = N->getOperand(1);
25351     SDValue CMP0 = N0->getOperand(1);
25352     SDValue CMP1 = N1->getOperand(1);
25353     SDLoc DL(N);
25354
25355     // The SETCCs should both refer to the same CMP.
25356     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
25357       return SDValue();
25358
25359     SDValue CMP00 = CMP0->getOperand(0);
25360     SDValue CMP01 = CMP0->getOperand(1);
25361     EVT     VT    = CMP00.getValueType();
25362
25363     if (VT == MVT::f32 || VT == MVT::f64) {
25364       bool ExpectingFlags = false;
25365       // Check for any users that want flags:
25366       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
25367            !ExpectingFlags && UI != UE; ++UI)
25368         switch (UI->getOpcode()) {
25369         default:
25370         case ISD::BR_CC:
25371         case ISD::BRCOND:
25372         case ISD::SELECT:
25373           ExpectingFlags = true;
25374           break;
25375         case ISD::CopyToReg:
25376         case ISD::SIGN_EXTEND:
25377         case ISD::ZERO_EXTEND:
25378         case ISD::ANY_EXTEND:
25379           break;
25380         }
25381
25382       if (!ExpectingFlags) {
25383         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
25384         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
25385
25386         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
25387           X86::CondCode tmp = cc0;
25388           cc0 = cc1;
25389           cc1 = tmp;
25390         }
25391
25392         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
25393             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
25394           // FIXME: need symbolic constants for these magic numbers.
25395           // See X86ATTInstPrinter.cpp:printSSECC().
25396           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
25397           if (Subtarget->hasAVX512()) {
25398             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
25399                                          CMP01,
25400                                          DAG.getConstant(x86cc, DL, MVT::i8));
25401             if (N->getValueType(0) != MVT::i1)
25402               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
25403                                  FSetCC);
25404             return FSetCC;
25405           }
25406           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
25407                                               CMP00.getValueType(), CMP00, CMP01,
25408                                               DAG.getConstant(x86cc, DL,
25409                                                               MVT::i8));
25410
25411           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
25412           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
25413
25414           if (is64BitFP && !Subtarget->is64Bit()) {
25415             // On a 32-bit target, we cannot bitcast the 64-bit float to a
25416             // 64-bit integer, since that's not a legal type. Since
25417             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
25418             // bits, but can do this little dance to extract the lowest 32 bits
25419             // and work with those going forward.
25420             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
25421                                            OnesOrZeroesF);
25422             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
25423             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
25424                                         Vector32, DAG.getIntPtrConstant(0, DL));
25425             IntVT = MVT::i32;
25426           }
25427
25428           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
25429           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
25430                                       DAG.getConstant(1, DL, IntVT));
25431           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
25432                                               ANDed);
25433           return OneBitOfTruth;
25434         }
25435       }
25436     }
25437   }
25438   return SDValue();
25439 }
25440
25441 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
25442 /// so it can be folded inside ANDNP.
25443 static bool CanFoldXORWithAllOnes(const SDNode *N) {
25444   EVT VT = N->getValueType(0);
25445
25446   // Match direct AllOnes for 128 and 256-bit vectors
25447   if (ISD::isBuildVectorAllOnes(N))
25448     return true;
25449
25450   // Look through a bit convert.
25451   if (N->getOpcode() == ISD::BITCAST)
25452     N = N->getOperand(0).getNode();
25453
25454   // Sometimes the operand may come from a insert_subvector building a 256-bit
25455   // allones vector
25456   if (VT.is256BitVector() &&
25457       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
25458     SDValue V1 = N->getOperand(0);
25459     SDValue V2 = N->getOperand(1);
25460
25461     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
25462         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
25463         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
25464         ISD::isBuildVectorAllOnes(V2.getNode()))
25465       return true;
25466   }
25467
25468   return false;
25469 }
25470
25471 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
25472 // register. In most cases we actually compare or select YMM-sized registers
25473 // and mixing the two types creates horrible code. This method optimizes
25474 // some of the transition sequences.
25475 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
25476                                  TargetLowering::DAGCombinerInfo &DCI,
25477                                  const X86Subtarget *Subtarget) {
25478   EVT VT = N->getValueType(0);
25479   if (!VT.is256BitVector())
25480     return SDValue();
25481
25482   assert((N->getOpcode() == ISD::ANY_EXTEND ||
25483           N->getOpcode() == ISD::ZERO_EXTEND ||
25484           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
25485
25486   SDValue Narrow = N->getOperand(0);
25487   EVT NarrowVT = Narrow->getValueType(0);
25488   if (!NarrowVT.is128BitVector())
25489     return SDValue();
25490
25491   if (Narrow->getOpcode() != ISD::XOR &&
25492       Narrow->getOpcode() != ISD::AND &&
25493       Narrow->getOpcode() != ISD::OR)
25494     return SDValue();
25495
25496   SDValue N0  = Narrow->getOperand(0);
25497   SDValue N1  = Narrow->getOperand(1);
25498   SDLoc DL(Narrow);
25499
25500   // The Left side has to be a trunc.
25501   if (N0.getOpcode() != ISD::TRUNCATE)
25502     return SDValue();
25503
25504   // The type of the truncated inputs.
25505   EVT WideVT = N0->getOperand(0)->getValueType(0);
25506   if (WideVT != VT)
25507     return SDValue();
25508
25509   // The right side has to be a 'trunc' or a constant vector.
25510   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
25511   ConstantSDNode *RHSConstSplat = nullptr;
25512   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
25513     RHSConstSplat = RHSBV->getConstantSplatNode();
25514   if (!RHSTrunc && !RHSConstSplat)
25515     return SDValue();
25516
25517   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25518
25519   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
25520     return SDValue();
25521
25522   // Set N0 and N1 to hold the inputs to the new wide operation.
25523   N0 = N0->getOperand(0);
25524   if (RHSConstSplat) {
25525     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getVectorElementType(),
25526                      SDValue(RHSConstSplat, 0));
25527     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
25528     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
25529   } else if (RHSTrunc) {
25530     N1 = N1->getOperand(0);
25531   }
25532
25533   // Generate the wide operation.
25534   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
25535   unsigned Opcode = N->getOpcode();
25536   switch (Opcode) {
25537   case ISD::ANY_EXTEND:
25538     return Op;
25539   case ISD::ZERO_EXTEND: {
25540     unsigned InBits = NarrowVT.getScalarSizeInBits();
25541     APInt Mask = APInt::getAllOnesValue(InBits);
25542     Mask = Mask.zext(VT.getScalarSizeInBits());
25543     return DAG.getNode(ISD::AND, DL, VT,
25544                        Op, DAG.getConstant(Mask, DL, VT));
25545   }
25546   case ISD::SIGN_EXTEND:
25547     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
25548                        Op, DAG.getValueType(NarrowVT));
25549   default:
25550     llvm_unreachable("Unexpected opcode");
25551   }
25552 }
25553
25554 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
25555                                  TargetLowering::DAGCombinerInfo &DCI,
25556                                  const X86Subtarget *Subtarget) {
25557   SDValue N0 = N->getOperand(0);
25558   SDValue N1 = N->getOperand(1);
25559   SDLoc DL(N);
25560
25561   // A vector zext_in_reg may be represented as a shuffle,
25562   // feeding into a bitcast (this represents anyext) feeding into
25563   // an and with a mask.
25564   // We'd like to try to combine that into a shuffle with zero
25565   // plus a bitcast, removing the and.
25566   if (N0.getOpcode() != ISD::BITCAST ||
25567       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
25568     return SDValue();
25569
25570   // The other side of the AND should be a splat of 2^C, where C
25571   // is the number of bits in the source type.
25572   if (N1.getOpcode() == ISD::BITCAST)
25573     N1 = N1.getOperand(0);
25574   if (N1.getOpcode() != ISD::BUILD_VECTOR)
25575     return SDValue();
25576   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
25577
25578   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
25579   EVT SrcType = Shuffle->getValueType(0);
25580
25581   // We expect a single-source shuffle
25582   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
25583     return SDValue();
25584
25585   unsigned SrcSize = SrcType.getScalarSizeInBits();
25586
25587   APInt SplatValue, SplatUndef;
25588   unsigned SplatBitSize;
25589   bool HasAnyUndefs;
25590   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
25591                                 SplatBitSize, HasAnyUndefs))
25592     return SDValue();
25593
25594   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
25595   // Make sure the splat matches the mask we expect
25596   if (SplatBitSize > ResSize ||
25597       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
25598     return SDValue();
25599
25600   // Make sure the input and output size make sense
25601   if (SrcSize >= ResSize || ResSize % SrcSize)
25602     return SDValue();
25603
25604   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
25605   // The number of u's between each two values depends on the ratio between
25606   // the source and dest type.
25607   unsigned ZextRatio = ResSize / SrcSize;
25608   bool IsZext = true;
25609   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
25610     if (i % ZextRatio) {
25611       if (Shuffle->getMaskElt(i) > 0) {
25612         // Expected undef
25613         IsZext = false;
25614         break;
25615       }
25616     } else {
25617       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
25618         // Expected element number
25619         IsZext = false;
25620         break;
25621       }
25622     }
25623   }
25624
25625   if (!IsZext)
25626     return SDValue();
25627
25628   // Ok, perform the transformation - replace the shuffle with
25629   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
25630   // (instead of undef) where the k elements come from the zero vector.
25631   SmallVector<int, 8> Mask;
25632   unsigned NumElems = SrcType.getVectorNumElements();
25633   for (unsigned i = 0; i < NumElems; ++i)
25634     if (i % ZextRatio)
25635       Mask.push_back(NumElems);
25636     else
25637       Mask.push_back(i / ZextRatio);
25638
25639   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
25640     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
25641   return DAG.getBitcast(N0.getValueType(), NewShuffle);
25642 }
25643
25644 /// If both input operands of a logic op are being cast from floating point
25645 /// types, try to convert this into a floating point logic node to avoid
25646 /// unnecessary moves from SSE to integer registers.
25647 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
25648                                         const X86Subtarget *Subtarget) {
25649   unsigned FPOpcode = ISD::DELETED_NODE;
25650   if (N->getOpcode() == ISD::AND)
25651     FPOpcode = X86ISD::FAND;
25652   else if (N->getOpcode() == ISD::OR)
25653     FPOpcode = X86ISD::FOR;
25654   else if (N->getOpcode() == ISD::XOR)
25655     FPOpcode = X86ISD::FXOR;
25656
25657   assert(FPOpcode != ISD::DELETED_NODE &&
25658          "Unexpected input node for FP logic conversion");
25659
25660   EVT VT = N->getValueType(0);
25661   SDValue N0 = N->getOperand(0);
25662   SDValue N1 = N->getOperand(1);
25663   SDLoc DL(N);
25664   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
25665       ((Subtarget->hasSSE1() && VT == MVT::i32) ||
25666        (Subtarget->hasSSE2() && VT == MVT::i64))) {
25667     SDValue N00 = N0.getOperand(0);
25668     SDValue N10 = N1.getOperand(0);
25669     EVT N00Type = N00.getValueType();
25670     EVT N10Type = N10.getValueType();
25671     if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
25672       SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
25673       return DAG.getBitcast(VT, FPLogic);
25674     }
25675   }
25676   return SDValue();
25677 }
25678
25679 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
25680                                  TargetLowering::DAGCombinerInfo &DCI,
25681                                  const X86Subtarget *Subtarget) {
25682   if (DCI.isBeforeLegalizeOps())
25683     return SDValue();
25684
25685   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
25686     return Zext;
25687
25688   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25689     return R;
25690
25691   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25692     return FPLogic;
25693
25694   EVT VT = N->getValueType(0);
25695   SDValue N0 = N->getOperand(0);
25696   SDValue N1 = N->getOperand(1);
25697   SDLoc DL(N);
25698
25699   // Create BEXTR instructions
25700   // BEXTR is ((X >> imm) & (2**size-1))
25701   if (VT == MVT::i32 || VT == MVT::i64) {
25702     // Check for BEXTR.
25703     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
25704         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
25705       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
25706       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25707       if (MaskNode && ShiftNode) {
25708         uint64_t Mask = MaskNode->getZExtValue();
25709         uint64_t Shift = ShiftNode->getZExtValue();
25710         if (isMask_64(Mask)) {
25711           uint64_t MaskSize = countPopulation(Mask);
25712           if (Shift + MaskSize <= VT.getSizeInBits())
25713             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
25714                                DAG.getConstant(Shift | (MaskSize << 8), DL,
25715                                                VT));
25716         }
25717       }
25718     } // BEXTR
25719
25720     return SDValue();
25721   }
25722
25723   // Want to form ANDNP nodes:
25724   // 1) In the hopes of then easily combining them with OR and AND nodes
25725   //    to form PBLEND/PSIGN.
25726   // 2) To match ANDN packed intrinsics
25727   if (VT != MVT::v2i64 && VT != MVT::v4i64)
25728     return SDValue();
25729
25730   // Check LHS for vnot
25731   if (N0.getOpcode() == ISD::XOR &&
25732       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
25733       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
25734     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
25735
25736   // Check RHS for vnot
25737   if (N1.getOpcode() == ISD::XOR &&
25738       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
25739       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
25740     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
25741
25742   return SDValue();
25743 }
25744
25745 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
25746                                 TargetLowering::DAGCombinerInfo &DCI,
25747                                 const X86Subtarget *Subtarget) {
25748   if (DCI.isBeforeLegalizeOps())
25749     return SDValue();
25750
25751   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25752     return R;
25753
25754   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25755     return FPLogic;
25756
25757   SDValue N0 = N->getOperand(0);
25758   SDValue N1 = N->getOperand(1);
25759   EVT VT = N->getValueType(0);
25760
25761   // look for psign/blend
25762   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
25763     if (!Subtarget->hasSSSE3() ||
25764         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
25765       return SDValue();
25766
25767     // Canonicalize pandn to RHS
25768     if (N0.getOpcode() == X86ISD::ANDNP)
25769       std::swap(N0, N1);
25770     // or (and (m, y), (pandn m, x))
25771     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
25772       SDValue Mask = N1.getOperand(0);
25773       SDValue X    = N1.getOperand(1);
25774       SDValue Y;
25775       if (N0.getOperand(0) == Mask)
25776         Y = N0.getOperand(1);
25777       if (N0.getOperand(1) == Mask)
25778         Y = N0.getOperand(0);
25779
25780       // Check to see if the mask appeared in both the AND and ANDNP and
25781       if (!Y.getNode())
25782         return SDValue();
25783
25784       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
25785       // Look through mask bitcast.
25786       if (Mask.getOpcode() == ISD::BITCAST)
25787         Mask = Mask.getOperand(0);
25788       if (X.getOpcode() == ISD::BITCAST)
25789         X = X.getOperand(0);
25790       if (Y.getOpcode() == ISD::BITCAST)
25791         Y = Y.getOperand(0);
25792
25793       EVT MaskVT = Mask.getValueType();
25794
25795       // Validate that the Mask operand is a vector sra node.
25796       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
25797       // there is no psrai.b
25798       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
25799       unsigned SraAmt = ~0;
25800       if (Mask.getOpcode() == ISD::SRA) {
25801         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
25802           if (auto *AmtConst = AmtBV->getConstantSplatNode())
25803             SraAmt = AmtConst->getZExtValue();
25804       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
25805         SDValue SraC = Mask.getOperand(1);
25806         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
25807       }
25808       if ((SraAmt + 1) != EltBits)
25809         return SDValue();
25810
25811       SDLoc DL(N);
25812
25813       // Now we know we at least have a plendvb with the mask val.  See if
25814       // we can form a psignb/w/d.
25815       // psign = x.type == y.type == mask.type && y = sub(0, x);
25816       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
25817           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
25818           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
25819         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
25820                "Unsupported VT for PSIGN");
25821         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
25822         return DAG.getBitcast(VT, Mask);
25823       }
25824       // PBLENDVB only available on SSE 4.1
25825       if (!Subtarget->hasSSE41())
25826         return SDValue();
25827
25828       MVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
25829
25830       X = DAG.getBitcast(BlendVT, X);
25831       Y = DAG.getBitcast(BlendVT, Y);
25832       Mask = DAG.getBitcast(BlendVT, Mask);
25833       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
25834       return DAG.getBitcast(VT, Mask);
25835     }
25836   }
25837
25838   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
25839     return SDValue();
25840
25841   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
25842   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
25843
25844   // SHLD/SHRD instructions have lower register pressure, but on some
25845   // platforms they have higher latency than the equivalent
25846   // series of shifts/or that would otherwise be generated.
25847   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
25848   // have higher latencies and we are not optimizing for size.
25849   if (!OptForSize && Subtarget->isSHLDSlow())
25850     return SDValue();
25851
25852   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
25853     std::swap(N0, N1);
25854   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
25855     return SDValue();
25856   if (!N0.hasOneUse() || !N1.hasOneUse())
25857     return SDValue();
25858
25859   SDValue ShAmt0 = N0.getOperand(1);
25860   if (ShAmt0.getValueType() != MVT::i8)
25861     return SDValue();
25862   SDValue ShAmt1 = N1.getOperand(1);
25863   if (ShAmt1.getValueType() != MVT::i8)
25864     return SDValue();
25865   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
25866     ShAmt0 = ShAmt0.getOperand(0);
25867   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
25868     ShAmt1 = ShAmt1.getOperand(0);
25869
25870   SDLoc DL(N);
25871   unsigned Opc = X86ISD::SHLD;
25872   SDValue Op0 = N0.getOperand(0);
25873   SDValue Op1 = N1.getOperand(0);
25874   if (ShAmt0.getOpcode() == ISD::SUB) {
25875     Opc = X86ISD::SHRD;
25876     std::swap(Op0, Op1);
25877     std::swap(ShAmt0, ShAmt1);
25878   }
25879
25880   unsigned Bits = VT.getSizeInBits();
25881   if (ShAmt1.getOpcode() == ISD::SUB) {
25882     SDValue Sum = ShAmt1.getOperand(0);
25883     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
25884       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
25885       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
25886         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
25887       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
25888         return DAG.getNode(Opc, DL, VT,
25889                            Op0, Op1,
25890                            DAG.getNode(ISD::TRUNCATE, DL,
25891                                        MVT::i8, ShAmt0));
25892     }
25893   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
25894     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
25895     if (ShAmt0C &&
25896         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
25897       return DAG.getNode(Opc, DL, VT,
25898                          N0.getOperand(0), N1.getOperand(0),
25899                          DAG.getNode(ISD::TRUNCATE, DL,
25900                                        MVT::i8, ShAmt0));
25901   }
25902
25903   return SDValue();
25904 }
25905
25906 // Generate NEG and CMOV for integer abs.
25907 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
25908   EVT VT = N->getValueType(0);
25909
25910   // Since X86 does not have CMOV for 8-bit integer, we don't convert
25911   // 8-bit integer abs to NEG and CMOV.
25912   if (VT.isInteger() && VT.getSizeInBits() == 8)
25913     return SDValue();
25914
25915   SDValue N0 = N->getOperand(0);
25916   SDValue N1 = N->getOperand(1);
25917   SDLoc DL(N);
25918
25919   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
25920   // and change it to SUB and CMOV.
25921   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
25922       N0.getOpcode() == ISD::ADD &&
25923       N0.getOperand(1) == N1 &&
25924       N1.getOpcode() == ISD::SRA &&
25925       N1.getOperand(0) == N0.getOperand(0))
25926     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
25927       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
25928         // Generate SUB & CMOV.
25929         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
25930                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
25931
25932         SDValue Ops[] = { N0.getOperand(0), Neg,
25933                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
25934                           SDValue(Neg.getNode(), 1) };
25935         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
25936       }
25937   return SDValue();
25938 }
25939
25940 // Try to turn tests against the signbit in the form of:
25941 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
25942 // into:
25943 //   SETGT(X, -1)
25944 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
25945   // This is only worth doing if the output type is i8.
25946   if (N->getValueType(0) != MVT::i8)
25947     return SDValue();
25948
25949   SDValue N0 = N->getOperand(0);
25950   SDValue N1 = N->getOperand(1);
25951
25952   // We should be performing an xor against a truncated shift.
25953   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
25954     return SDValue();
25955
25956   // Make sure we are performing an xor against one.
25957   if (!isOneConstant(N1))
25958     return SDValue();
25959
25960   // SetCC on x86 zero extends so only act on this if it's a logical shift.
25961   SDValue Shift = N0.getOperand(0);
25962   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
25963     return SDValue();
25964
25965   // Make sure we are truncating from one of i16, i32 or i64.
25966   EVT ShiftTy = Shift.getValueType();
25967   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
25968     return SDValue();
25969
25970   // Make sure the shift amount extracts the sign bit.
25971   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
25972       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
25973     return SDValue();
25974
25975   // Create a greater-than comparison against -1.
25976   // N.B. Using SETGE against 0 works but we want a canonical looking
25977   // comparison, using SETGT matches up with what TranslateX86CC.
25978   SDLoc DL(N);
25979   SDValue ShiftOp = Shift.getOperand(0);
25980   EVT ShiftOpTy = ShiftOp.getValueType();
25981   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
25982                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
25983   return Cond;
25984 }
25985
25986 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
25987                                  TargetLowering::DAGCombinerInfo &DCI,
25988                                  const X86Subtarget *Subtarget) {
25989   if (DCI.isBeforeLegalizeOps())
25990     return SDValue();
25991
25992   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
25993     return RV;
25994
25995   if (Subtarget->hasCMov())
25996     if (SDValue RV = performIntegerAbsCombine(N, DAG))
25997       return RV;
25998
25999   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
26000     return FPLogic;
26001
26002   return SDValue();
26003 }
26004
26005 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
26006 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
26007 /// X86ISD::AVG instruction.
26008 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
26009                                 const X86Subtarget *Subtarget, SDLoc DL) {
26010   if (!VT.isVector() || !VT.isSimple())
26011     return SDValue();
26012   EVT InVT = In.getValueType();
26013   unsigned NumElems = VT.getVectorNumElements();
26014
26015   EVT ScalarVT = VT.getVectorElementType();
26016   if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) &&
26017         isPowerOf2_32(NumElems)))
26018     return SDValue();
26019
26020   // InScalarVT is the intermediate type in AVG pattern and it should be greater
26021   // than the original input type (i8/i16).
26022   EVT InScalarVT = InVT.getVectorElementType();
26023   if (InScalarVT.getSizeInBits() <= ScalarVT.getSizeInBits())
26024     return SDValue();
26025
26026   if (Subtarget->hasAVX512()) {
26027     if (VT.getSizeInBits() > 512)
26028       return SDValue();
26029   } else if (Subtarget->hasAVX2()) {
26030     if (VT.getSizeInBits() > 256)
26031       return SDValue();
26032   } else {
26033     if (VT.getSizeInBits() > 128)
26034       return SDValue();
26035   }
26036
26037   // Detect the following pattern:
26038   //
26039   //   %1 = zext <N x i8> %a to <N x i32>
26040   //   %2 = zext <N x i8> %b to <N x i32>
26041   //   %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
26042   //   %4 = add nuw nsw <N x i32> %3, %2
26043   //   %5 = lshr <N x i32> %N, <i32 1 x N>
26044   //   %6 = trunc <N x i32> %5 to <N x i8>
26045   //
26046   // In AVX512, the last instruction can also be a trunc store.
26047
26048   if (In.getOpcode() != ISD::SRL)
26049     return SDValue();
26050
26051   // A lambda checking the given SDValue is a constant vector and each element
26052   // is in the range [Min, Max].
26053   auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
26054     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(V);
26055     if (!BV || !BV->isConstant())
26056       return false;
26057     for (unsigned i = 0, e = V.getNumOperands(); i < e; i++) {
26058       ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(i));
26059       if (!C)
26060         return false;
26061       uint64_t Val = C->getZExtValue();
26062       if (Val < Min || Val > Max)
26063         return false;
26064     }
26065     return true;
26066   };
26067
26068   // Check if each element of the vector is left-shifted by one.
26069   auto LHS = In.getOperand(0);
26070   auto RHS = In.getOperand(1);
26071   if (!IsConstVectorInRange(RHS, 1, 1))
26072     return SDValue();
26073   if (LHS.getOpcode() != ISD::ADD)
26074     return SDValue();
26075
26076   // Detect a pattern of a + b + 1 where the order doesn't matter.
26077   SDValue Operands[3];
26078   Operands[0] = LHS.getOperand(0);
26079   Operands[1] = LHS.getOperand(1);
26080
26081   // Take care of the case when one of the operands is a constant vector whose
26082   // element is in the range [1, 256].
26083   if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
26084       Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
26085       Operands[0].getOperand(0).getValueType() == VT) {
26086     // The pattern is detected. Subtract one from the constant vector, then
26087     // demote it and emit X86ISD::AVG instruction.
26088     SDValue One = DAG.getConstant(1, DL, InScalarVT);
26089     SDValue Ones = DAG.getNode(ISD::BUILD_VECTOR, DL, InVT,
26090                                SmallVector<SDValue, 8>(NumElems, One));
26091     Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], Ones);
26092     Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
26093     return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26094                        Operands[1]);
26095   }
26096
26097   if (Operands[0].getOpcode() == ISD::ADD)
26098     std::swap(Operands[0], Operands[1]);
26099   else if (Operands[1].getOpcode() != ISD::ADD)
26100     return SDValue();
26101   Operands[2] = Operands[1].getOperand(0);
26102   Operands[1] = Operands[1].getOperand(1);
26103
26104   // Now we have three operands of two additions. Check that one of them is a
26105   // constant vector with ones, and the other two are promoted from i8/i16.
26106   for (int i = 0; i < 3; ++i) {
26107     if (!IsConstVectorInRange(Operands[i], 1, 1))
26108       continue;
26109     std::swap(Operands[i], Operands[2]);
26110
26111     // Check if Operands[0] and Operands[1] are results of type promotion.
26112     for (int j = 0; j < 2; ++j)
26113       if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
26114           Operands[j].getOperand(0).getValueType() != VT)
26115         return SDValue();
26116
26117     // The pattern is detected, emit X86ISD::AVG instruction.
26118     return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26119                        Operands[1].getOperand(0));
26120   }
26121
26122   return SDValue();
26123 }
26124
26125 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
26126 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
26127                                   TargetLowering::DAGCombinerInfo &DCI,
26128                                   const X86Subtarget *Subtarget) {
26129   LoadSDNode *Ld = cast<LoadSDNode>(N);
26130   EVT RegVT = Ld->getValueType(0);
26131   EVT MemVT = Ld->getMemoryVT();
26132   SDLoc dl(Ld);
26133   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26134
26135   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
26136   // into two 16-byte operations.
26137   ISD::LoadExtType Ext = Ld->getExtensionType();
26138   bool Fast;
26139   unsigned AddressSpace = Ld->getAddressSpace();
26140   unsigned Alignment = Ld->getAlignment();
26141   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
26142       Ext == ISD::NON_EXTLOAD &&
26143       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
26144                              AddressSpace, Alignment, &Fast) && !Fast) {
26145     unsigned NumElems = RegVT.getVectorNumElements();
26146     if (NumElems < 2)
26147       return SDValue();
26148
26149     SDValue Ptr = Ld->getBasePtr();
26150     SDValue Increment =
26151         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26152
26153     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
26154                                   NumElems/2);
26155     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26156                                 Ld->getPointerInfo(), Ld->isVolatile(),
26157                                 Ld->isNonTemporal(), Ld->isInvariant(),
26158                                 Alignment);
26159     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26160     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26161                                 Ld->getPointerInfo(), Ld->isVolatile(),
26162                                 Ld->isNonTemporal(), Ld->isInvariant(),
26163                                 std::min(16U, Alignment));
26164     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
26165                              Load1.getValue(1),
26166                              Load2.getValue(1));
26167
26168     SDValue NewVec = DAG.getUNDEF(RegVT);
26169     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
26170     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
26171     return DCI.CombineTo(N, NewVec, TF, true);
26172   }
26173
26174   return SDValue();
26175 }
26176
26177 /// PerformMLOADCombine - Resolve extending loads
26178 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
26179                                    TargetLowering::DAGCombinerInfo &DCI,
26180                                    const X86Subtarget *Subtarget) {
26181   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
26182   if (Mld->getExtensionType() != ISD::SEXTLOAD)
26183     return SDValue();
26184
26185   EVT VT = Mld->getValueType(0);
26186   unsigned NumElems = VT.getVectorNumElements();
26187   EVT LdVT = Mld->getMemoryVT();
26188   SDLoc dl(Mld);
26189
26190   assert(LdVT != VT && "Cannot extend to the same type");
26191   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
26192   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
26193   // From, To sizes and ElemCount must be pow of two
26194   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26195     "Unexpected size for extending masked load");
26196
26197   unsigned SizeRatio  = ToSz / FromSz;
26198   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
26199
26200   // Create a type on which we perform the shuffle
26201   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26202           LdVT.getScalarType(), NumElems*SizeRatio);
26203   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26204
26205   // Convert Src0 value
26206   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
26207   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
26208     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26209     for (unsigned i = 0; i != NumElems; ++i)
26210       ShuffleVec[i] = i * SizeRatio;
26211
26212     // Can't shuffle using an illegal type.
26213     assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26214            "WideVecVT should be legal");
26215     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
26216                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
26217   }
26218   // Prepare the new mask
26219   SDValue NewMask;
26220   SDValue Mask = Mld->getMask();
26221   if (Mask.getValueType() == VT) {
26222     // Mask and original value have the same type
26223     NewMask = DAG.getBitcast(WideVecVT, Mask);
26224     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26225     for (unsigned i = 0; i != NumElems; ++i)
26226       ShuffleVec[i] = i * SizeRatio;
26227     for (unsigned i = NumElems; i != NumElems * SizeRatio; ++i)
26228       ShuffleVec[i] = NumElems * SizeRatio;
26229     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26230                                    DAG.getConstant(0, dl, WideVecVT),
26231                                    &ShuffleVec[0]);
26232   }
26233   else {
26234     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26235     unsigned WidenNumElts = NumElems*SizeRatio;
26236     unsigned MaskNumElts = VT.getVectorNumElements();
26237     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
26238                                      WidenNumElts);
26239
26240     unsigned NumConcat = WidenNumElts / MaskNumElts;
26241     SmallVector<SDValue, 16> Ops(NumConcat);
26242     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26243     Ops[0] = Mask;
26244     for (unsigned i = 1; i != NumConcat; ++i)
26245       Ops[i] = ZeroVal;
26246
26247     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26248   }
26249
26250   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
26251                                      Mld->getBasePtr(), NewMask, WideSrc0,
26252                                      Mld->getMemoryVT(), Mld->getMemOperand(),
26253                                      ISD::NON_EXTLOAD);
26254   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
26255   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
26256 }
26257 /// PerformMSTORECombine - Resolve truncating stores
26258 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
26259                                     const X86Subtarget *Subtarget) {
26260   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
26261   if (!Mst->isTruncatingStore())
26262     return SDValue();
26263
26264   EVT VT = Mst->getValue().getValueType();
26265   unsigned NumElems = VT.getVectorNumElements();
26266   EVT StVT = Mst->getMemoryVT();
26267   SDLoc dl(Mst);
26268
26269   assert(StVT != VT && "Cannot truncate to the same type");
26270   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26271   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26272
26273   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26274
26275   // The truncating store is legal in some cases. For example
26276   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26277   // are designated for truncate store.
26278   // In this case we don't need any further transformations.
26279   if (TLI.isTruncStoreLegal(VT, StVT))
26280     return SDValue();
26281
26282   // From, To sizes and ElemCount must be pow of two
26283   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26284     "Unexpected size for truncating masked store");
26285   // We are going to use the original vector elt for storing.
26286   // Accumulated smaller vector elements must be a multiple of the store size.
26287   assert (((NumElems * FromSz) % ToSz) == 0 &&
26288           "Unexpected ratio for truncating masked store");
26289
26290   unsigned SizeRatio  = FromSz / ToSz;
26291   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26292
26293   // Create a type on which we perform the shuffle
26294   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26295           StVT.getScalarType(), NumElems*SizeRatio);
26296
26297   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26298
26299   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
26300   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26301   for (unsigned i = 0; i != NumElems; ++i)
26302     ShuffleVec[i] = i * SizeRatio;
26303
26304   // Can't shuffle using an illegal type.
26305   assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26306          "WideVecVT should be legal");
26307
26308   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26309                                               DAG.getUNDEF(WideVecVT),
26310                                               &ShuffleVec[0]);
26311
26312   SDValue NewMask;
26313   SDValue Mask = Mst->getMask();
26314   if (Mask.getValueType() == VT) {
26315     // Mask and original value have the same type
26316     NewMask = DAG.getBitcast(WideVecVT, Mask);
26317     for (unsigned i = 0; i != NumElems; ++i)
26318       ShuffleVec[i] = i * SizeRatio;
26319     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
26320       ShuffleVec[i] = NumElems*SizeRatio;
26321     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26322                                    DAG.getConstant(0, dl, WideVecVT),
26323                                    &ShuffleVec[0]);
26324   }
26325   else {
26326     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26327     unsigned WidenNumElts = NumElems*SizeRatio;
26328     unsigned MaskNumElts = VT.getVectorNumElements();
26329     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
26330                                      WidenNumElts);
26331
26332     unsigned NumConcat = WidenNumElts / MaskNumElts;
26333     SmallVector<SDValue, 16> Ops(NumConcat);
26334     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26335     Ops[0] = Mask;
26336     for (unsigned i = 1; i != NumConcat; ++i)
26337       Ops[i] = ZeroVal;
26338
26339     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26340   }
26341
26342   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal,
26343                             Mst->getBasePtr(), NewMask, StVT,
26344                             Mst->getMemOperand(), false);
26345 }
26346 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
26347 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
26348                                    const X86Subtarget *Subtarget) {
26349   StoreSDNode *St = cast<StoreSDNode>(N);
26350   EVT VT = St->getValue().getValueType();
26351   EVT StVT = St->getMemoryVT();
26352   SDLoc dl(St);
26353   SDValue StoredVal = St->getOperand(1);
26354   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26355
26356   // If we are saving a concatenation of two XMM registers and 32-byte stores
26357   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
26358   bool Fast;
26359   unsigned AddressSpace = St->getAddressSpace();
26360   unsigned Alignment = St->getAlignment();
26361   if (VT.is256BitVector() && StVT == VT &&
26362       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
26363                              AddressSpace, Alignment, &Fast) && !Fast) {
26364     unsigned NumElems = VT.getVectorNumElements();
26365     if (NumElems < 2)
26366       return SDValue();
26367
26368     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
26369     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
26370
26371     SDValue Stride =
26372         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26373     SDValue Ptr0 = St->getBasePtr();
26374     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
26375
26376     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
26377                                 St->getPointerInfo(), St->isVolatile(),
26378                                 St->isNonTemporal(), Alignment);
26379     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
26380                                 St->getPointerInfo(), St->isVolatile(),
26381                                 St->isNonTemporal(),
26382                                 std::min(16U, Alignment));
26383     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
26384   }
26385
26386   // Optimize trunc store (of multiple scalars) to shuffle and store.
26387   // First, pack all of the elements in one place. Next, store to memory
26388   // in fewer chunks.
26389   if (St->isTruncatingStore() && VT.isVector()) {
26390     // Check if we can detect an AVG pattern from the truncation. If yes,
26391     // replace the trunc store by a normal store with the result of X86ISD::AVG
26392     // instruction.
26393     SDValue Avg =
26394         detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG, Subtarget, dl);
26395     if (Avg.getNode())
26396       return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
26397                           St->getPointerInfo(), St->isVolatile(),
26398                           St->isNonTemporal(), St->getAlignment());
26399
26400     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26401     unsigned NumElems = VT.getVectorNumElements();
26402     assert(StVT != VT && "Cannot truncate to the same type");
26403     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26404     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26405
26406     // The truncating store is legal in some cases. For example
26407     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26408     // are designated for truncate store.
26409     // In this case we don't need any further transformations.
26410     if (TLI.isTruncStoreLegal(VT, StVT))
26411       return SDValue();
26412
26413     // From, To sizes and ElemCount must be pow of two
26414     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
26415     // We are going to use the original vector elt for storing.
26416     // Accumulated smaller vector elements must be a multiple of the store size.
26417     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
26418
26419     unsigned SizeRatio  = FromSz / ToSz;
26420
26421     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26422
26423     // Create a type on which we perform the shuffle
26424     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26425             StVT.getScalarType(), NumElems*SizeRatio);
26426
26427     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26428
26429     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
26430     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
26431     for (unsigned i = 0; i != NumElems; ++i)
26432       ShuffleVec[i] = i * SizeRatio;
26433
26434     // Can't shuffle using an illegal type.
26435     if (!TLI.isTypeLegal(WideVecVT))
26436       return SDValue();
26437
26438     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26439                                          DAG.getUNDEF(WideVecVT),
26440                                          &ShuffleVec[0]);
26441     // At this point all of the data is stored at the bottom of the
26442     // register. We now need to save it to mem.
26443
26444     // Find the largest store unit
26445     MVT StoreType = MVT::i8;
26446     for (MVT Tp : MVT::integer_valuetypes()) {
26447       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
26448         StoreType = Tp;
26449     }
26450
26451     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
26452     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
26453         (64 <= NumElems * ToSz))
26454       StoreType = MVT::f64;
26455
26456     // Bitcast the original vector into a vector of store-size units
26457     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
26458             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
26459     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
26460     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
26461     SmallVector<SDValue, 8> Chains;
26462     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
26463                                         TLI.getPointerTy(DAG.getDataLayout()));
26464     SDValue Ptr = St->getBasePtr();
26465
26466     // Perform one or more big stores into memory.
26467     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
26468       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
26469                                    StoreType, ShuffWide,
26470                                    DAG.getIntPtrConstant(i, dl));
26471       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
26472                                 St->getPointerInfo(), St->isVolatile(),
26473                                 St->isNonTemporal(), St->getAlignment());
26474       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26475       Chains.push_back(Ch);
26476     }
26477
26478     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
26479   }
26480
26481   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
26482   // the FP state in cases where an emms may be missing.
26483   // A preferable solution to the general problem is to figure out the right
26484   // places to insert EMMS.  This qualifies as a quick hack.
26485
26486   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
26487   if (VT.getSizeInBits() != 64)
26488     return SDValue();
26489
26490   const Function *F = DAG.getMachineFunction().getFunction();
26491   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
26492   bool F64IsLegal =
26493       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
26494   if ((VT.isVector() ||
26495        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
26496       isa<LoadSDNode>(St->getValue()) &&
26497       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
26498       St->getChain().hasOneUse() && !St->isVolatile()) {
26499     SDNode* LdVal = St->getValue().getNode();
26500     LoadSDNode *Ld = nullptr;
26501     int TokenFactorIndex = -1;
26502     SmallVector<SDValue, 8> Ops;
26503     SDNode* ChainVal = St->getChain().getNode();
26504     // Must be a store of a load.  We currently handle two cases:  the load
26505     // is a direct child, and it's under an intervening TokenFactor.  It is
26506     // possible to dig deeper under nested TokenFactors.
26507     if (ChainVal == LdVal)
26508       Ld = cast<LoadSDNode>(St->getChain());
26509     else if (St->getValue().hasOneUse() &&
26510              ChainVal->getOpcode() == ISD::TokenFactor) {
26511       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
26512         if (ChainVal->getOperand(i).getNode() == LdVal) {
26513           TokenFactorIndex = i;
26514           Ld = cast<LoadSDNode>(St->getValue());
26515         } else
26516           Ops.push_back(ChainVal->getOperand(i));
26517       }
26518     }
26519
26520     if (!Ld || !ISD::isNormalLoad(Ld))
26521       return SDValue();
26522
26523     // If this is not the MMX case, i.e. we are just turning i64 load/store
26524     // into f64 load/store, avoid the transformation if there are multiple
26525     // uses of the loaded value.
26526     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
26527       return SDValue();
26528
26529     SDLoc LdDL(Ld);
26530     SDLoc StDL(N);
26531     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
26532     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
26533     // pair instead.
26534     if (Subtarget->is64Bit() || F64IsLegal) {
26535       MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
26536       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
26537                                   Ld->getPointerInfo(), Ld->isVolatile(),
26538                                   Ld->isNonTemporal(), Ld->isInvariant(),
26539                                   Ld->getAlignment());
26540       SDValue NewChain = NewLd.getValue(1);
26541       if (TokenFactorIndex != -1) {
26542         Ops.push_back(NewChain);
26543         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26544       }
26545       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
26546                           St->getPointerInfo(),
26547                           St->isVolatile(), St->isNonTemporal(),
26548                           St->getAlignment());
26549     }
26550
26551     // Otherwise, lower to two pairs of 32-bit loads / stores.
26552     SDValue LoAddr = Ld->getBasePtr();
26553     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
26554                                  DAG.getConstant(4, LdDL, MVT::i32));
26555
26556     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
26557                                Ld->getPointerInfo(),
26558                                Ld->isVolatile(), Ld->isNonTemporal(),
26559                                Ld->isInvariant(), Ld->getAlignment());
26560     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
26561                                Ld->getPointerInfo().getWithOffset(4),
26562                                Ld->isVolatile(), Ld->isNonTemporal(),
26563                                Ld->isInvariant(),
26564                                MinAlign(Ld->getAlignment(), 4));
26565
26566     SDValue NewChain = LoLd.getValue(1);
26567     if (TokenFactorIndex != -1) {
26568       Ops.push_back(LoLd);
26569       Ops.push_back(HiLd);
26570       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26571     }
26572
26573     LoAddr = St->getBasePtr();
26574     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
26575                          DAG.getConstant(4, StDL, MVT::i32));
26576
26577     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
26578                                 St->getPointerInfo(),
26579                                 St->isVolatile(), St->isNonTemporal(),
26580                                 St->getAlignment());
26581     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
26582                                 St->getPointerInfo().getWithOffset(4),
26583                                 St->isVolatile(),
26584                                 St->isNonTemporal(),
26585                                 MinAlign(St->getAlignment(), 4));
26586     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
26587   }
26588
26589   // This is similar to the above case, but here we handle a scalar 64-bit
26590   // integer store that is extracted from a vector on a 32-bit target.
26591   // If we have SSE2, then we can treat it like a floating-point double
26592   // to get past legalization. The execution dependencies fixup pass will
26593   // choose the optimal machine instruction for the store if this really is
26594   // an integer or v2f32 rather than an f64.
26595   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
26596       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
26597     SDValue OldExtract = St->getOperand(1);
26598     SDValue ExtOp0 = OldExtract.getOperand(0);
26599     unsigned VecSize = ExtOp0.getValueSizeInBits();
26600     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
26601     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
26602     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
26603                                      BitCast, OldExtract.getOperand(1));
26604     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
26605                         St->getPointerInfo(), St->isVolatile(),
26606                         St->isNonTemporal(), St->getAlignment());
26607   }
26608
26609   return SDValue();
26610 }
26611
26612 /// Return 'true' if this vector operation is "horizontal"
26613 /// and return the operands for the horizontal operation in LHS and RHS.  A
26614 /// horizontal operation performs the binary operation on successive elements
26615 /// of its first operand, then on successive elements of its second operand,
26616 /// returning the resulting values in a vector.  For example, if
26617 ///   A = < float a0, float a1, float a2, float a3 >
26618 /// and
26619 ///   B = < float b0, float b1, float b2, float b3 >
26620 /// then the result of doing a horizontal operation on A and B is
26621 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
26622 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
26623 /// A horizontal-op B, for some already available A and B, and if so then LHS is
26624 /// set to A, RHS to B, and the routine returns 'true'.
26625 /// Note that the binary operation should have the property that if one of the
26626 /// operands is UNDEF then the result is UNDEF.
26627 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
26628   // Look for the following pattern: if
26629   //   A = < float a0, float a1, float a2, float a3 >
26630   //   B = < float b0, float b1, float b2, float b3 >
26631   // and
26632   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
26633   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
26634   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
26635   // which is A horizontal-op B.
26636
26637   // At least one of the operands should be a vector shuffle.
26638   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
26639       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
26640     return false;
26641
26642   MVT VT = LHS.getSimpleValueType();
26643
26644   assert((VT.is128BitVector() || VT.is256BitVector()) &&
26645          "Unsupported vector type for horizontal add/sub");
26646
26647   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
26648   // operate independently on 128-bit lanes.
26649   unsigned NumElts = VT.getVectorNumElements();
26650   unsigned NumLanes = VT.getSizeInBits()/128;
26651   unsigned NumLaneElts = NumElts / NumLanes;
26652   assert((NumLaneElts % 2 == 0) &&
26653          "Vector type should have an even number of elements in each lane");
26654   unsigned HalfLaneElts = NumLaneElts/2;
26655
26656   // View LHS in the form
26657   //   LHS = VECTOR_SHUFFLE A, B, LMask
26658   // If LHS is not a shuffle then pretend it is the shuffle
26659   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
26660   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
26661   // type VT.
26662   SDValue A, B;
26663   SmallVector<int, 16> LMask(NumElts);
26664   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26665     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
26666       A = LHS.getOperand(0);
26667     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
26668       B = LHS.getOperand(1);
26669     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
26670     std::copy(Mask.begin(), Mask.end(), LMask.begin());
26671   } else {
26672     if (LHS.getOpcode() != ISD::UNDEF)
26673       A = LHS;
26674     for (unsigned i = 0; i != NumElts; ++i)
26675       LMask[i] = i;
26676   }
26677
26678   // Likewise, view RHS in the form
26679   //   RHS = VECTOR_SHUFFLE C, D, RMask
26680   SDValue C, D;
26681   SmallVector<int, 16> RMask(NumElts);
26682   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26683     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
26684       C = RHS.getOperand(0);
26685     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
26686       D = RHS.getOperand(1);
26687     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
26688     std::copy(Mask.begin(), Mask.end(), RMask.begin());
26689   } else {
26690     if (RHS.getOpcode() != ISD::UNDEF)
26691       C = RHS;
26692     for (unsigned i = 0; i != NumElts; ++i)
26693       RMask[i] = i;
26694   }
26695
26696   // Check that the shuffles are both shuffling the same vectors.
26697   if (!(A == C && B == D) && !(A == D && B == C))
26698     return false;
26699
26700   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
26701   if (!A.getNode() && !B.getNode())
26702     return false;
26703
26704   // If A and B occur in reverse order in RHS, then "swap" them (which means
26705   // rewriting the mask).
26706   if (A != C)
26707     ShuffleVectorSDNode::commuteMask(RMask);
26708
26709   // At this point LHS and RHS are equivalent to
26710   //   LHS = VECTOR_SHUFFLE A, B, LMask
26711   //   RHS = VECTOR_SHUFFLE A, B, RMask
26712   // Check that the masks correspond to performing a horizontal operation.
26713   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
26714     for (unsigned i = 0; i != NumLaneElts; ++i) {
26715       int LIdx = LMask[i+l], RIdx = RMask[i+l];
26716
26717       // Ignore any UNDEF components.
26718       if (LIdx < 0 || RIdx < 0 ||
26719           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
26720           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
26721         continue;
26722
26723       // Check that successive elements are being operated on.  If not, this is
26724       // not a horizontal operation.
26725       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
26726       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
26727       if (!(LIdx == Index && RIdx == Index + 1) &&
26728           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
26729         return false;
26730     }
26731   }
26732
26733   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
26734   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
26735   return true;
26736 }
26737
26738 /// Do target-specific dag combines on floating point adds.
26739 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
26740                                   const X86Subtarget *Subtarget) {
26741   EVT VT = N->getValueType(0);
26742   SDValue LHS = N->getOperand(0);
26743   SDValue RHS = N->getOperand(1);
26744
26745   // Try to synthesize horizontal adds from adds of shuffles.
26746   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26747        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26748       isHorizontalBinOp(LHS, RHS, true))
26749     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
26750   return SDValue();
26751 }
26752
26753 /// Do target-specific dag combines on floating point subs.
26754 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
26755                                   const X86Subtarget *Subtarget) {
26756   EVT VT = N->getValueType(0);
26757   SDValue LHS = N->getOperand(0);
26758   SDValue RHS = N->getOperand(1);
26759
26760   // Try to synthesize horizontal subs from subs of shuffles.
26761   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26762        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26763       isHorizontalBinOp(LHS, RHS, false))
26764     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
26765   return SDValue();
26766 }
26767
26768 /// Truncate a group of v4i32 into v16i8/v8i16 using X86ISD::PACKUS.
26769 static SDValue
26770 combineVectorTruncationWithPACKUS(SDNode *N, SelectionDAG &DAG,
26771                                   SmallVector<SDValue, 8> &Regs) {
26772   assert(Regs.size() > 0 && (Regs[0].getValueType() == MVT::v4i32 ||
26773                              Regs[0].getValueType() == MVT::v2i64));
26774   EVT OutVT = N->getValueType(0);
26775   EVT OutSVT = OutVT.getVectorElementType();
26776   EVT InVT = Regs[0].getValueType();
26777   EVT InSVT = InVT.getVectorElementType();
26778   SDLoc DL(N);
26779
26780   // First, use mask to unset all bits that won't appear in the result.
26781   assert((OutSVT == MVT::i8 || OutSVT == MVT::i16) &&
26782          "OutSVT can only be either i8 or i16.");
26783   SDValue MaskVal =
26784       DAG.getConstant(OutSVT == MVT::i8 ? 0xFF : 0xFFFF, DL, InSVT);
26785   SDValue MaskVec = DAG.getNode(
26786       ISD::BUILD_VECTOR, DL, InVT,
26787       SmallVector<SDValue, 8>(InVT.getVectorNumElements(), MaskVal));
26788   for (auto &Reg : Regs)
26789     Reg = DAG.getNode(ISD::AND, DL, InVT, MaskVec, Reg);
26790
26791   MVT UnpackedVT, PackedVT;
26792   if (OutSVT == MVT::i8) {
26793     UnpackedVT = MVT::v8i16;
26794     PackedVT = MVT::v16i8;
26795   } else {
26796     UnpackedVT = MVT::v4i32;
26797     PackedVT = MVT::v8i16;
26798   }
26799
26800   // In each iteration, truncate the type by a half size.
26801   auto RegNum = Regs.size();
26802   for (unsigned j = 1, e = InSVT.getSizeInBits() / OutSVT.getSizeInBits();
26803        j < e; j *= 2, RegNum /= 2) {
26804     for (unsigned i = 0; i < RegNum; i++)
26805       Regs[i] = DAG.getNode(ISD::BITCAST, DL, UnpackedVT, Regs[i]);
26806     for (unsigned i = 0; i < RegNum / 2; i++)
26807       Regs[i] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[i * 2],
26808                             Regs[i * 2 + 1]);
26809   }
26810
26811   // If the type of the result is v8i8, we need do one more X86ISD::PACKUS, and
26812   // then extract a subvector as the result since v8i8 is not a legal type.
26813   if (OutVT == MVT::v8i8) {
26814     Regs[0] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[0], Regs[0]);
26815     Regs[0] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, Regs[0],
26816                           DAG.getIntPtrConstant(0, DL));
26817     return Regs[0];
26818   } else if (RegNum > 1) {
26819     Regs.resize(RegNum);
26820     return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26821   } else
26822     return Regs[0];
26823 }
26824
26825 /// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
26826 static SDValue
26827 combineVectorTruncationWithPACKSS(SDNode *N, SelectionDAG &DAG,
26828                                   SmallVector<SDValue, 8> &Regs) {
26829   assert(Regs.size() > 0 && Regs[0].getValueType() == MVT::v4i32);
26830   EVT OutVT = N->getValueType(0);
26831   SDLoc DL(N);
26832
26833   // Shift left by 16 bits, then arithmetic-shift right by 16 bits.
26834   SDValue ShAmt = DAG.getConstant(16, DL, MVT::i32);
26835   for (auto &Reg : Regs) {
26836     Reg = getTargetVShiftNode(X86ISD::VSHLI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26837     Reg = getTargetVShiftNode(X86ISD::VSRAI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26838   }
26839
26840   for (unsigned i = 0, e = Regs.size() / 2; i < e; i++)
26841     Regs[i] = DAG.getNode(X86ISD::PACKSS, DL, MVT::v8i16, Regs[i * 2],
26842                           Regs[i * 2 + 1]);
26843
26844   if (Regs.size() > 2) {
26845     Regs.resize(Regs.size() / 2);
26846     return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26847   } else
26848     return Regs[0];
26849 }
26850
26851 /// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
26852 /// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
26853 /// legalization the truncation will be translated into a BUILD_VECTOR with each
26854 /// element that is extracted from a vector and then truncated, and it is
26855 /// diffcult to do this optimization based on them.
26856 static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
26857                                        const X86Subtarget *Subtarget) {
26858   EVT OutVT = N->getValueType(0);
26859   if (!OutVT.isVector())
26860     return SDValue();
26861
26862   SDValue In = N->getOperand(0);
26863   if (!In.getValueType().isSimple())
26864     return SDValue();
26865
26866   EVT InVT = In.getValueType();
26867   unsigned NumElems = OutVT.getVectorNumElements();
26868
26869   // TODO: On AVX2, the behavior of X86ISD::PACKUS is different from that on
26870   // SSE2, and we need to take care of it specially.
26871   // AVX512 provides vpmovdb.
26872   if (!Subtarget->hasSSE2() || Subtarget->hasAVX2())
26873     return SDValue();
26874
26875   EVT OutSVT = OutVT.getVectorElementType();
26876   EVT InSVT = InVT.getVectorElementType();
26877   if (!((InSVT == MVT::i32 || InSVT == MVT::i64) &&
26878         (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
26879         NumElems >= 8))
26880     return SDValue();
26881
26882   // SSSE3's pshufb results in less instructions in the cases below.
26883   if (Subtarget->hasSSSE3() && NumElems == 8 &&
26884       ((OutSVT == MVT::i8 && InSVT != MVT::i64) ||
26885        (InSVT == MVT::i32 && OutSVT == MVT::i16)))
26886     return SDValue();
26887
26888   SDLoc DL(N);
26889
26890   // Split a long vector into vectors of legal type.
26891   unsigned RegNum = InVT.getSizeInBits() / 128;
26892   SmallVector<SDValue, 8> SubVec(RegNum);
26893   if (InSVT == MVT::i32) {
26894     for (unsigned i = 0; i < RegNum; i++)
26895       SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
26896                               DAG.getIntPtrConstant(i * 4, DL));
26897   } else {
26898     for (unsigned i = 0; i < RegNum; i++)
26899       SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
26900                               DAG.getIntPtrConstant(i * 2, DL));
26901   }
26902
26903   // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PAKCUS
26904   // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
26905   // truncate 2 x v4i32 to v8i16.
26906   if (Subtarget->hasSSE41() || OutSVT == MVT::i8)
26907     return combineVectorTruncationWithPACKUS(N, DAG, SubVec);
26908   else if (InSVT == MVT::i32)
26909     return combineVectorTruncationWithPACKSS(N, DAG, SubVec);
26910   else
26911     return SDValue();
26912 }
26913
26914 static SDValue PerformTRUNCATECombine(SDNode *N, SelectionDAG &DAG,
26915                                       const X86Subtarget *Subtarget) {
26916   // Try to detect AVG pattern first.
26917   SDValue Avg = detectAVGPattern(N->getOperand(0), N->getValueType(0), DAG,
26918                                  Subtarget, SDLoc(N));
26919   if (Avg.getNode())
26920     return Avg;
26921
26922   return combineVectorTruncation(N, DAG, Subtarget);
26923 }
26924
26925 /// Do target-specific dag combines on floating point negations.
26926 static SDValue PerformFNEGCombine(SDNode *N, SelectionDAG &DAG,
26927                                   const X86Subtarget *Subtarget) {
26928   EVT VT = N->getValueType(0);
26929   EVT SVT = VT.getScalarType();
26930   SDValue Arg = N->getOperand(0);
26931   SDLoc DL(N);
26932
26933   // Let legalize expand this if it isn't a legal type yet.
26934   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
26935     return SDValue();
26936
26937   // If we're negating a FMUL node on a target with FMA, then we can avoid the
26938   // use of a constant by performing (-0 - A*B) instead.
26939   // FIXME: Check rounding control flags as well once it becomes available.
26940   if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
26941       Arg->getFlags()->hasNoSignedZeros() && Subtarget->hasAnyFMA()) {
26942     SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
26943     return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
26944                        Arg.getOperand(1), Zero);
26945   }
26946
26947   // If we're negating a FMA node, then we can adjust the
26948   // instruction to include the extra negation.
26949   if (Arg.hasOneUse()) {
26950     switch (Arg.getOpcode()) {
26951     case X86ISD::FMADD:
26952       return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
26953                          Arg.getOperand(1), Arg.getOperand(2));
26954     case X86ISD::FMSUB:
26955       return DAG.getNode(X86ISD::FNMADD, DL, VT, Arg.getOperand(0),
26956                          Arg.getOperand(1), Arg.getOperand(2));
26957     case X86ISD::FNMADD:
26958       return DAG.getNode(X86ISD::FMSUB, DL, VT, Arg.getOperand(0),
26959                          Arg.getOperand(1), Arg.getOperand(2));
26960     case X86ISD::FNMSUB:
26961       return DAG.getNode(X86ISD::FMADD, DL, VT, Arg.getOperand(0),
26962                          Arg.getOperand(1), Arg.getOperand(2));
26963     }
26964   }
26965   return SDValue();
26966 }
26967
26968 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
26969                               const X86Subtarget *Subtarget) {
26970   EVT VT = N->getValueType(0);
26971   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
26972     // VXORPS, VORPS, VANDPS, VANDNPS are supported only under DQ extention.
26973     // These logic operations may be executed in the integer domain.
26974     SDLoc dl(N);
26975     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
26976     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
26977
26978     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
26979     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
26980     unsigned IntOpcode = 0;
26981     switch (N->getOpcode()) {
26982       default: llvm_unreachable("Unexpected FP logic op");
26983       case X86ISD::FOR: IntOpcode = ISD::OR; break;
26984       case X86ISD::FXOR: IntOpcode = ISD::XOR; break;
26985       case X86ISD::FAND: IntOpcode = ISD::AND; break;
26986       case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
26987     }
26988     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
26989     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
26990   }
26991   return SDValue();
26992 }
26993 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
26994 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
26995                                  const X86Subtarget *Subtarget) {
26996   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
26997
26998   // F[X]OR(0.0, x) -> x
26999   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27000     if (C->getValueAPF().isPosZero())
27001       return N->getOperand(1);
27002
27003   // F[X]OR(x, 0.0) -> x
27004   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27005     if (C->getValueAPF().isPosZero())
27006       return N->getOperand(0);
27007
27008   return lowerX86FPLogicOp(N, DAG, Subtarget);
27009 }
27010
27011 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
27012 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
27013   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
27014
27015   // Only perform optimizations if UnsafeMath is used.
27016   if (!DAG.getTarget().Options.UnsafeFPMath)
27017     return SDValue();
27018
27019   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
27020   // into FMINC and FMAXC, which are Commutative operations.
27021   unsigned NewOp = 0;
27022   switch (N->getOpcode()) {
27023     default: llvm_unreachable("unknown opcode");
27024     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
27025     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
27026   }
27027
27028   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
27029                      N->getOperand(0), N->getOperand(1));
27030 }
27031
27032 static SDValue performFMinNumFMaxNumCombine(SDNode *N, SelectionDAG &DAG,
27033                                             const X86Subtarget *Subtarget) {
27034   if (Subtarget->useSoftFloat())
27035     return SDValue();
27036
27037   // TODO: Check for global or instruction-level "nnan". In that case, we
27038   //       should be able to lower to FMAX/FMIN alone.
27039   // TODO: If an operand is already known to be a NaN or not a NaN, this
27040   //       should be an optional swap and FMAX/FMIN.
27041
27042   EVT VT = N->getValueType(0);
27043   if (!((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
27044         (Subtarget->hasSSE2() && (VT == MVT::f64 || VT == MVT::v2f64)) ||
27045         (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))))
27046     return SDValue();
27047
27048   // This takes at least 3 instructions, so favor a library call when operating
27049   // on a scalar and minimizing code size.
27050   if (!VT.isVector() && DAG.getMachineFunction().getFunction()->optForMinSize())
27051     return SDValue();
27052
27053   SDValue Op0 = N->getOperand(0);
27054   SDValue Op1 = N->getOperand(1);
27055   SDLoc DL(N);
27056   EVT SetCCType = DAG.getTargetLoweringInfo().getSetCCResultType(
27057       DAG.getDataLayout(), *DAG.getContext(), VT);
27058
27059   // There are 4 possibilities involving NaN inputs, and these are the required
27060   // outputs:
27061   //                   Op1
27062   //               Num     NaN
27063   //            ----------------
27064   //       Num  |  Max  |  Op0 |
27065   // Op0        ----------------
27066   //       NaN  |  Op1  |  NaN |
27067   //            ----------------
27068   //
27069   // The SSE FP max/min instructions were not designed for this case, but rather
27070   // to implement:
27071   //   Min = Op1 < Op0 ? Op1 : Op0
27072   //   Max = Op1 > Op0 ? Op1 : Op0
27073   //
27074   // So they always return Op0 if either input is a NaN. However, we can still
27075   // use those instructions for fmaxnum by selecting away a NaN input.
27076
27077   // If either operand is NaN, the 2nd source operand (Op0) is passed through.
27078   auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
27079   SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
27080   SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType , Op0, Op0, ISD::SETUO);
27081
27082   // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
27083   // are NaN, the NaN value of Op1 is the result.
27084   auto SelectOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT;
27085   return DAG.getNode(SelectOpcode, DL, VT, IsOp0Nan, Op1, MinOrMax);
27086 }
27087
27088 /// Do target-specific dag combines on X86ISD::FAND nodes.
27089 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG,
27090                                   const X86Subtarget *Subtarget) {
27091   // FAND(0.0, x) -> 0.0
27092   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27093     if (C->getValueAPF().isPosZero())
27094       return N->getOperand(0);
27095
27096   // FAND(x, 0.0) -> 0.0
27097   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27098     if (C->getValueAPF().isPosZero())
27099       return N->getOperand(1);
27100
27101   return lowerX86FPLogicOp(N, DAG, Subtarget);
27102 }
27103
27104 /// Do target-specific dag combines on X86ISD::FANDN nodes
27105 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG,
27106                                    const X86Subtarget *Subtarget) {
27107   // FANDN(0.0, x) -> x
27108   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27109     if (C->getValueAPF().isPosZero())
27110       return N->getOperand(1);
27111
27112   // FANDN(x, 0.0) -> 0.0
27113   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27114     if (C->getValueAPF().isPosZero())
27115       return N->getOperand(1);
27116
27117   return lowerX86FPLogicOp(N, DAG, Subtarget);
27118 }
27119
27120 static SDValue PerformBTCombine(SDNode *N,
27121                                 SelectionDAG &DAG,
27122                                 TargetLowering::DAGCombinerInfo &DCI) {
27123   // BT ignores high bits in the bit index operand.
27124   SDValue Op1 = N->getOperand(1);
27125   if (Op1.hasOneUse()) {
27126     unsigned BitWidth = Op1.getValueSizeInBits();
27127     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
27128     APInt KnownZero, KnownOne;
27129     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
27130                                           !DCI.isBeforeLegalizeOps());
27131     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27132     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
27133         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
27134       DCI.CommitTargetLoweringOpt(TLO);
27135   }
27136   return SDValue();
27137 }
27138
27139 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
27140   SDValue Op = N->getOperand(0);
27141   if (Op.getOpcode() == ISD::BITCAST)
27142     Op = Op.getOperand(0);
27143   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
27144   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
27145       VT.getVectorElementType().getSizeInBits() ==
27146       OpVT.getVectorElementType().getSizeInBits()) {
27147     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
27148   }
27149   return SDValue();
27150 }
27151
27152 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
27153                                                const X86Subtarget *Subtarget) {
27154   EVT VT = N->getValueType(0);
27155   if (!VT.isVector())
27156     return SDValue();
27157
27158   SDValue N0 = N->getOperand(0);
27159   SDValue N1 = N->getOperand(1);
27160   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
27161   SDLoc dl(N);
27162
27163   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
27164   // both SSE and AVX2 since there is no sign-extended shift right
27165   // operation on a vector with 64-bit elements.
27166   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
27167   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
27168   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
27169       N0.getOpcode() == ISD::SIGN_EXTEND)) {
27170     SDValue N00 = N0.getOperand(0);
27171
27172     // EXTLOAD has a better solution on AVX2,
27173     // it may be replaced with X86ISD::VSEXT node.
27174     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
27175       if (!ISD::isNormalLoad(N00.getNode()))
27176         return SDValue();
27177
27178     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
27179         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
27180                                   N00, N1);
27181       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
27182     }
27183   }
27184   return SDValue();
27185 }
27186
27187 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
27188 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
27189 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
27190 /// eliminate extend, add, and shift instructions.
27191 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
27192                                        const X86Subtarget *Subtarget) {
27193   // TODO: This should be valid for other integer types.
27194   EVT VT = Sext->getValueType(0);
27195   if (VT != MVT::i64)
27196     return SDValue();
27197
27198   // We need an 'add nsw' feeding into the 'sext'.
27199   SDValue Add = Sext->getOperand(0);
27200   if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
27201     return SDValue();
27202
27203   // Having a constant operand to the 'add' ensures that we are not increasing
27204   // the instruction count because the constant is extended for free below.
27205   // A constant operand can also become the displacement field of an LEA.
27206   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
27207   if (!AddOp1)
27208     return SDValue();
27209
27210   // Don't make the 'add' bigger if there's no hope of combining it with some
27211   // other 'add' or 'shl' instruction.
27212   // TODO: It may be profitable to generate simpler LEA instructions in place
27213   // of single 'add' instructions, but the cost model for selecting an LEA
27214   // currently has a high threshold.
27215   bool HasLEAPotential = false;
27216   for (auto *User : Sext->uses()) {
27217     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
27218       HasLEAPotential = true;
27219       break;
27220     }
27221   }
27222   if (!HasLEAPotential)
27223     return SDValue();
27224
27225   // Everything looks good, so pull the 'sext' ahead of the 'add'.
27226   int64_t AddConstant = AddOp1->getSExtValue();
27227   SDValue AddOp0 = Add.getOperand(0);
27228   SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
27229   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
27230
27231   // The wider add is guaranteed to not wrap because both operands are
27232   // sign-extended.
27233   SDNodeFlags Flags;
27234   Flags.setNoSignedWrap(true);
27235   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
27236 }
27237
27238 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
27239                                   TargetLowering::DAGCombinerInfo &DCI,
27240                                   const X86Subtarget *Subtarget) {
27241   SDValue N0 = N->getOperand(0);
27242   EVT VT = N->getValueType(0);
27243   EVT SVT = VT.getScalarType();
27244   EVT InVT = N0.getValueType();
27245   EVT InSVT = InVT.getScalarType();
27246   SDLoc DL(N);
27247
27248   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
27249   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
27250   // This exposes the sext to the sdivrem lowering, so that it directly extends
27251   // from AH (which we otherwise need to do contortions to access).
27252   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
27253       InVT == MVT::i8 && VT == MVT::i32) {
27254     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
27255     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
27256                             N0.getOperand(0), N0.getOperand(1));
27257     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
27258     return R.getValue(1);
27259   }
27260
27261   if (!DCI.isBeforeLegalizeOps()) {
27262     if (InVT == MVT::i1) {
27263       SDValue Zero = DAG.getConstant(0, DL, VT);
27264       SDValue AllOnes =
27265         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
27266       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
27267     }
27268     return SDValue();
27269   }
27270
27271   if (VT.isVector() && Subtarget->hasSSE2()) {
27272     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
27273       EVT InVT = N.getValueType();
27274       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
27275                                    Size / InVT.getScalarSizeInBits());
27276       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
27277                                     DAG.getUNDEF(InVT));
27278       Opnds[0] = N;
27279       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
27280     };
27281
27282     // If target-size is less than 128-bits, extend to a type that would extend
27283     // to 128 bits, extend that and extract the original target vector.
27284     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
27285         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27286         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27287       unsigned Scale = 128 / VT.getSizeInBits();
27288       EVT ExVT =
27289           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
27290       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
27291       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
27292       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
27293                          DAG.getIntPtrConstant(0, DL));
27294     }
27295
27296     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
27297     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
27298     if (VT.getSizeInBits() == 128 &&
27299         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27300         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27301       SDValue ExOp = ExtendVecSize(DL, N0, 128);
27302       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
27303     }
27304
27305     // On pre-AVX2 targets, split into 128-bit nodes of
27306     // ISD::SIGN_EXTEND_VECTOR_INREG.
27307     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
27308         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27309         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27310       unsigned NumVecs = VT.getSizeInBits() / 128;
27311       unsigned NumSubElts = 128 / SVT.getSizeInBits();
27312       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
27313       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
27314
27315       SmallVector<SDValue, 8> Opnds;
27316       for (unsigned i = 0, Offset = 0; i != NumVecs;
27317            ++i, Offset += NumSubElts) {
27318         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
27319                                      DAG.getIntPtrConstant(Offset, DL));
27320         SrcVec = ExtendVecSize(DL, SrcVec, 128);
27321         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
27322         Opnds.push_back(SrcVec);
27323       }
27324       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
27325     }
27326   }
27327
27328   if (Subtarget->hasAVX() && VT.is256BitVector())
27329     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27330       return R;
27331
27332   if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
27333     return NewAdd;
27334
27335   return SDValue();
27336 }
27337
27338 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
27339                                  const X86Subtarget* Subtarget) {
27340   SDLoc dl(N);
27341   EVT VT = N->getValueType(0);
27342
27343   // Let legalize expand this if it isn't a legal type yet.
27344   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
27345     return SDValue();
27346
27347   EVT ScalarVT = VT.getScalarType();
27348   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget->hasAnyFMA())
27349     return SDValue();
27350
27351   SDValue A = N->getOperand(0);
27352   SDValue B = N->getOperand(1);
27353   SDValue C = N->getOperand(2);
27354
27355   bool NegA = (A.getOpcode() == ISD::FNEG);
27356   bool NegB = (B.getOpcode() == ISD::FNEG);
27357   bool NegC = (C.getOpcode() == ISD::FNEG);
27358
27359   // Negative multiplication when NegA xor NegB
27360   bool NegMul = (NegA != NegB);
27361   if (NegA)
27362     A = A.getOperand(0);
27363   if (NegB)
27364     B = B.getOperand(0);
27365   if (NegC)
27366     C = C.getOperand(0);
27367
27368   unsigned Opcode;
27369   if (!NegMul)
27370     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
27371   else
27372     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
27373
27374   return DAG.getNode(Opcode, dl, VT, A, B, C);
27375 }
27376
27377 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
27378                                   TargetLowering::DAGCombinerInfo &DCI,
27379                                   const X86Subtarget *Subtarget) {
27380   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
27381   //           (and (i32 x86isd::setcc_carry), 1)
27382   // This eliminates the zext. This transformation is necessary because
27383   // ISD::SETCC is always legalized to i8.
27384   SDLoc dl(N);
27385   SDValue N0 = N->getOperand(0);
27386   EVT VT = N->getValueType(0);
27387
27388   if (N0.getOpcode() == ISD::AND &&
27389       N0.hasOneUse() &&
27390       N0.getOperand(0).hasOneUse()) {
27391     SDValue N00 = N0.getOperand(0);
27392     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27393       if (!isOneConstant(N0.getOperand(1)))
27394         return SDValue();
27395       return DAG.getNode(ISD::AND, dl, VT,
27396                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27397                                      N00.getOperand(0), N00.getOperand(1)),
27398                          DAG.getConstant(1, dl, VT));
27399     }
27400   }
27401
27402   if (N0.getOpcode() == ISD::TRUNCATE &&
27403       N0.hasOneUse() &&
27404       N0.getOperand(0).hasOneUse()) {
27405     SDValue N00 = N0.getOperand(0);
27406     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27407       return DAG.getNode(ISD::AND, dl, VT,
27408                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27409                                      N00.getOperand(0), N00.getOperand(1)),
27410                          DAG.getConstant(1, dl, VT));
27411     }
27412   }
27413
27414   if (VT.is256BitVector())
27415     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27416       return R;
27417
27418   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
27419   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
27420   // This exposes the zext to the udivrem lowering, so that it directly extends
27421   // from AH (which we otherwise need to do contortions to access).
27422   if (N0.getOpcode() == ISD::UDIVREM &&
27423       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
27424       (VT == MVT::i32 || VT == MVT::i64)) {
27425     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
27426     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
27427                             N0.getOperand(0), N0.getOperand(1));
27428     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
27429     return R.getValue(1);
27430   }
27431
27432   return SDValue();
27433 }
27434
27435 // Optimize x == -y --> x+y == 0
27436 //          x != -y --> x+y != 0
27437 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
27438                                       const X86Subtarget* Subtarget) {
27439   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
27440   SDValue LHS = N->getOperand(0);
27441   SDValue RHS = N->getOperand(1);
27442   EVT VT = N->getValueType(0);
27443   SDLoc DL(N);
27444
27445   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
27446     if (isNullConstant(LHS.getOperand(0)) && LHS.hasOneUse()) {
27447       SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
27448                                  LHS.getOperand(1));
27449       return DAG.getSetCC(DL, N->getValueType(0), addV,
27450                           DAG.getConstant(0, DL, addV.getValueType()), CC);
27451     }
27452   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
27453     if (isNullConstant(RHS.getOperand(0)) && RHS.hasOneUse()) {
27454       SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
27455                                  RHS.getOperand(1));
27456       return DAG.getSetCC(DL, N->getValueType(0), addV,
27457                           DAG.getConstant(0, DL, addV.getValueType()), CC);
27458     }
27459
27460   if (VT.getScalarType() == MVT::i1 &&
27461       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
27462     bool IsSEXT0 =
27463         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27464         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27465     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27466
27467     if (!IsSEXT0 || !IsVZero1) {
27468       // Swap the operands and update the condition code.
27469       std::swap(LHS, RHS);
27470       CC = ISD::getSetCCSwappedOperands(CC);
27471
27472       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27473                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27474       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27475     }
27476
27477     if (IsSEXT0 && IsVZero1) {
27478       assert(VT == LHS.getOperand(0).getValueType() &&
27479              "Uexpected operand type");
27480       if (CC == ISD::SETGT)
27481         return DAG.getConstant(0, DL, VT);
27482       if (CC == ISD::SETLE)
27483         return DAG.getConstant(1, DL, VT);
27484       if (CC == ISD::SETEQ || CC == ISD::SETGE)
27485         return DAG.getNOT(DL, LHS.getOperand(0), VT);
27486
27487       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
27488              "Unexpected condition code!");
27489       return LHS.getOperand(0);
27490     }
27491   }
27492
27493   return SDValue();
27494 }
27495
27496 static SDValue PerformGatherScatterCombine(SDNode *N, SelectionDAG &DAG) {
27497   SDLoc DL(N);
27498   // Gather and Scatter instructions use k-registers for masks. The type of
27499   // the masks is v*i1. So the mask will be truncated anyway.
27500   // The SIGN_EXTEND_INREG my be dropped.
27501   SDValue Mask = N->getOperand(2);
27502   if (Mask.getOpcode() == ISD::SIGN_EXTEND_INREG) {
27503     SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
27504     NewOps[2] = Mask.getOperand(0);
27505     DAG.UpdateNodeOperands(N, NewOps);
27506   }
27507   return SDValue();
27508 }
27509
27510 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
27511 // as "sbb reg,reg", since it can be extended without zext and produces
27512 // an all-ones bit which is more useful than 0/1 in some cases.
27513 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
27514                                MVT VT) {
27515   if (VT == MVT::i8)
27516     return DAG.getNode(ISD::AND, DL, VT,
27517                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27518                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
27519                                    EFLAGS),
27520                        DAG.getConstant(1, DL, VT));
27521   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
27522   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
27523                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27524                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
27525                                  EFLAGS));
27526 }
27527
27528 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
27529 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
27530                                    TargetLowering::DAGCombinerInfo &DCI,
27531                                    const X86Subtarget *Subtarget) {
27532   SDLoc DL(N);
27533   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
27534   SDValue EFLAGS = N->getOperand(1);
27535
27536   if (CC == X86::COND_A) {
27537     // Try to convert COND_A into COND_B in an attempt to facilitate
27538     // materializing "setb reg".
27539     //
27540     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
27541     // cannot take an immediate as its first operand.
27542     //
27543     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
27544         EFLAGS.getValueType().isInteger() &&
27545         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
27546       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
27547                                    EFLAGS.getNode()->getVTList(),
27548                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
27549       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
27550       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
27551     }
27552   }
27553
27554   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
27555   // a zext and produces an all-ones bit which is more useful than 0/1 in some
27556   // cases.
27557   if (CC == X86::COND_B)
27558     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
27559
27560   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27561     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27562     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
27563   }
27564
27565   return SDValue();
27566 }
27567
27568 // Optimize branch condition evaluation.
27569 //
27570 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
27571                                     TargetLowering::DAGCombinerInfo &DCI,
27572                                     const X86Subtarget *Subtarget) {
27573   SDLoc DL(N);
27574   SDValue Chain = N->getOperand(0);
27575   SDValue Dest = N->getOperand(1);
27576   SDValue EFLAGS = N->getOperand(3);
27577   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
27578
27579   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27580     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27581     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
27582                        Flags);
27583   }
27584
27585   return SDValue();
27586 }
27587
27588 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
27589                                                          SelectionDAG &DAG) {
27590   // Take advantage of vector comparisons producing 0 or -1 in each lane to
27591   // optimize away operation when it's from a constant.
27592   //
27593   // The general transformation is:
27594   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
27595   //       AND(VECTOR_CMP(x,y), constant2)
27596   //    constant2 = UNARYOP(constant)
27597
27598   // Early exit if this isn't a vector operation, the operand of the
27599   // unary operation isn't a bitwise AND, or if the sizes of the operations
27600   // aren't the same.
27601   EVT VT = N->getValueType(0);
27602   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
27603       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
27604       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
27605     return SDValue();
27606
27607   // Now check that the other operand of the AND is a constant. We could
27608   // make the transformation for non-constant splats as well, but it's unclear
27609   // that would be a benefit as it would not eliminate any operations, just
27610   // perform one more step in scalar code before moving to the vector unit.
27611   if (BuildVectorSDNode *BV =
27612           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
27613     // Bail out if the vector isn't a constant.
27614     if (!BV->isConstant())
27615       return SDValue();
27616
27617     // Everything checks out. Build up the new and improved node.
27618     SDLoc DL(N);
27619     EVT IntVT = BV->getValueType(0);
27620     // Create a new constant of the appropriate type for the transformed
27621     // DAG.
27622     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
27623     // The AND node needs bitcasts to/from an integer vector type around it.
27624     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
27625     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
27626                                  N->getOperand(0)->getOperand(0), MaskConst);
27627     SDValue Res = DAG.getBitcast(VT, NewAnd);
27628     return Res;
27629   }
27630
27631   return SDValue();
27632 }
27633
27634 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27635                                         const X86Subtarget *Subtarget) {
27636   SDValue Op0 = N->getOperand(0);
27637   EVT VT = N->getValueType(0);
27638   EVT InVT = Op0.getValueType();
27639   EVT InSVT = InVT.getScalarType();
27640   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27641
27642   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
27643   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
27644   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27645     SDLoc dl(N);
27646     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27647                                  InVT.getVectorNumElements());
27648     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
27649
27650     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
27651       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
27652
27653     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27654   }
27655
27656   return SDValue();
27657 }
27658
27659 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27660                                         const X86Subtarget *Subtarget) {
27661   // First try to optimize away the conversion entirely when it's
27662   // conditionally from a constant. Vectors only.
27663   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
27664     return Res;
27665
27666   // Now move on to more general possibilities.
27667   SDValue Op0 = N->getOperand(0);
27668   EVT VT = N->getValueType(0);
27669   EVT InVT = Op0.getValueType();
27670   EVT InSVT = InVT.getScalarType();
27671
27672   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
27673   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
27674   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27675     SDLoc dl(N);
27676     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27677                                  InVT.getVectorNumElements());
27678     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
27679     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27680   }
27681
27682   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
27683   // a 32-bit target where SSE doesn't support i64->FP operations.
27684   if (!Subtarget->useSoftFloat() && Op0.getOpcode() == ISD::LOAD) {
27685     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
27686     EVT LdVT = Ld->getValueType(0);
27687
27688     // This transformation is not supported if the result type is f16
27689     if (VT == MVT::f16)
27690       return SDValue();
27691
27692     if (!Ld->isVolatile() && !VT.isVector() &&
27693         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
27694         !Subtarget->is64Bit() && LdVT == MVT::i64) {
27695       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
27696           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
27697       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
27698       return FILDChain;
27699     }
27700   }
27701   return SDValue();
27702 }
27703
27704 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
27705 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
27706                                  X86TargetLowering::DAGCombinerInfo &DCI) {
27707   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
27708   // the result is either zero or one (depending on the input carry bit).
27709   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
27710   if (X86::isZeroNode(N->getOperand(0)) &&
27711       X86::isZeroNode(N->getOperand(1)) &&
27712       // We don't have a good way to replace an EFLAGS use, so only do this when
27713       // dead right now.
27714       SDValue(N, 1).use_empty()) {
27715     SDLoc DL(N);
27716     EVT VT = N->getValueType(0);
27717     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
27718     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
27719                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
27720                                            DAG.getConstant(X86::COND_B, DL,
27721                                                            MVT::i8),
27722                                            N->getOperand(2)),
27723                                DAG.getConstant(1, DL, VT));
27724     return DCI.CombineTo(N, Res1, CarryOut);
27725   }
27726
27727   return SDValue();
27728 }
27729
27730 // fold (add Y, (sete  X, 0)) -> adc  0, Y
27731 //      (add Y, (setne X, 0)) -> sbb -1, Y
27732 //      (sub (sete  X, 0), Y) -> sbb  0, Y
27733 //      (sub (setne X, 0), Y) -> adc -1, Y
27734 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
27735   SDLoc DL(N);
27736
27737   // Look through ZExts.
27738   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
27739   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
27740     return SDValue();
27741
27742   SDValue SetCC = Ext.getOperand(0);
27743   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
27744     return SDValue();
27745
27746   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
27747   if (CC != X86::COND_E && CC != X86::COND_NE)
27748     return SDValue();
27749
27750   SDValue Cmp = SetCC.getOperand(1);
27751   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
27752       !X86::isZeroNode(Cmp.getOperand(1)) ||
27753       !Cmp.getOperand(0).getValueType().isInteger())
27754     return SDValue();
27755
27756   SDValue CmpOp0 = Cmp.getOperand(0);
27757   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
27758                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
27759
27760   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
27761   if (CC == X86::COND_NE)
27762     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
27763                        DL, OtherVal.getValueType(), OtherVal,
27764                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
27765                        NewCmp);
27766   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
27767                      DL, OtherVal.getValueType(), OtherVal,
27768                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
27769 }
27770
27771 /// PerformADDCombine - Do target-specific dag combines on integer adds.
27772 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
27773                                  const X86Subtarget *Subtarget) {
27774   EVT VT = N->getValueType(0);
27775   SDValue Op0 = N->getOperand(0);
27776   SDValue Op1 = N->getOperand(1);
27777
27778   // Try to synthesize horizontal adds from adds of shuffles.
27779   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27780        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27781       isHorizontalBinOp(Op0, Op1, true))
27782     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
27783
27784   return OptimizeConditionalInDecrement(N, DAG);
27785 }
27786
27787 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
27788                                  const X86Subtarget *Subtarget) {
27789   SDValue Op0 = N->getOperand(0);
27790   SDValue Op1 = N->getOperand(1);
27791
27792   // X86 can't encode an immediate LHS of a sub. See if we can push the
27793   // negation into a preceding instruction.
27794   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
27795     // If the RHS of the sub is a XOR with one use and a constant, invert the
27796     // immediate. Then add one to the LHS of the sub so we can turn
27797     // X-Y -> X+~Y+1, saving one register.
27798     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
27799         isa<ConstantSDNode>(Op1.getOperand(1))) {
27800       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
27801       EVT VT = Op0.getValueType();
27802       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
27803                                    Op1.getOperand(0),
27804                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
27805       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
27806                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
27807     }
27808   }
27809
27810   // Try to synthesize horizontal adds from adds of shuffles.
27811   EVT VT = N->getValueType(0);
27812   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27813        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27814       isHorizontalBinOp(Op0, Op1, true))
27815     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
27816
27817   return OptimizeConditionalInDecrement(N, DAG);
27818 }
27819
27820 /// performVZEXTCombine - Performs build vector combines
27821 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
27822                                    TargetLowering::DAGCombinerInfo &DCI,
27823                                    const X86Subtarget *Subtarget) {
27824   SDLoc DL(N);
27825   MVT VT = N->getSimpleValueType(0);
27826   SDValue Op = N->getOperand(0);
27827   MVT OpVT = Op.getSimpleValueType();
27828   MVT OpEltVT = OpVT.getVectorElementType();
27829   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
27830
27831   // (vzext (bitcast (vzext (x)) -> (vzext x)
27832   SDValue V = Op;
27833   while (V.getOpcode() == ISD::BITCAST)
27834     V = V.getOperand(0);
27835
27836   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
27837     MVT InnerVT = V.getSimpleValueType();
27838     MVT InnerEltVT = InnerVT.getVectorElementType();
27839
27840     // If the element sizes match exactly, we can just do one larger vzext. This
27841     // is always an exact type match as vzext operates on integer types.
27842     if (OpEltVT == InnerEltVT) {
27843       assert(OpVT == InnerVT && "Types must match for vzext!");
27844       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
27845     }
27846
27847     // The only other way we can combine them is if only a single element of the
27848     // inner vzext is used in the input to the outer vzext.
27849     if (InnerEltVT.getSizeInBits() < InputBits)
27850       return SDValue();
27851
27852     // In this case, the inner vzext is completely dead because we're going to
27853     // only look at bits inside of the low element. Just do the outer vzext on
27854     // a bitcast of the input to the inner.
27855     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
27856   }
27857
27858   // Check if we can bypass extracting and re-inserting an element of an input
27859   // vector. Essentially:
27860   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
27861   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
27862       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
27863       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
27864     SDValue ExtractedV = V.getOperand(0);
27865     SDValue OrigV = ExtractedV.getOperand(0);
27866     if (isNullConstant(ExtractedV.getOperand(1))) {
27867         MVT OrigVT = OrigV.getSimpleValueType();
27868         // Extract a subvector if necessary...
27869         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
27870           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
27871           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
27872                                     OrigVT.getVectorNumElements() / Ratio);
27873           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
27874                               DAG.getIntPtrConstant(0, DL));
27875         }
27876         Op = DAG.getBitcast(OpVT, OrigV);
27877         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
27878       }
27879   }
27880
27881   return SDValue();
27882 }
27883
27884 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
27885                                              DAGCombinerInfo &DCI) const {
27886   SelectionDAG &DAG = DCI.DAG;
27887   switch (N->getOpcode()) {
27888   default: break;
27889   case ISD::EXTRACT_VECTOR_ELT:
27890     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
27891   case ISD::VSELECT:
27892   case ISD::SELECT:
27893   case X86ISD::SHRUNKBLEND:
27894     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
27895   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG, Subtarget);
27896   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
27897   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
27898   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
27899   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
27900   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
27901   case ISD::SHL:
27902   case ISD::SRA:
27903   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
27904   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
27905   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
27906   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
27907   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
27908   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
27909   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
27910   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
27911   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
27912   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
27913   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
27914   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
27915   case ISD::FNEG:           return PerformFNEGCombine(N, DAG, Subtarget);
27916   case ISD::TRUNCATE:       return PerformTRUNCATECombine(N, DAG, Subtarget);
27917   case X86ISD::FXOR:
27918   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
27919   case X86ISD::FMIN:
27920   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
27921   case ISD::FMINNUM:
27922   case ISD::FMAXNUM:        return performFMinNumFMaxNumCombine(N, DAG,
27923                                                                 Subtarget);
27924   case X86ISD::FAND:        return PerformFANDCombine(N, DAG, Subtarget);
27925   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG, Subtarget);
27926   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
27927   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
27928   case ISD::ANY_EXTEND:
27929   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
27930   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
27931   case ISD::SIGN_EXTEND_INREG:
27932     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
27933   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
27934   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
27935   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
27936   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
27937   case X86ISD::SHUFP:       // Handle all target specific shuffles
27938   case X86ISD::PALIGNR:
27939   case X86ISD::BLENDI:
27940   case X86ISD::UNPCKH:
27941   case X86ISD::UNPCKL:
27942   case X86ISD::MOVHLPS:
27943   case X86ISD::MOVLHPS:
27944   case X86ISD::PSHUFB:
27945   case X86ISD::PSHUFD:
27946   case X86ISD::PSHUFHW:
27947   case X86ISD::PSHUFLW:
27948   case X86ISD::MOVSS:
27949   case X86ISD::MOVSD:
27950   case X86ISD::VPERMILPI:
27951   case X86ISD::VPERM2X128:
27952   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
27953   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
27954   case ISD::MGATHER:
27955   case ISD::MSCATTER:       return PerformGatherScatterCombine(N, DAG);
27956   }
27957
27958   return SDValue();
27959 }
27960
27961 /// isTypeDesirableForOp - Return true if the target has native support for
27962 /// the specified value type and it is 'desirable' to use the type for the
27963 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
27964 /// instruction encodings are longer and some i16 instructions are slow.
27965 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
27966   if (!isTypeLegal(VT))
27967     return false;
27968   if (VT != MVT::i16)
27969     return true;
27970
27971   switch (Opc) {
27972   default:
27973     return true;
27974   case ISD::LOAD:
27975   case ISD::SIGN_EXTEND:
27976   case ISD::ZERO_EXTEND:
27977   case ISD::ANY_EXTEND:
27978   case ISD::SHL:
27979   case ISD::SRL:
27980   case ISD::SUB:
27981   case ISD::ADD:
27982   case ISD::MUL:
27983   case ISD::AND:
27984   case ISD::OR:
27985   case ISD::XOR:
27986     return false;
27987   }
27988 }
27989
27990 /// This function checks if any of the users of EFLAGS copies the EFLAGS. We
27991 /// know that the code that lowers COPY of EFLAGS has to use the stack, and if
27992 /// we don't adjust the stack we clobber the first frame index.
27993 /// See X86InstrInfo::copyPhysReg.
27994 bool X86TargetLowering::hasCopyImplyingStackAdjustment(
27995     MachineFunction *MF) const {
27996   const MachineRegisterInfo &MRI = MF->getRegInfo();
27997
27998   return any_of(MRI.reg_instructions(X86::EFLAGS),
27999                 [](const MachineInstr &RI) { return RI.isCopy(); });
28000 }
28001
28002 /// IsDesirableToPromoteOp - This method query the target whether it is
28003 /// beneficial for dag combiner to promote the specified node. If true, it
28004 /// should return the desired promotion type by reference.
28005 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
28006   EVT VT = Op.getValueType();
28007   if (VT != MVT::i16)
28008     return false;
28009
28010   bool Promote = false;
28011   bool Commute = false;
28012   switch (Op.getOpcode()) {
28013   default: break;
28014   case ISD::LOAD: {
28015     LoadSDNode *LD = cast<LoadSDNode>(Op);
28016     // If the non-extending load has a single use and it's not live out, then it
28017     // might be folded.
28018     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
28019                                                      Op.hasOneUse()*/) {
28020       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
28021              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
28022         // The only case where we'd want to promote LOAD (rather then it being
28023         // promoted as an operand is when it's only use is liveout.
28024         if (UI->getOpcode() != ISD::CopyToReg)
28025           return false;
28026       }
28027     }
28028     Promote = true;
28029     break;
28030   }
28031   case ISD::SIGN_EXTEND:
28032   case ISD::ZERO_EXTEND:
28033   case ISD::ANY_EXTEND:
28034     Promote = true;
28035     break;
28036   case ISD::SHL:
28037   case ISD::SRL: {
28038     SDValue N0 = Op.getOperand(0);
28039     // Look out for (store (shl (load), x)).
28040     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
28041       return false;
28042     Promote = true;
28043     break;
28044   }
28045   case ISD::ADD:
28046   case ISD::MUL:
28047   case ISD::AND:
28048   case ISD::OR:
28049   case ISD::XOR:
28050     Commute = true;
28051     // fallthrough
28052   case ISD::SUB: {
28053     SDValue N0 = Op.getOperand(0);
28054     SDValue N1 = Op.getOperand(1);
28055     if (!Commute && MayFoldLoad(N1))
28056       return false;
28057     // Avoid disabling potential load folding opportunities.
28058     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
28059       return false;
28060     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
28061       return false;
28062     Promote = true;
28063   }
28064   }
28065
28066   PVT = MVT::i32;
28067   return Promote;
28068 }
28069
28070 //===----------------------------------------------------------------------===//
28071 //                           X86 Inline Assembly Support
28072 //===----------------------------------------------------------------------===//
28073
28074 // Helper to match a string separated by whitespace.
28075 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
28076   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
28077
28078   for (StringRef Piece : Pieces) {
28079     if (!S.startswith(Piece)) // Check if the piece matches.
28080       return false;
28081
28082     S = S.substr(Piece.size());
28083     StringRef::size_type Pos = S.find_first_not_of(" \t");
28084     if (Pos == 0) // We matched a prefix.
28085       return false;
28086
28087     S = S.substr(Pos);
28088   }
28089
28090   return S.empty();
28091 }
28092
28093 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
28094
28095   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
28096     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
28097         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
28098         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
28099
28100       if (AsmPieces.size() == 3)
28101         return true;
28102       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
28103         return true;
28104     }
28105   }
28106   return false;
28107 }
28108
28109 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
28110   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
28111
28112   std::string AsmStr = IA->getAsmString();
28113
28114   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
28115   if (!Ty || Ty->getBitWidth() % 16 != 0)
28116     return false;
28117
28118   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
28119   SmallVector<StringRef, 4> AsmPieces;
28120   SplitString(AsmStr, AsmPieces, ";\n");
28121
28122   switch (AsmPieces.size()) {
28123   default: return false;
28124   case 1:
28125     // FIXME: this should verify that we are targeting a 486 or better.  If not,
28126     // we will turn this bswap into something that will be lowered to logical
28127     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
28128     // lower so don't worry about this.
28129     // bswap $0
28130     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
28131         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
28132         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
28133         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
28134         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
28135         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
28136       // No need to check constraints, nothing other than the equivalent of
28137       // "=r,0" would be valid here.
28138       return IntrinsicLowering::LowerToByteSwap(CI);
28139     }
28140
28141     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
28142     if (CI->getType()->isIntegerTy(16) &&
28143         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28144         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
28145          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
28146       AsmPieces.clear();
28147       StringRef ConstraintsStr = IA->getConstraintString();
28148       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28149       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28150       if (clobbersFlagRegisters(AsmPieces))
28151         return IntrinsicLowering::LowerToByteSwap(CI);
28152     }
28153     break;
28154   case 3:
28155     if (CI->getType()->isIntegerTy(32) &&
28156         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28157         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
28158         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
28159         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
28160       AsmPieces.clear();
28161       StringRef ConstraintsStr = IA->getConstraintString();
28162       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28163       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28164       if (clobbersFlagRegisters(AsmPieces))
28165         return IntrinsicLowering::LowerToByteSwap(CI);
28166     }
28167
28168     if (CI->getType()->isIntegerTy(64)) {
28169       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
28170       if (Constraints.size() >= 2 &&
28171           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
28172           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
28173         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
28174         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
28175             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
28176             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
28177           return IntrinsicLowering::LowerToByteSwap(CI);
28178       }
28179     }
28180     break;
28181   }
28182   return false;
28183 }
28184
28185 /// getConstraintType - Given a constraint letter, return the type of
28186 /// constraint it is for this target.
28187 X86TargetLowering::ConstraintType
28188 X86TargetLowering::getConstraintType(StringRef Constraint) const {
28189   if (Constraint.size() == 1) {
28190     switch (Constraint[0]) {
28191     case 'R':
28192     case 'q':
28193     case 'Q':
28194     case 'f':
28195     case 't':
28196     case 'u':
28197     case 'y':
28198     case 'x':
28199     case 'Y':
28200     case 'l':
28201       return C_RegisterClass;
28202     case 'a':
28203     case 'b':
28204     case 'c':
28205     case 'd':
28206     case 'S':
28207     case 'D':
28208     case 'A':
28209       return C_Register;
28210     case 'I':
28211     case 'J':
28212     case 'K':
28213     case 'L':
28214     case 'M':
28215     case 'N':
28216     case 'G':
28217     case 'C':
28218     case 'e':
28219     case 'Z':
28220       return C_Other;
28221     default:
28222       break;
28223     }
28224   }
28225   return TargetLowering::getConstraintType(Constraint);
28226 }
28227
28228 /// Examine constraint type and operand type and determine a weight value.
28229 /// This object must already have been set up with the operand type
28230 /// and the current alternative constraint selected.
28231 TargetLowering::ConstraintWeight
28232   X86TargetLowering::getSingleConstraintMatchWeight(
28233     AsmOperandInfo &info, const char *constraint) const {
28234   ConstraintWeight weight = CW_Invalid;
28235   Value *CallOperandVal = info.CallOperandVal;
28236     // If we don't have a value, we can't do a match,
28237     // but allow it at the lowest weight.
28238   if (!CallOperandVal)
28239     return CW_Default;
28240   Type *type = CallOperandVal->getType();
28241   // Look at the constraint type.
28242   switch (*constraint) {
28243   default:
28244     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
28245   case 'R':
28246   case 'q':
28247   case 'Q':
28248   case 'a':
28249   case 'b':
28250   case 'c':
28251   case 'd':
28252   case 'S':
28253   case 'D':
28254   case 'A':
28255     if (CallOperandVal->getType()->isIntegerTy())
28256       weight = CW_SpecificReg;
28257     break;
28258   case 'f':
28259   case 't':
28260   case 'u':
28261     if (type->isFloatingPointTy())
28262       weight = CW_SpecificReg;
28263     break;
28264   case 'y':
28265     if (type->isX86_MMXTy() && Subtarget->hasMMX())
28266       weight = CW_SpecificReg;
28267     break;
28268   case 'x':
28269   case 'Y':
28270     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
28271         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
28272       weight = CW_Register;
28273     break;
28274   case 'I':
28275     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
28276       if (C->getZExtValue() <= 31)
28277         weight = CW_Constant;
28278     }
28279     break;
28280   case 'J':
28281     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28282       if (C->getZExtValue() <= 63)
28283         weight = CW_Constant;
28284     }
28285     break;
28286   case 'K':
28287     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28288       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
28289         weight = CW_Constant;
28290     }
28291     break;
28292   case 'L':
28293     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28294       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
28295         weight = CW_Constant;
28296     }
28297     break;
28298   case 'M':
28299     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28300       if (C->getZExtValue() <= 3)
28301         weight = CW_Constant;
28302     }
28303     break;
28304   case 'N':
28305     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28306       if (C->getZExtValue() <= 0xff)
28307         weight = CW_Constant;
28308     }
28309     break;
28310   case 'G':
28311   case 'C':
28312     if (isa<ConstantFP>(CallOperandVal)) {
28313       weight = CW_Constant;
28314     }
28315     break;
28316   case 'e':
28317     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28318       if ((C->getSExtValue() >= -0x80000000LL) &&
28319           (C->getSExtValue() <= 0x7fffffffLL))
28320         weight = CW_Constant;
28321     }
28322     break;
28323   case 'Z':
28324     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28325       if (C->getZExtValue() <= 0xffffffff)
28326         weight = CW_Constant;
28327     }
28328     break;
28329   }
28330   return weight;
28331 }
28332
28333 /// LowerXConstraint - try to replace an X constraint, which matches anything,
28334 /// with another that has more specific requirements based on the type of the
28335 /// corresponding operand.
28336 const char *X86TargetLowering::
28337 LowerXConstraint(EVT ConstraintVT) const {
28338   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
28339   // 'f' like normal targets.
28340   if (ConstraintVT.isFloatingPoint()) {
28341     if (Subtarget->hasSSE2())
28342       return "Y";
28343     if (Subtarget->hasSSE1())
28344       return "x";
28345   }
28346
28347   return TargetLowering::LowerXConstraint(ConstraintVT);
28348 }
28349
28350 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
28351 /// vector.  If it is invalid, don't add anything to Ops.
28352 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
28353                                                      std::string &Constraint,
28354                                                      std::vector<SDValue>&Ops,
28355                                                      SelectionDAG &DAG) const {
28356   SDValue Result;
28357
28358   // Only support length 1 constraints for now.
28359   if (Constraint.length() > 1) return;
28360
28361   char ConstraintLetter = Constraint[0];
28362   switch (ConstraintLetter) {
28363   default: break;
28364   case 'I':
28365     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28366       if (C->getZExtValue() <= 31) {
28367         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28368                                        Op.getValueType());
28369         break;
28370       }
28371     }
28372     return;
28373   case 'J':
28374     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28375       if (C->getZExtValue() <= 63) {
28376         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28377                                        Op.getValueType());
28378         break;
28379       }
28380     }
28381     return;
28382   case 'K':
28383     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28384       if (isInt<8>(C->getSExtValue())) {
28385         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28386                                        Op.getValueType());
28387         break;
28388       }
28389     }
28390     return;
28391   case 'L':
28392     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28393       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
28394           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
28395         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
28396                                        Op.getValueType());
28397         break;
28398       }
28399     }
28400     return;
28401   case 'M':
28402     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28403       if (C->getZExtValue() <= 3) {
28404         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28405                                        Op.getValueType());
28406         break;
28407       }
28408     }
28409     return;
28410   case 'N':
28411     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28412       if (C->getZExtValue() <= 255) {
28413         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28414                                        Op.getValueType());
28415         break;
28416       }
28417     }
28418     return;
28419   case 'O':
28420     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28421       if (C->getZExtValue() <= 127) {
28422         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28423                                        Op.getValueType());
28424         break;
28425       }
28426     }
28427     return;
28428   case 'e': {
28429     // 32-bit signed value
28430     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28431       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28432                                            C->getSExtValue())) {
28433         // Widen to 64 bits here to get it sign extended.
28434         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
28435         break;
28436       }
28437     // FIXME gcc accepts some relocatable values here too, but only in certain
28438     // memory models; it's complicated.
28439     }
28440     return;
28441   }
28442   case 'Z': {
28443     // 32-bit unsigned value
28444     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28445       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28446                                            C->getZExtValue())) {
28447         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28448                                        Op.getValueType());
28449         break;
28450       }
28451     }
28452     // FIXME gcc accepts some relocatable values here too, but only in certain
28453     // memory models; it's complicated.
28454     return;
28455   }
28456   case 'i': {
28457     // Literal immediates are always ok.
28458     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
28459       // Widen to 64 bits here to get it sign extended.
28460       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
28461       break;
28462     }
28463
28464     // In any sort of PIC mode addresses need to be computed at runtime by
28465     // adding in a register or some sort of table lookup.  These can't
28466     // be used as immediates.
28467     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
28468       return;
28469
28470     // If we are in non-pic codegen mode, we allow the address of a global (with
28471     // an optional displacement) to be used with 'i'.
28472     GlobalAddressSDNode *GA = nullptr;
28473     int64_t Offset = 0;
28474
28475     // Match either (GA), (GA+C), (GA+C1+C2), etc.
28476     while (1) {
28477       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
28478         Offset += GA->getOffset();
28479         break;
28480       } else if (Op.getOpcode() == ISD::ADD) {
28481         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28482           Offset += C->getZExtValue();
28483           Op = Op.getOperand(0);
28484           continue;
28485         }
28486       } else if (Op.getOpcode() == ISD::SUB) {
28487         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28488           Offset += -C->getZExtValue();
28489           Op = Op.getOperand(0);
28490           continue;
28491         }
28492       }
28493
28494       // Otherwise, this isn't something we can handle, reject it.
28495       return;
28496     }
28497
28498     const GlobalValue *GV = GA->getGlobal();
28499     // If we require an extra load to get this address, as in PIC mode, we
28500     // can't accept it.
28501     if (isGlobalStubReference(
28502             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
28503       return;
28504
28505     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
28506                                         GA->getValueType(0), Offset);
28507     break;
28508   }
28509   }
28510
28511   if (Result.getNode()) {
28512     Ops.push_back(Result);
28513     return;
28514   }
28515   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
28516 }
28517
28518 std::pair<unsigned, const TargetRegisterClass *>
28519 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
28520                                                 StringRef Constraint,
28521                                                 MVT VT) const {
28522   // First, see if this is a constraint that directly corresponds to an LLVM
28523   // register class.
28524   if (Constraint.size() == 1) {
28525     // GCC Constraint Letters
28526     switch (Constraint[0]) {
28527     default: break;
28528       // TODO: Slight differences here in allocation order and leaving
28529       // RIP in the class. Do they matter any more here than they do
28530       // in the normal allocation?
28531     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
28532       if (Subtarget->is64Bit()) {
28533         if (VT == MVT::i32 || VT == MVT::f32)
28534           return std::make_pair(0U, &X86::GR32RegClass);
28535         if (VT == MVT::i16)
28536           return std::make_pair(0U, &X86::GR16RegClass);
28537         if (VT == MVT::i8 || VT == MVT::i1)
28538           return std::make_pair(0U, &X86::GR8RegClass);
28539         if (VT == MVT::i64 || VT == MVT::f64)
28540           return std::make_pair(0U, &X86::GR64RegClass);
28541         break;
28542       }
28543       // 32-bit fallthrough
28544     case 'Q':   // Q_REGS
28545       if (VT == MVT::i32 || VT == MVT::f32)
28546         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
28547       if (VT == MVT::i16)
28548         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
28549       if (VT == MVT::i8 || VT == MVT::i1)
28550         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
28551       if (VT == MVT::i64)
28552         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
28553       break;
28554     case 'r':   // GENERAL_REGS
28555     case 'l':   // INDEX_REGS
28556       if (VT == MVT::i8 || VT == MVT::i1)
28557         return std::make_pair(0U, &X86::GR8RegClass);
28558       if (VT == MVT::i16)
28559         return std::make_pair(0U, &X86::GR16RegClass);
28560       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
28561         return std::make_pair(0U, &X86::GR32RegClass);
28562       return std::make_pair(0U, &X86::GR64RegClass);
28563     case 'R':   // LEGACY_REGS
28564       if (VT == MVT::i8 || VT == MVT::i1)
28565         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
28566       if (VT == MVT::i16)
28567         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
28568       if (VT == MVT::i32 || !Subtarget->is64Bit())
28569         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
28570       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
28571     case 'f':  // FP Stack registers.
28572       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
28573       // value to the correct fpstack register class.
28574       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
28575         return std::make_pair(0U, &X86::RFP32RegClass);
28576       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
28577         return std::make_pair(0U, &X86::RFP64RegClass);
28578       return std::make_pair(0U, &X86::RFP80RegClass);
28579     case 'y':   // MMX_REGS if MMX allowed.
28580       if (!Subtarget->hasMMX()) break;
28581       return std::make_pair(0U, &X86::VR64RegClass);
28582     case 'Y':   // SSE_REGS if SSE2 allowed
28583       if (!Subtarget->hasSSE2()) break;
28584       // FALL THROUGH.
28585     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
28586       if (!Subtarget->hasSSE1()) break;
28587
28588       switch (VT.SimpleTy) {
28589       default: break;
28590       // Scalar SSE types.
28591       case MVT::f32:
28592       case MVT::i32:
28593         return std::make_pair(0U, &X86::FR32RegClass);
28594       case MVT::f64:
28595       case MVT::i64:
28596         return std::make_pair(0U, &X86::FR64RegClass);
28597       // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28598       // Vector types.
28599       case MVT::v16i8:
28600       case MVT::v8i16:
28601       case MVT::v4i32:
28602       case MVT::v2i64:
28603       case MVT::v4f32:
28604       case MVT::v2f64:
28605         return std::make_pair(0U, &X86::VR128RegClass);
28606       // AVX types.
28607       case MVT::v32i8:
28608       case MVT::v16i16:
28609       case MVT::v8i32:
28610       case MVT::v4i64:
28611       case MVT::v8f32:
28612       case MVT::v4f64:
28613         return std::make_pair(0U, &X86::VR256RegClass);
28614       case MVT::v8f64:
28615       case MVT::v16f32:
28616       case MVT::v16i32:
28617       case MVT::v8i64:
28618         return std::make_pair(0U, &X86::VR512RegClass);
28619       }
28620       break;
28621     }
28622   }
28623
28624   // Use the default implementation in TargetLowering to convert the register
28625   // constraint into a member of a register class.
28626   std::pair<unsigned, const TargetRegisterClass*> Res;
28627   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
28628
28629   // Not found as a standard register?
28630   if (!Res.second) {
28631     // Map st(0) -> st(7) -> ST0
28632     if (Constraint.size() == 7 && Constraint[0] == '{' &&
28633         tolower(Constraint[1]) == 's' &&
28634         tolower(Constraint[2]) == 't' &&
28635         Constraint[3] == '(' &&
28636         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
28637         Constraint[5] == ')' &&
28638         Constraint[6] == '}') {
28639
28640       Res.first = X86::FP0+Constraint[4]-'0';
28641       Res.second = &X86::RFP80RegClass;
28642       return Res;
28643     }
28644
28645     // GCC allows "st(0)" to be called just plain "st".
28646     if (StringRef("{st}").equals_lower(Constraint)) {
28647       Res.first = X86::FP0;
28648       Res.second = &X86::RFP80RegClass;
28649       return Res;
28650     }
28651
28652     // flags -> EFLAGS
28653     if (StringRef("{flags}").equals_lower(Constraint)) {
28654       Res.first = X86::EFLAGS;
28655       Res.second = &X86::CCRRegClass;
28656       return Res;
28657     }
28658
28659     // 'A' means EAX + EDX.
28660     if (Constraint == "A") {
28661       Res.first = X86::EAX;
28662       Res.second = &X86::GR32_ADRegClass;
28663       return Res;
28664     }
28665     return Res;
28666   }
28667
28668   // Otherwise, check to see if this is a register class of the wrong value
28669   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
28670   // turn into {ax},{dx}.
28671   // MVT::Other is used to specify clobber names.
28672   if (Res.second->hasType(VT) || VT == MVT::Other)
28673     return Res;   // Correct type already, nothing to do.
28674
28675   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
28676   // return "eax". This should even work for things like getting 64bit integer
28677   // registers when given an f64 type.
28678   const TargetRegisterClass *Class = Res.second;
28679   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
28680       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
28681     unsigned Size = VT.getSizeInBits();
28682     if (Size == 1) Size = 8;
28683     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, Size);
28684     if (DestReg > 0) {
28685       Res.first = DestReg;
28686       Res.second = Size == 8 ? &X86::GR8RegClass
28687                  : Size == 16 ? &X86::GR16RegClass
28688                  : Size == 32 ? &X86::GR32RegClass
28689                  : &X86::GR64RegClass;
28690       assert(Res.second->contains(Res.first) && "Register in register class");
28691     } else {
28692       // No register found/type mismatch.
28693       Res.first = 0;
28694       Res.second = nullptr;
28695     }
28696   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
28697              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
28698              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
28699              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
28700              Class == &X86::VR512RegClass) {
28701     // Handle references to XMM physical registers that got mapped into the
28702     // wrong class.  This can happen with constraints like {xmm0} where the
28703     // target independent register mapper will just pick the first match it can
28704     // find, ignoring the required type.
28705
28706     // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28707     if (VT == MVT::f32 || VT == MVT::i32)
28708       Res.second = &X86::FR32RegClass;
28709     else if (VT == MVT::f64 || VT == MVT::i64)
28710       Res.second = &X86::FR64RegClass;
28711     else if (X86::VR128RegClass.hasType(VT))
28712       Res.second = &X86::VR128RegClass;
28713     else if (X86::VR256RegClass.hasType(VT))
28714       Res.second = &X86::VR256RegClass;
28715     else if (X86::VR512RegClass.hasType(VT))
28716       Res.second = &X86::VR512RegClass;
28717     else {
28718       // Type mismatch and not a clobber: Return an error;
28719       Res.first = 0;
28720       Res.second = nullptr;
28721     }
28722   }
28723
28724   return Res;
28725 }
28726
28727 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
28728                                             const AddrMode &AM, Type *Ty,
28729                                             unsigned AS) const {
28730   // Scaling factors are not free at all.
28731   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
28732   // will take 2 allocations in the out of order engine instead of 1
28733   // for plain addressing mode, i.e. inst (reg1).
28734   // E.g.,
28735   // vaddps (%rsi,%drx), %ymm0, %ymm1
28736   // Requires two allocations (one for the load, one for the computation)
28737   // whereas:
28738   // vaddps (%rsi), %ymm0, %ymm1
28739   // Requires just 1 allocation, i.e., freeing allocations for other operations
28740   // and having less micro operations to execute.
28741   //
28742   // For some X86 architectures, this is even worse because for instance for
28743   // stores, the complex addressing mode forces the instruction to use the
28744   // "load" ports instead of the dedicated "store" port.
28745   // E.g., on Haswell:
28746   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
28747   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
28748   if (isLegalAddressingMode(DL, AM, Ty, AS))
28749     // Scale represents reg2 * scale, thus account for 1
28750     // as soon as we use a second register.
28751     return AM.Scale != 0;
28752   return -1;
28753 }
28754
28755 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
28756   // Integer division on x86 is expensive. However, when aggressively optimizing
28757   // for code size, we prefer to use a div instruction, as it is usually smaller
28758   // than the alternative sequence.
28759   // The exception to this is vector division. Since x86 doesn't have vector
28760   // integer division, leaving the division as-is is a loss even in terms of
28761   // size, because it will have to be scalarized, while the alternative code
28762   // sequence can be performed in vector form.
28763   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
28764                                    Attribute::MinSize);
28765   return OptSize && !VT.isVector();
28766 }