[X86][XOP] Add VPROT instruction opcodes
[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 "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
71                                      const X86Subtarget &STI)
72     : TargetLowering(TM), Subtarget(&STI) {
73   X86ScalarSSEf64 = Subtarget->hasSSE2();
74   X86ScalarSSEf32 = Subtarget->hasSSE1();
75   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
76
77   // Set up the TargetLowering object.
78   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
79
80   // X86 is weird. It always uses i8 for shift amounts and setcc results.
81   setBooleanContents(ZeroOrOneBooleanContent);
82   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
83   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
84
85   // For 64-bit, since we have so many registers, use the ILP scheduler.
86   // For 32-bit, use the register pressure specific scheduling.
87   // For Atom, always use ILP scheduling.
88   if (Subtarget->isAtom())
89     setSchedulingPreference(Sched::ILP);
90   else if (Subtarget->is64Bit())
91     setSchedulingPreference(Sched::ILP);
92   else
93     setSchedulingPreference(Sched::RegPressure);
94   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
95   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
96
97   // Bypass expensive divides on Atom when compiling with O2.
98   if (TM.getOptLevel() >= CodeGenOpt::Default) {
99     if (Subtarget->hasSlowDivide32())
100       addBypassSlowDiv(32, 8);
101     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
102       addBypassSlowDiv(64, 16);
103   }
104
105   if (Subtarget->isTargetKnownWindowsMSVC()) {
106     // Setup Windows compiler runtime calls.
107     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
108     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
109     setLibcallName(RTLIB::SREM_I64, "_allrem");
110     setLibcallName(RTLIB::UREM_I64, "_aullrem");
111     setLibcallName(RTLIB::MUL_I64, "_allmul");
112     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
113     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
114     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
115     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
116     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
117   }
118
119   if (Subtarget->isTargetDarwin()) {
120     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
121     setUseUnderscoreSetJmp(false);
122     setUseUnderscoreLongJmp(false);
123   } else if (Subtarget->isTargetWindowsGNU()) {
124     // MS runtime is weird: it exports _setjmp, but longjmp!
125     setUseUnderscoreSetJmp(true);
126     setUseUnderscoreLongJmp(false);
127   } else {
128     setUseUnderscoreSetJmp(true);
129     setUseUnderscoreLongJmp(true);
130   }
131
132   // Set up the register classes.
133   addRegisterClass(MVT::i8, &X86::GR8RegClass);
134   addRegisterClass(MVT::i16, &X86::GR16RegClass);
135   addRegisterClass(MVT::i32, &X86::GR32RegClass);
136   if (Subtarget->is64Bit())
137     addRegisterClass(MVT::i64, &X86::GR64RegClass);
138
139   for (MVT VT : MVT::integer_valuetypes())
140     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
141
142   // We don't accept any truncstore of integer registers.
143   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
144   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
145   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
146   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
147   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
148   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
149
150   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
151
152   // SETOEQ and SETUNE require checking two conditions.
153   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
154   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
155   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
156   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
157   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
158   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
159
160   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
161   // operation.
162   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
163   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
164   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
165
166   if (Subtarget->is64Bit()) {
167     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512())
168       // f32/f64 are legal, f80 is custom.
169       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
170     else
171       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
172     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
173   } else if (!Subtarget->useSoftFloat()) {
174     // We have an algorithm for SSE2->double, and we turn this into a
175     // 64-bit FILD followed by conditional FADD for other targets.
176     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
177     // We have an algorithm for SSE2, and we turn this into a 64-bit
178     // FILD or VCVTUSI2SS/SD for other targets.
179     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
180   }
181
182   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
183   // this operation.
184   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
185   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
186
187   if (!Subtarget->useSoftFloat()) {
188     // SSE has no i16 to fp conversion, only i32
189     if (X86ScalarSSEf32) {
190       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
191       // f32 and f64 cases are Legal, f80 case is not
192       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
193     } else {
194       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
195       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
196     }
197   } else {
198     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
199     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
200   }
201
202   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
203   // are Legal, f80 is custom lowered.
204   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
205   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
206
207   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
208   // this operation.
209   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
210   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
211
212   if (X86ScalarSSEf32) {
213     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
214     // f32 and f64 cases are Legal, f80 case is not
215     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
216   } else {
217     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
218     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
219   }
220
221   // Handle FP_TO_UINT by promoting the destination to a larger signed
222   // conversion.
223   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
224   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
225   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
226
227   if (Subtarget->is64Bit()) {
228     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
229       // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
230       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
231       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Custom);
232     } else {
233       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
234       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Expand);
235     }
236   } else if (!Subtarget->useSoftFloat()) {
237     // Since AVX is a superset of SSE3, only check for SSE here.
238     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
239       // Expand FP_TO_UINT into a select.
240       // FIXME: We would like to use a Custom expander here eventually to do
241       // the optimal thing for SSE vs. the default expansion in the legalizer.
242       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
243     else
244       // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
245       // With SSE3 we can use fisttpll to convert to a signed i64; without
246       // SSE, we're stuck with a fistpll.
247       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
248
249     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
250   }
251
252   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
253   if (!X86ScalarSSEf64) {
254     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
255     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
256     if (Subtarget->is64Bit()) {
257       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
258       // Without SSE, i64->f64 goes through memory.
259       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
260     }
261   }
262
263   // Scalar integer divide and remainder are lowered to use operations that
264   // produce two results, to match the available instructions. This exposes
265   // the two-result form to trivial CSE, which is able to combine x/y and x%y
266   // into a single instruction.
267   //
268   // Scalar integer multiply-high is also lowered to use two-result
269   // operations, to match the available instructions. However, plain multiply
270   // (low) operations are left as Legal, as there are single-result
271   // instructions for this in x86. Using the two-result multiply instructions
272   // when both high and low results are needed must be arranged by dagcombine.
273   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
274     MVT VT = IntVTs[i];
275     setOperationAction(ISD::MULHS, VT, Expand);
276     setOperationAction(ISD::MULHU, VT, Expand);
277     setOperationAction(ISD::SDIV, VT, Expand);
278     setOperationAction(ISD::UDIV, VT, Expand);
279     setOperationAction(ISD::SREM, VT, Expand);
280     setOperationAction(ISD::UREM, VT, Expand);
281
282     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
283     setOperationAction(ISD::ADDC, VT, Custom);
284     setOperationAction(ISD::ADDE, VT, Custom);
285     setOperationAction(ISD::SUBC, VT, Custom);
286     setOperationAction(ISD::SUBE, VT, Custom);
287   }
288
289   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
290   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
291   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
292   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
293   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
294   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
295   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
296   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
297   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
298   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
299   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
300   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
301   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
302   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
303   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
304   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
305   if (Subtarget->is64Bit())
306     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
307   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
308   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
309   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
310   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
311
312   if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
313     // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
314     // is. We should promote the value to 64-bits to solve this.
315     // This is what the CRT headers do - `fmodf` is an inline header
316     // function casting to f64 and calling `fmod`.
317     setOperationAction(ISD::FREM           , MVT::f32  , Promote);
318   } else {
319     setOperationAction(ISD::FREM           , MVT::f32  , Expand);
320   }
321
322   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
323   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
324   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
325
326   // Promote the i8 variants and force them on up to i32 which has a shorter
327   // encoding.
328   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
329   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
330   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
331   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
332   if (Subtarget->hasBMI()) {
333     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
334     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
335     if (Subtarget->is64Bit())
336       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
337   } else {
338     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
339     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
340     if (Subtarget->is64Bit())
341       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
342   }
343
344   if (Subtarget->hasLZCNT()) {
345     // When promoting the i8 variants, force them to i32 for a shorter
346     // encoding.
347     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
348     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
349     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
350     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
351     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
352     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
353     if (Subtarget->is64Bit())
354       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
355   } else {
356     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
357     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
358     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
359     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
360     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
361     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
362     if (Subtarget->is64Bit()) {
363       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
364       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
365     }
366   }
367
368   // Special handling for half-precision floating point conversions.
369   // If we don't have F16C support, then lower half float conversions
370   // into library calls.
371   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
372     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
373     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
374   }
375
376   // There's never any support for operations beyond MVT::f32.
377   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
378   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
379   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
380   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
381
382   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
383   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
384   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
385   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
386   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
387   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
388
389   if (Subtarget->hasPOPCNT()) {
390     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
391   } else {
392     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
393     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
394     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
395     if (Subtarget->is64Bit())
396       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
397   }
398
399   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
400
401   if (!Subtarget->hasMOVBE())
402     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
403
404   // These should be promoted to a larger select which is supported.
405   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
406   // X86 wants to expand cmov itself.
407   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
408   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
409   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
410   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
411   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
412   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
413   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
414   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
415   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
416   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
417   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
418   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
419   if (Subtarget->is64Bit()) {
420     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
421     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
422   }
423   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
424   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
425   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
426   // support continuation, user-level threading, and etc.. As a result, no
427   // other SjLj exception interfaces are implemented and please don't build
428   // your own exception handling based on them.
429   // LLVM/Clang supports zero-cost DWARF exception handling.
430   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
431   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
432
433   // Darwin ABI issue.
434   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
435   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
436   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
437   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
438   if (Subtarget->is64Bit())
439     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
440   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
441   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
442   if (Subtarget->is64Bit()) {
443     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
444     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
445     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
446     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
447     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
448   }
449   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
450   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
451   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
452   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
453   if (Subtarget->is64Bit()) {
454     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
455     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
456     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
457   }
458
459   if (Subtarget->hasSSE1())
460     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
461
462   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
463
464   // Expand certain atomics
465   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
466     MVT VT = IntVTs[i];
467     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
468     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
469     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
470   }
471
472   if (Subtarget->hasCmpxchg16b()) {
473     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
474   }
475
476   // FIXME - use subtarget debug flags
477   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
478       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
479     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
480   }
481
482   if (Subtarget->isTarget64BitLP64()) {
483     setExceptionPointerRegister(X86::RAX);
484     setExceptionSelectorRegister(X86::RDX);
485   } else {
486     setExceptionPointerRegister(X86::EAX);
487     setExceptionSelectorRegister(X86::EDX);
488   }
489   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
490   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
491
492   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
493   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
494
495   setOperationAction(ISD::TRAP, MVT::Other, Legal);
496   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
497
498   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
499   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
500   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
501   if (Subtarget->is64Bit()) {
502     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
503     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
504   } else {
505     // TargetInfo::CharPtrBuiltinVaList
506     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
507     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
508   }
509
510   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
511   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
512
513   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
514
515   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
516   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
517   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
518
519   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
520     // f32 and f64 use SSE.
521     // Set up the FP register classes.
522     addRegisterClass(MVT::f32, &X86::FR32RegClass);
523     addRegisterClass(MVT::f64, &X86::FR64RegClass);
524
525     // Use ANDPD to simulate FABS.
526     setOperationAction(ISD::FABS , MVT::f64, Custom);
527     setOperationAction(ISD::FABS , MVT::f32, Custom);
528
529     // Use XORP to simulate FNEG.
530     setOperationAction(ISD::FNEG , MVT::f64, Custom);
531     setOperationAction(ISD::FNEG , MVT::f32, Custom);
532
533     // Use ANDPD and ORPD to simulate FCOPYSIGN.
534     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
535     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
536
537     // Lower this to FGETSIGNx86 plus an AND.
538     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
539     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
540
541     // We don't support sin/cos/fmod
542     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
543     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
544     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
545     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
546     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
547     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
548
549     // Expand FP immediates into loads from the stack, except for the special
550     // cases we handle.
551     addLegalFPImmediate(APFloat(+0.0)); // xorpd
552     addLegalFPImmediate(APFloat(+0.0f)); // xorps
553   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
554     // Use SSE for f32, x87 for f64.
555     // Set up the FP register classes.
556     addRegisterClass(MVT::f32, &X86::FR32RegClass);
557     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
558
559     // Use ANDPS to simulate FABS.
560     setOperationAction(ISD::FABS , MVT::f32, Custom);
561
562     // Use XORP to simulate FNEG.
563     setOperationAction(ISD::FNEG , MVT::f32, Custom);
564
565     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
566
567     // Use ANDPS and ORPS to simulate FCOPYSIGN.
568     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
569     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
570
571     // We don't support sin/cos/fmod
572     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
573     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
574     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
575
576     // Special cases we handle for FP constants.
577     addLegalFPImmediate(APFloat(+0.0f)); // xorps
578     addLegalFPImmediate(APFloat(+0.0)); // FLD0
579     addLegalFPImmediate(APFloat(+1.0)); // FLD1
580     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
581     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
582
583     if (!TM.Options.UnsafeFPMath) {
584       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
585       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
586       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
587     }
588   } else if (!Subtarget->useSoftFloat()) {
589     // f32 and f64 in x87.
590     // Set up the FP register classes.
591     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
592     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
593
594     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
595     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
596     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
597     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
598
599     if (!TM.Options.UnsafeFPMath) {
600       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
601       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
602       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
603       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
604       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
605       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
606     }
607     addLegalFPImmediate(APFloat(+0.0)); // FLD0
608     addLegalFPImmediate(APFloat(+1.0)); // FLD1
609     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
610     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
611     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
612     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
613     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
614     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
615   }
616
617   // We don't support FMA.
618   setOperationAction(ISD::FMA, MVT::f64, Expand);
619   setOperationAction(ISD::FMA, MVT::f32, Expand);
620
621   // Long double always uses X87.
622   if (!Subtarget->useSoftFloat()) {
623     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
624     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
625     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
626     {
627       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
628       addLegalFPImmediate(TmpFlt);  // FLD0
629       TmpFlt.changeSign();
630       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
631
632       bool ignored;
633       APFloat TmpFlt2(+1.0);
634       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
635                       &ignored);
636       addLegalFPImmediate(TmpFlt2);  // FLD1
637       TmpFlt2.changeSign();
638       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
639     }
640
641     if (!TM.Options.UnsafeFPMath) {
642       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
643       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
644       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
645     }
646
647     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
648     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
649     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
650     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
651     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
652     setOperationAction(ISD::FMA, MVT::f80, Expand);
653   }
654
655   // Always use a library call for pow.
656   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
657   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
658   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
659
660   setOperationAction(ISD::FLOG, MVT::f80, Expand);
661   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
662   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
663   setOperationAction(ISD::FEXP, MVT::f80, Expand);
664   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
665   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
666   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
667
668   // First set operation action for all vector types to either promote
669   // (for widening) or expand (for scalarization). Then we will selectively
670   // turn on ones that can be effectively codegen'd.
671   for (MVT VT : MVT::vector_valuetypes()) {
672     setOperationAction(ISD::ADD , VT, Expand);
673     setOperationAction(ISD::SUB , VT, Expand);
674     setOperationAction(ISD::FADD, VT, Expand);
675     setOperationAction(ISD::FNEG, VT, Expand);
676     setOperationAction(ISD::FSUB, VT, Expand);
677     setOperationAction(ISD::MUL , VT, Expand);
678     setOperationAction(ISD::FMUL, VT, Expand);
679     setOperationAction(ISD::SDIV, VT, Expand);
680     setOperationAction(ISD::UDIV, VT, Expand);
681     setOperationAction(ISD::FDIV, VT, Expand);
682     setOperationAction(ISD::SREM, VT, Expand);
683     setOperationAction(ISD::UREM, VT, Expand);
684     setOperationAction(ISD::LOAD, VT, Expand);
685     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
686     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
687     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
688     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
689     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
690     setOperationAction(ISD::FABS, VT, Expand);
691     setOperationAction(ISD::FSIN, VT, Expand);
692     setOperationAction(ISD::FSINCOS, VT, Expand);
693     setOperationAction(ISD::FCOS, VT, Expand);
694     setOperationAction(ISD::FSINCOS, VT, Expand);
695     setOperationAction(ISD::FREM, VT, Expand);
696     setOperationAction(ISD::FMA,  VT, Expand);
697     setOperationAction(ISD::FPOWI, VT, Expand);
698     setOperationAction(ISD::FSQRT, VT, Expand);
699     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
700     setOperationAction(ISD::FFLOOR, VT, Expand);
701     setOperationAction(ISD::FCEIL, VT, Expand);
702     setOperationAction(ISD::FTRUNC, VT, Expand);
703     setOperationAction(ISD::FRINT, VT, Expand);
704     setOperationAction(ISD::FNEARBYINT, VT, Expand);
705     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
706     setOperationAction(ISD::MULHS, VT, Expand);
707     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
708     setOperationAction(ISD::MULHU, VT, Expand);
709     setOperationAction(ISD::SDIVREM, VT, Expand);
710     setOperationAction(ISD::UDIVREM, VT, Expand);
711     setOperationAction(ISD::FPOW, VT, Expand);
712     setOperationAction(ISD::CTPOP, VT, Expand);
713     setOperationAction(ISD::CTTZ, VT, Expand);
714     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
715     setOperationAction(ISD::CTLZ, VT, Expand);
716     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
717     setOperationAction(ISD::SHL, VT, Expand);
718     setOperationAction(ISD::SRA, VT, Expand);
719     setOperationAction(ISD::SRL, VT, Expand);
720     setOperationAction(ISD::ROTL, VT, Expand);
721     setOperationAction(ISD::ROTR, VT, Expand);
722     setOperationAction(ISD::BSWAP, VT, Expand);
723     setOperationAction(ISD::SETCC, VT, Expand);
724     setOperationAction(ISD::FLOG, VT, Expand);
725     setOperationAction(ISD::FLOG2, VT, Expand);
726     setOperationAction(ISD::FLOG10, VT, Expand);
727     setOperationAction(ISD::FEXP, VT, Expand);
728     setOperationAction(ISD::FEXP2, VT, Expand);
729     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
730     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
731     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
732     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
733     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
734     setOperationAction(ISD::TRUNCATE, VT, Expand);
735     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
736     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
737     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
738     setOperationAction(ISD::VSELECT, VT, Expand);
739     setOperationAction(ISD::SELECT_CC, VT, Expand);
740     for (MVT InnerVT : MVT::vector_valuetypes()) {
741       setTruncStoreAction(InnerVT, VT, Expand);
742
743       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
744       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
745
746       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
747       // types, we have to deal with them whether we ask for Expansion or not.
748       // Setting Expand causes its own optimisation problems though, so leave
749       // them legal.
750       if (VT.getVectorElementType() == MVT::i1)
751         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
752
753       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
754       // split/scalarized right now.
755       if (VT.getVectorElementType() == MVT::f16)
756         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
757     }
758   }
759
760   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
761   // with -msoft-float, disable use of MMX as well.
762   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
763     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
764     // No operations on x86mmx supported, everything uses intrinsics.
765   }
766
767   // MMX-sized vectors (other than x86mmx) are expected to be expanded
768   // into smaller operations.
769   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
770     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
771     setOperationAction(ISD::AND,                MMXTy,      Expand);
772     setOperationAction(ISD::OR,                 MMXTy,      Expand);
773     setOperationAction(ISD::XOR,                MMXTy,      Expand);
774     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
775     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
776     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
777   }
778   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
779
780   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
781     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
782
783     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
784     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
785     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
786     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
787     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
788     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
789     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
790     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
791     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
792     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
793     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
794     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
795     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
796     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
797   }
798
799   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
800     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
801
802     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
803     // registers cannot be used even for integer operations.
804     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
805     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
806     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
807     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
808
809     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
810     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
811     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
812     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
813     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
814     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
815     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
816     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
817     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
818     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
819     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
820     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
821     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
822     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
823     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
824     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
825     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
826     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
830     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
831     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
832
833     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
834     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
835     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
836     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
837
838     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
839     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
840     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
841     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
842
843     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
844     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
845     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
846     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
847     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
848
849     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
850     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
851     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
852     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
853
854     setOperationAction(ISD::CTTZ,               MVT::v16i8, Custom);
855     setOperationAction(ISD::CTTZ,               MVT::v8i16, Custom);
856     setOperationAction(ISD::CTTZ,               MVT::v4i32, Custom);
857     // ISD::CTTZ v2i64 - scalarization is faster.
858     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v16i8, Custom);
859     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v8i16, Custom);
860     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v4i32, Custom);
861     // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
862
863     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
864     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
865       MVT VT = (MVT::SimpleValueType)i;
866       // Do not attempt to custom lower non-power-of-2 vectors
867       if (!isPowerOf2_32(VT.getVectorNumElements()))
868         continue;
869       // Do not attempt to custom lower non-128-bit vectors
870       if (!VT.is128BitVector())
871         continue;
872       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
873       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
874       setOperationAction(ISD::VSELECT,            VT, Custom);
875       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
876     }
877
878     // We support custom legalizing of sext and anyext loads for specific
879     // memory vector types which we can load as a scalar (or sequence of
880     // scalars) and extend in-register to a legal 128-bit vector type. For sext
881     // loads these must work with a single scalar load.
882     for (MVT VT : MVT::integer_vector_valuetypes()) {
883       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
884       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
885       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
886       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
887       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
888       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
889       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
890       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
891       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
892     }
893
894     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
895     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
896     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
897     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
898     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
899     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
900     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
901     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
902
903     if (Subtarget->is64Bit()) {
904       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
905       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
906     }
907
908     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
909     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
910       MVT VT = (MVT::SimpleValueType)i;
911
912       // Do not attempt to promote non-128-bit vectors
913       if (!VT.is128BitVector())
914         continue;
915
916       setOperationAction(ISD::AND,    VT, Promote);
917       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
918       setOperationAction(ISD::OR,     VT, Promote);
919       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
920       setOperationAction(ISD::XOR,    VT, Promote);
921       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
922       setOperationAction(ISD::LOAD,   VT, Promote);
923       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
924       setOperationAction(ISD::SELECT, VT, Promote);
925       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
926     }
927
928     // Custom lower v2i64 and v2f64 selects.
929     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
930     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
931     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
932     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
933
934     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
935     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
936
937     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
938
939     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
940     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
941     // As there is no 64-bit GPR available, we need build a special custom
942     // sequence to convert from v2i32 to v2f32.
943     if (!Subtarget->is64Bit())
944       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
945
946     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
947     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
948
949     for (MVT VT : MVT::fp_vector_valuetypes())
950       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
951
952     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
953     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
954     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
955   }
956
957   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
958     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
959       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
960       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
961       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
962       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
963       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
964     }
965
966     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
967     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
968     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
969     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
970     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
971     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
972     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
973     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
974
975     // FIXME: Do we need to handle scalar-to-vector here?
976     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
977
978     // We directly match byte blends in the backend as they match the VSELECT
979     // condition form.
980     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
981
982     // SSE41 brings specific instructions for doing vector sign extend even in
983     // cases where we don't have SRA.
984     for (MVT VT : MVT::integer_vector_valuetypes()) {
985       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
986       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
987       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
988     }
989
990     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
991     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
992     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
993     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
994     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
995     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
996     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
997
998     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
999     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
1000     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
1001     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1002     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1003     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1004
1005     // i8 and i16 vectors are custom because the source register and source
1006     // source memory operand types are not the same width.  f32 vectors are
1007     // custom since the immediate controlling the insert encodes additional
1008     // information.
1009     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1010     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1011     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1012     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1013
1014     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1015     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1016     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1017     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1018
1019     // FIXME: these should be Legal, but that's only for the case where
1020     // the index is constant.  For now custom expand to deal with that.
1021     if (Subtarget->is64Bit()) {
1022       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1023       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1024     }
1025   }
1026
1027   if (Subtarget->hasSSE2()) {
1028     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1029     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1030     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1031
1032     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1033     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1034
1035     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1036     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1037
1038     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1039     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1040
1041     // In the customized shift lowering, the legal cases in AVX2 will be
1042     // recognized.
1043     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1044     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1045
1046     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1047     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1048
1049     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1050     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1051   }
1052
1053   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1054     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1055     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1056     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1057     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1058     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1059     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1060
1061     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1062     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1063     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1064
1065     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1066     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1067     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1068     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1069     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1070     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1071     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1072     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1073     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1074     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1075     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1076     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1077
1078     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1079     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1080     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1081     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1082     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1083     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1084     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1085     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1086     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1087     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1088     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1089     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1090
1091     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1092     // even though v8i16 is a legal type.
1093     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1094     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1095     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1096
1097     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1098     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1099     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1100
1101     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1102     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1103
1104     for (MVT VT : MVT::fp_vector_valuetypes())
1105       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1106
1107     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1108     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1109
1110     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1111     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1112
1113     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1114     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1115
1116     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1117     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1118     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1119     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1120
1121     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1122     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1123     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1124
1125     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1126     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1127     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1128     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1129     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1130     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1131     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1132     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1133     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1134     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1135     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1136     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1137
1138     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1139     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1140     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1141     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1142
1143     setOperationAction(ISD::CTTZ,              MVT::v32i8, Custom);
1144     setOperationAction(ISD::CTTZ,              MVT::v16i16, Custom);
1145     setOperationAction(ISD::CTTZ,              MVT::v8i32, Custom);
1146     setOperationAction(ISD::CTTZ,              MVT::v4i64, Custom);
1147     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v32i8, Custom);
1148     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v16i16, Custom);
1149     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v8i32, Custom);
1150     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v4i64, Custom);
1151
1152     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1153       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1154       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1155       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1156       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1157       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1158       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1159     }
1160
1161     if (Subtarget->hasInt256()) {
1162       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1163       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1164       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1165       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1166
1167       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1168       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1169       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1170       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1171
1172       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1173       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1174       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1175       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1176
1177       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1178       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1179       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1180       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1181
1182       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1183       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1184       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1185       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1186       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1187       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1188       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1189       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1190       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1191       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1192       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1193       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1194
1195       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1196       // when we have a 256bit-wide blend with immediate.
1197       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1198
1199       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1200       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1201       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1202       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1203       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1204       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1205       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1206
1207       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1208       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1209       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1210       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1211       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1212       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1213     } else {
1214       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1215       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1216       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1217       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1218
1219       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1220       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1221       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1222       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1223
1224       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1225       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1226       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1227       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1228
1229       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1230       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1231       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1232       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1233       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1234       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1235       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1236       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1237       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1238       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1239       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1240       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1241     }
1242
1243     // In the customized shift lowering, the legal cases in AVX2 will be
1244     // recognized.
1245     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1246     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1247
1248     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1249     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1250
1251     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1252     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1253
1254     // Custom lower several nodes for 256-bit types.
1255     for (MVT VT : MVT::vector_valuetypes()) {
1256       if (VT.getScalarSizeInBits() >= 32) {
1257         setOperationAction(ISD::MLOAD,  VT, Legal);
1258         setOperationAction(ISD::MSTORE, VT, Legal);
1259       }
1260       // Extract subvector is special because the value type
1261       // (result) is 128-bit but the source is 256-bit wide.
1262       if (VT.is128BitVector()) {
1263         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1264       }
1265       // Do not attempt to custom lower other non-256-bit vectors
1266       if (!VT.is256BitVector())
1267         continue;
1268
1269       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1270       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1271       setOperationAction(ISD::VSELECT,            VT, Custom);
1272       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1273       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1274       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1275       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1276       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1277     }
1278
1279     if (Subtarget->hasInt256())
1280       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1281
1282     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1283     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1284       MVT VT = (MVT::SimpleValueType)i;
1285
1286       // Do not attempt to promote non-256-bit vectors
1287       if (!VT.is256BitVector())
1288         continue;
1289
1290       setOperationAction(ISD::AND,    VT, Promote);
1291       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1292       setOperationAction(ISD::OR,     VT, Promote);
1293       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1294       setOperationAction(ISD::XOR,    VT, Promote);
1295       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1296       setOperationAction(ISD::LOAD,   VT, Promote);
1297       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1298       setOperationAction(ISD::SELECT, VT, Promote);
1299       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1300     }
1301   }
1302
1303   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1304     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1305     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1306     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1307     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1308
1309     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1310     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1311     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1312
1313     for (MVT VT : MVT::fp_vector_valuetypes())
1314       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1315
1316     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1317     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1318     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1319     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1320     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1321     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1322     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1323     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1324     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1325     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1326     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1327     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1328
1329     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1330     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1331     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1332     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1333     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1334     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1335     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1336     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1337     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1338     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1339     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1340     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1341     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1342
1343     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1344     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1345     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1346     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1347     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1348     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1349
1350     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1351     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1352     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1353     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1354     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1355     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1356     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1357     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1358
1359     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1360     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1361     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1362     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1363     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1364     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1365     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1366     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1367     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1368     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1369     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1370     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1371     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1372     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1373     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1374     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1375
1376     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1377     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1378     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1379     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1380     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1381     if (Subtarget->hasVLX()){
1382       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1383       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1384       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1385       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1386       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1387
1388       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1389       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1390       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1391       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1392       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1393     }
1394     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1395     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1396     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1397     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i1,  Custom);
1398     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v16i1, Custom);
1399     if (Subtarget->hasDQI()) {
1400       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1401       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1402
1403       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1404       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1405       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1406       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1407       if (Subtarget->hasVLX()) {
1408         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1409         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1410         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1411         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1412         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1413         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1414         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1415         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1416       }
1417     }
1418     if (Subtarget->hasVLX()) {
1419       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1420       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1421       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1422       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1423       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1424       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1425       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1426       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1427     }
1428     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1429     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1430     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1431     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1432     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1433     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1434     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1436     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1437     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1438     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1439     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1440     if (Subtarget->hasDQI()) {
1441       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1442       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1443     }
1444     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1445     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1446     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1447     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1448     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1449     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1450     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1451     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1452     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1453     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1454
1455     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1456     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1457     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1458     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1459     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1460
1461     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1462     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1463
1464     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1465
1466     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1467     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1468     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1469     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1470     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1471     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1472     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1473     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1474     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1475     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1476     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1477
1478     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1479     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1480     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1481     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1482     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1483     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1484     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1485     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1486
1487     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1488     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1489
1490     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1491     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1492
1493     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1494
1495     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1496     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1497
1498     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1499     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1500
1501     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1502     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1503
1504     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1505     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1506     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1507     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1508     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1509     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1510
1511     if (Subtarget->hasCDI()) {
1512       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1513       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1514       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64, Legal);
1515       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Legal);
1516
1517       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i64, Custom);
1518       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v16i32, Custom);
1519     }
1520     if (Subtarget->hasVLX() && Subtarget->hasCDI()) {
1521       setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1522       setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1523       setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1524       setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1525       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Legal);
1526       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Legal);
1527       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Legal);
1528       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Legal);
1529
1530       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1531       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1532       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1533       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1534     }
1535     if (Subtarget->hasDQI()) {
1536       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1537       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1538       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1539     }
1540     // Custom lower several nodes.
1541     for (MVT VT : MVT::vector_valuetypes()) {
1542       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1543       if (EltSize == 1) {
1544         setOperationAction(ISD::AND, VT, Legal);
1545         setOperationAction(ISD::OR,  VT, Legal);
1546         setOperationAction(ISD::XOR,  VT, Legal);
1547       }
1548       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1549         setOperationAction(ISD::MGATHER,  VT, Custom);
1550         setOperationAction(ISD::MSCATTER, VT, Custom);
1551       }
1552       // Extract subvector is special because the value type
1553       // (result) is 256/128-bit but the source is 512-bit wide.
1554       if (VT.is128BitVector() || VT.is256BitVector()) {
1555         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1556       }
1557       if (VT.getVectorElementType() == MVT::i1)
1558         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1559
1560       // Do not attempt to custom lower other non-512-bit vectors
1561       if (!VT.is512BitVector())
1562         continue;
1563
1564       if (EltSize >= 32) {
1565         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1566         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1567         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1568         setOperationAction(ISD::VSELECT,             VT, Legal);
1569         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1570         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1571         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1572         setOperationAction(ISD::MLOAD,               VT, Legal);
1573         setOperationAction(ISD::MSTORE,              VT, Legal);
1574       }
1575     }
1576     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1577       MVT VT = (MVT::SimpleValueType)i;
1578
1579       // Do not attempt to promote non-512-bit vectors.
1580       if (!VT.is512BitVector())
1581         continue;
1582
1583       setOperationAction(ISD::SELECT, VT, Promote);
1584       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1585     }
1586   }// has  AVX-512
1587
1588   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1589     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1590     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1591
1592     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1593     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1594
1595     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1596     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1597     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1598     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1599     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1600     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1601     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1602     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1603     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1604     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1605     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1606     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Legal);
1607     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Legal);
1608     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1609     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1610     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i16, Custom);
1611     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i8, Custom);
1612     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1613     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1614     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1615     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1616     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1617     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1618     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1619     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1620     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1621     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1622     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1623     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1624     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1625     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i16, Custom);
1626     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i8, Custom);
1627     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1628     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1629     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1630     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1631     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1632     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i1, Custom);
1633     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i1, Custom);
1634
1635     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1636     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1637     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1638     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1639     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1640     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1641     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1642     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1643
1644     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1645     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1646     if (Subtarget->hasVLX())
1647       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1648
1649     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1650       const MVT VT = (MVT::SimpleValueType)i;
1651
1652       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1653
1654       // Do not attempt to promote non-512-bit vectors.
1655       if (!VT.is512BitVector())
1656         continue;
1657
1658       if (EltSize < 32) {
1659         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1660         setOperationAction(ISD::VSELECT,             VT, Legal);
1661       }
1662     }
1663   }
1664
1665   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1666     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1667     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1668
1669     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1670     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1671     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1672     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1673     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1674     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1675     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1676     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1677     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1678     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1679     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i1, Custom);
1680     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i1, Custom);
1681
1682     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1683     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1684     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1685     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1686     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1687     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1688     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1689     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1690
1691     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1692     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1693     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1694     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1695     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1696     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1697     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1698     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1699   }
1700
1701   // We want to custom lower some of our intrinsics.
1702   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1703   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1704   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1705   if (!Subtarget->is64Bit())
1706     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1707
1708   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1709   // handle type legalization for these operations here.
1710   //
1711   // FIXME: We really should do custom legalization for addition and
1712   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1713   // than generic legalization for 64-bit multiplication-with-overflow, though.
1714   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1715     // Add/Sub/Mul with overflow operations are custom lowered.
1716     MVT VT = IntVTs[i];
1717     setOperationAction(ISD::SADDO, VT, Custom);
1718     setOperationAction(ISD::UADDO, VT, Custom);
1719     setOperationAction(ISD::SSUBO, VT, Custom);
1720     setOperationAction(ISD::USUBO, VT, Custom);
1721     setOperationAction(ISD::SMULO, VT, Custom);
1722     setOperationAction(ISD::UMULO, VT, Custom);
1723   }
1724
1725   if (!Subtarget->is64Bit()) {
1726     // These libcalls are not available in 32-bit.
1727     setLibcallName(RTLIB::SHL_I128, nullptr);
1728     setLibcallName(RTLIB::SRL_I128, nullptr);
1729     setLibcallName(RTLIB::SRA_I128, nullptr);
1730   }
1731
1732   // Combine sin / cos into one node or libcall if possible.
1733   if (Subtarget->hasSinCos()) {
1734     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1735     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1736     if (Subtarget->isTargetDarwin()) {
1737       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1738       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1739       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1740       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1741     }
1742   }
1743
1744   if (Subtarget->isTargetWin64()) {
1745     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1746     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1747     setOperationAction(ISD::SREM, MVT::i128, Custom);
1748     setOperationAction(ISD::UREM, MVT::i128, Custom);
1749     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1750     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1751   }
1752
1753   // We have target-specific dag combine patterns for the following nodes:
1754   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1755   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1756   setTargetDAGCombine(ISD::BITCAST);
1757   setTargetDAGCombine(ISD::VSELECT);
1758   setTargetDAGCombine(ISD::SELECT);
1759   setTargetDAGCombine(ISD::SHL);
1760   setTargetDAGCombine(ISD::SRA);
1761   setTargetDAGCombine(ISD::SRL);
1762   setTargetDAGCombine(ISD::OR);
1763   setTargetDAGCombine(ISD::AND);
1764   setTargetDAGCombine(ISD::ADD);
1765   setTargetDAGCombine(ISD::FADD);
1766   setTargetDAGCombine(ISD::FSUB);
1767   setTargetDAGCombine(ISD::FMA);
1768   setTargetDAGCombine(ISD::SUB);
1769   setTargetDAGCombine(ISD::LOAD);
1770   setTargetDAGCombine(ISD::MLOAD);
1771   setTargetDAGCombine(ISD::STORE);
1772   setTargetDAGCombine(ISD::MSTORE);
1773   setTargetDAGCombine(ISD::ZERO_EXTEND);
1774   setTargetDAGCombine(ISD::ANY_EXTEND);
1775   setTargetDAGCombine(ISD::SIGN_EXTEND);
1776   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1777   setTargetDAGCombine(ISD::SINT_TO_FP);
1778   setTargetDAGCombine(ISD::UINT_TO_FP);
1779   setTargetDAGCombine(ISD::SETCC);
1780   setTargetDAGCombine(ISD::BUILD_VECTOR);
1781   setTargetDAGCombine(ISD::MUL);
1782   setTargetDAGCombine(ISD::XOR);
1783
1784   computeRegisterProperties(Subtarget->getRegisterInfo());
1785
1786   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1787   MaxStoresPerMemsetOptSize = 8;
1788   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1789   MaxStoresPerMemcpyOptSize = 4;
1790   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1791   MaxStoresPerMemmoveOptSize = 4;
1792   setPrefLoopAlignment(4); // 2^4 bytes.
1793
1794   // A predictable cmov does not hurt on an in-order CPU.
1795   // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1796   PredictableSelectIsExpensive = !Subtarget->isAtom();
1797   EnableExtLdPromotion = true;
1798   setPrefFunctionAlignment(4); // 2^4 bytes.
1799
1800   verifyIntrinsicTables();
1801 }
1802
1803 // This has so far only been implemented for 64-bit MachO.
1804 bool X86TargetLowering::useLoadStackGuardNode() const {
1805   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1806 }
1807
1808 TargetLoweringBase::LegalizeTypeAction
1809 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1810   if (ExperimentalVectorWideningLegalization &&
1811       VT.getVectorNumElements() != 1 &&
1812       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1813     return TypeWidenVector;
1814
1815   return TargetLoweringBase::getPreferredVectorAction(VT);
1816 }
1817
1818 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1819                                           EVT VT) const {
1820   if (!VT.isVector())
1821     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1822
1823   const unsigned NumElts = VT.getVectorNumElements();
1824   const EVT EltVT = VT.getVectorElementType();
1825   if (VT.is512BitVector()) {
1826     if (Subtarget->hasAVX512())
1827       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1828           EltVT == MVT::f32 || EltVT == MVT::f64)
1829         switch(NumElts) {
1830         case  8: return MVT::v8i1;
1831         case 16: return MVT::v16i1;
1832       }
1833     if (Subtarget->hasBWI())
1834       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1835         switch(NumElts) {
1836         case 32: return MVT::v32i1;
1837         case 64: return MVT::v64i1;
1838       }
1839   }
1840
1841   if (VT.is256BitVector() || VT.is128BitVector()) {
1842     if (Subtarget->hasVLX())
1843       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1844           EltVT == MVT::f32 || EltVT == MVT::f64)
1845         switch(NumElts) {
1846         case 2: return MVT::v2i1;
1847         case 4: return MVT::v4i1;
1848         case 8: return MVT::v8i1;
1849       }
1850     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1851       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1852         switch(NumElts) {
1853         case  8: return MVT::v8i1;
1854         case 16: return MVT::v16i1;
1855         case 32: return MVT::v32i1;
1856       }
1857   }
1858
1859   return VT.changeVectorElementTypeToInteger();
1860 }
1861
1862 /// Helper for getByValTypeAlignment to determine
1863 /// the desired ByVal argument alignment.
1864 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1865   if (MaxAlign == 16)
1866     return;
1867   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1868     if (VTy->getBitWidth() == 128)
1869       MaxAlign = 16;
1870   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1871     unsigned EltAlign = 0;
1872     getMaxByValAlign(ATy->getElementType(), EltAlign);
1873     if (EltAlign > MaxAlign)
1874       MaxAlign = EltAlign;
1875   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1876     for (auto *EltTy : STy->elements()) {
1877       unsigned EltAlign = 0;
1878       getMaxByValAlign(EltTy, EltAlign);
1879       if (EltAlign > MaxAlign)
1880         MaxAlign = EltAlign;
1881       if (MaxAlign == 16)
1882         break;
1883     }
1884   }
1885 }
1886
1887 /// Return the desired alignment for ByVal aggregate
1888 /// function arguments in the caller parameter area. For X86, aggregates
1889 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1890 /// are at 4-byte boundaries.
1891 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1892                                                   const DataLayout &DL) const {
1893   if (Subtarget->is64Bit()) {
1894     // Max of 8 and alignment of type.
1895     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1896     if (TyAlign > 8)
1897       return TyAlign;
1898     return 8;
1899   }
1900
1901   unsigned Align = 4;
1902   if (Subtarget->hasSSE1())
1903     getMaxByValAlign(Ty, Align);
1904   return Align;
1905 }
1906
1907 /// Returns the target specific optimal type for load
1908 /// and store operations as a result of memset, memcpy, and memmove
1909 /// lowering. If DstAlign is zero that means it's safe to destination
1910 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1911 /// means there isn't a need to check it against alignment requirement,
1912 /// probably because the source does not need to be loaded. If 'IsMemset' is
1913 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1914 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1915 /// source is constant so it does not need to be loaded.
1916 /// It returns EVT::Other if the type should be determined using generic
1917 /// target-independent logic.
1918 EVT
1919 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1920                                        unsigned DstAlign, unsigned SrcAlign,
1921                                        bool IsMemset, bool ZeroMemset,
1922                                        bool MemcpyStrSrc,
1923                                        MachineFunction &MF) const {
1924   const Function *F = MF.getFunction();
1925   if ((!IsMemset || ZeroMemset) &&
1926       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1927     if (Size >= 16 &&
1928         (!Subtarget->isUnalignedMem16Slow() ||
1929          ((DstAlign == 0 || DstAlign >= 16) &&
1930           (SrcAlign == 0 || SrcAlign >= 16)))) {
1931       if (Size >= 32) {
1932         // FIXME: Check if unaligned 32-byte accesses are slow.
1933         if (Subtarget->hasInt256())
1934           return MVT::v8i32;
1935         if (Subtarget->hasFp256())
1936           return MVT::v8f32;
1937       }
1938       if (Subtarget->hasSSE2())
1939         return MVT::v4i32;
1940       if (Subtarget->hasSSE1())
1941         return MVT::v4f32;
1942     } else if (!MemcpyStrSrc && Size >= 8 &&
1943                !Subtarget->is64Bit() &&
1944                Subtarget->hasSSE2()) {
1945       // Do not use f64 to lower memcpy if source is string constant. It's
1946       // better to use i32 to avoid the loads.
1947       return MVT::f64;
1948     }
1949   }
1950   // This is a compromise. If we reach here, unaligned accesses may be slow on
1951   // this target. However, creating smaller, aligned accesses could be even
1952   // slower and would certainly be a lot more code.
1953   if (Subtarget->is64Bit() && Size >= 8)
1954     return MVT::i64;
1955   return MVT::i32;
1956 }
1957
1958 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1959   if (VT == MVT::f32)
1960     return X86ScalarSSEf32;
1961   else if (VT == MVT::f64)
1962     return X86ScalarSSEf64;
1963   return true;
1964 }
1965
1966 bool
1967 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1968                                                   unsigned,
1969                                                   unsigned,
1970                                                   bool *Fast) const {
1971   if (Fast) {
1972     switch (VT.getSizeInBits()) {
1973     default:
1974       // 8-byte and under are always assumed to be fast.
1975       *Fast = true;
1976       break;
1977     case 128:
1978       *Fast = !Subtarget->isUnalignedMem16Slow();
1979       break;
1980     case 256:
1981       *Fast = !Subtarget->isUnalignedMem32Slow();
1982       break;
1983     // TODO: What about AVX-512 (512-bit) accesses?
1984     }
1985   }
1986   // Misaligned accesses of any size are always allowed.
1987   return true;
1988 }
1989
1990 /// Return the entry encoding for a jump table in the
1991 /// current function.  The returned value is a member of the
1992 /// MachineJumpTableInfo::JTEntryKind enum.
1993 unsigned X86TargetLowering::getJumpTableEncoding() const {
1994   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1995   // symbol.
1996   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1997       Subtarget->isPICStyleGOT())
1998     return MachineJumpTableInfo::EK_Custom32;
1999
2000   // Otherwise, use the normal jump table encoding heuristics.
2001   return TargetLowering::getJumpTableEncoding();
2002 }
2003
2004 bool X86TargetLowering::useSoftFloat() const {
2005   return Subtarget->useSoftFloat();
2006 }
2007
2008 const MCExpr *
2009 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2010                                              const MachineBasicBlock *MBB,
2011                                              unsigned uid,MCContext &Ctx) const{
2012   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2013          Subtarget->isPICStyleGOT());
2014   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2015   // entries.
2016   return MCSymbolRefExpr::create(MBB->getSymbol(),
2017                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2018 }
2019
2020 /// Returns relocation base for the given PIC jumptable.
2021 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2022                                                     SelectionDAG &DAG) const {
2023   if (!Subtarget->is64Bit())
2024     // This doesn't have SDLoc associated with it, but is not really the
2025     // same as a Register.
2026     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2027                        getPointerTy(DAG.getDataLayout()));
2028   return Table;
2029 }
2030
2031 /// This returns the relocation base for the given PIC jumptable,
2032 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2033 const MCExpr *X86TargetLowering::
2034 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2035                              MCContext &Ctx) const {
2036   // X86-64 uses RIP relative addressing based on the jump table label.
2037   if (Subtarget->isPICStyleRIPRel())
2038     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2039
2040   // Otherwise, the reference is relative to the PIC base.
2041   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2042 }
2043
2044 std::pair<const TargetRegisterClass *, uint8_t>
2045 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2046                                            MVT VT) const {
2047   const TargetRegisterClass *RRC = nullptr;
2048   uint8_t Cost = 1;
2049   switch (VT.SimpleTy) {
2050   default:
2051     return TargetLowering::findRepresentativeClass(TRI, VT);
2052   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2053     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2054     break;
2055   case MVT::x86mmx:
2056     RRC = &X86::VR64RegClass;
2057     break;
2058   case MVT::f32: case MVT::f64:
2059   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2060   case MVT::v4f32: case MVT::v2f64:
2061   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2062   case MVT::v4f64:
2063     RRC = &X86::VR128RegClass;
2064     break;
2065   }
2066   return std::make_pair(RRC, Cost);
2067 }
2068
2069 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2070                                                unsigned &Offset) const {
2071   if (!Subtarget->isTargetLinux())
2072     return false;
2073
2074   if (Subtarget->is64Bit()) {
2075     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2076     Offset = 0x28;
2077     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2078       AddressSpace = 256;
2079     else
2080       AddressSpace = 257;
2081   } else {
2082     // %gs:0x14 on i386
2083     Offset = 0x14;
2084     AddressSpace = 256;
2085   }
2086   return true;
2087 }
2088
2089 /// Android provides a fixed TLS slot for the SafeStack pointer.
2090 /// See the definition of TLS_SLOT_SAFESTACK in
2091 /// https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2092 bool X86TargetLowering::getSafeStackPointerLocation(unsigned &AddressSpace,
2093                                                     unsigned &Offset) const {
2094   if (!Subtarget->isTargetAndroid())
2095     return false;
2096
2097   if (Subtarget->is64Bit()) {
2098     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2099     Offset = 0x48;
2100     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2101       AddressSpace = 256;
2102     else
2103       AddressSpace = 257;
2104   } else {
2105     // %gs:0x24 on i386
2106     Offset = 0x24;
2107     AddressSpace = 256;
2108   }
2109   return true;
2110 }
2111
2112 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2113                                             unsigned DestAS) const {
2114   assert(SrcAS != DestAS && "Expected different address spaces!");
2115
2116   return SrcAS < 256 && DestAS < 256;
2117 }
2118
2119 //===----------------------------------------------------------------------===//
2120 //               Return Value Calling Convention Implementation
2121 //===----------------------------------------------------------------------===//
2122
2123 #include "X86GenCallingConv.inc"
2124
2125 bool X86TargetLowering::CanLowerReturn(
2126     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2127     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2128   SmallVector<CCValAssign, 16> RVLocs;
2129   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2130   return CCInfo.CheckReturn(Outs, RetCC_X86);
2131 }
2132
2133 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2134   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2135   return ScratchRegs;
2136 }
2137
2138 SDValue
2139 X86TargetLowering::LowerReturn(SDValue Chain,
2140                                CallingConv::ID CallConv, bool isVarArg,
2141                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2142                                const SmallVectorImpl<SDValue> &OutVals,
2143                                SDLoc dl, SelectionDAG &DAG) const {
2144   MachineFunction &MF = DAG.getMachineFunction();
2145   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2146
2147   SmallVector<CCValAssign, 16> RVLocs;
2148   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2149   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2150
2151   SDValue Flag;
2152   SmallVector<SDValue, 6> RetOps;
2153   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2154   // Operand #1 = Bytes To Pop
2155   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2156                    MVT::i16));
2157
2158   // Copy the result values into the output registers.
2159   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2160     CCValAssign &VA = RVLocs[i];
2161     assert(VA.isRegLoc() && "Can only return in registers!");
2162     SDValue ValToCopy = OutVals[i];
2163     EVT ValVT = ValToCopy.getValueType();
2164
2165     // Promote values to the appropriate types.
2166     if (VA.getLocInfo() == CCValAssign::SExt)
2167       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2168     else if (VA.getLocInfo() == CCValAssign::ZExt)
2169       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2170     else if (VA.getLocInfo() == CCValAssign::AExt) {
2171       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2172         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2173       else
2174         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2175     }
2176     else if (VA.getLocInfo() == CCValAssign::BCvt)
2177       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2178
2179     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2180            "Unexpected FP-extend for return value.");
2181
2182     // If this is x86-64, and we disabled SSE, we can't return FP values,
2183     // or SSE or MMX vectors.
2184     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2185          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2186           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2187       report_fatal_error("SSE register return with SSE disabled");
2188     }
2189     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2190     // llvm-gcc has never done it right and no one has noticed, so this
2191     // should be OK for now.
2192     if (ValVT == MVT::f64 &&
2193         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2194       report_fatal_error("SSE2 register return with SSE2 disabled");
2195
2196     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2197     // the RET instruction and handled by the FP Stackifier.
2198     if (VA.getLocReg() == X86::FP0 ||
2199         VA.getLocReg() == X86::FP1) {
2200       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2201       // change the value to the FP stack register class.
2202       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2203         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2204       RetOps.push_back(ValToCopy);
2205       // Don't emit a copytoreg.
2206       continue;
2207     }
2208
2209     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2210     // which is returned in RAX / RDX.
2211     if (Subtarget->is64Bit()) {
2212       if (ValVT == MVT::x86mmx) {
2213         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2214           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2215           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2216                                   ValToCopy);
2217           // If we don't have SSE2 available, convert to v4f32 so the generated
2218           // register is legal.
2219           if (!Subtarget->hasSSE2())
2220             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2221         }
2222       }
2223     }
2224
2225     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2226     Flag = Chain.getValue(1);
2227     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2228   }
2229
2230   // All x86 ABIs require that for returning structs by value we copy
2231   // the sret argument into %rax/%eax (depending on ABI) for the return.
2232   // We saved the argument into a virtual register in the entry block,
2233   // so now we copy the value out and into %rax/%eax.
2234   //
2235   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2236   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2237   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2238   // either case FuncInfo->setSRetReturnReg() will have been called.
2239   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2240     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2241                                      getPointerTy(MF.getDataLayout()));
2242
2243     unsigned RetValReg
2244         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2245           X86::RAX : X86::EAX;
2246     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2247     Flag = Chain.getValue(1);
2248
2249     // RAX/EAX now acts like a return value.
2250     RetOps.push_back(
2251         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2252   }
2253
2254   RetOps[0] = Chain;  // Update chain.
2255
2256   // Add the flag if we have it.
2257   if (Flag.getNode())
2258     RetOps.push_back(Flag);
2259
2260   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2261 }
2262
2263 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2264   if (N->getNumValues() != 1)
2265     return false;
2266   if (!N->hasNUsesOfValue(1, 0))
2267     return false;
2268
2269   SDValue TCChain = Chain;
2270   SDNode *Copy = *N->use_begin();
2271   if (Copy->getOpcode() == ISD::CopyToReg) {
2272     // If the copy has a glue operand, we conservatively assume it isn't safe to
2273     // perform a tail call.
2274     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2275       return false;
2276     TCChain = Copy->getOperand(0);
2277   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2278     return false;
2279
2280   bool HasRet = false;
2281   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2282        UI != UE; ++UI) {
2283     if (UI->getOpcode() != X86ISD::RET_FLAG)
2284       return false;
2285     // If we are returning more than one value, we can definitely
2286     // not make a tail call see PR19530
2287     if (UI->getNumOperands() > 4)
2288       return false;
2289     if (UI->getNumOperands() == 4 &&
2290         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2291       return false;
2292     HasRet = true;
2293   }
2294
2295   if (!HasRet)
2296     return false;
2297
2298   Chain = TCChain;
2299   return true;
2300 }
2301
2302 EVT
2303 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2304                                             ISD::NodeType ExtendKind) const {
2305   MVT ReturnMVT;
2306   // TODO: Is this also valid on 32-bit?
2307   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2308     ReturnMVT = MVT::i8;
2309   else
2310     ReturnMVT = MVT::i32;
2311
2312   EVT MinVT = getRegisterType(Context, ReturnMVT);
2313   return VT.bitsLT(MinVT) ? MinVT : VT;
2314 }
2315
2316 /// Lower the result values of a call into the
2317 /// appropriate copies out of appropriate physical registers.
2318 ///
2319 SDValue
2320 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2321                                    CallingConv::ID CallConv, bool isVarArg,
2322                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2323                                    SDLoc dl, SelectionDAG &DAG,
2324                                    SmallVectorImpl<SDValue> &InVals) const {
2325
2326   // Assign locations to each value returned by this call.
2327   SmallVector<CCValAssign, 16> RVLocs;
2328   bool Is64Bit = Subtarget->is64Bit();
2329   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2330                  *DAG.getContext());
2331   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2332
2333   // Copy all of the result registers out of their specified physreg.
2334   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2335     CCValAssign &VA = RVLocs[i];
2336     EVT CopyVT = VA.getLocVT();
2337
2338     // If this is x86-64, and we disabled SSE, we can't return FP values
2339     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2340         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2341       report_fatal_error("SSE register return with SSE disabled");
2342     }
2343
2344     // If we prefer to use the value in xmm registers, copy it out as f80 and
2345     // use a truncate to move it from fp stack reg to xmm reg.
2346     bool RoundAfterCopy = false;
2347     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2348         isScalarFPTypeInSSEReg(VA.getValVT())) {
2349       CopyVT = MVT::f80;
2350       RoundAfterCopy = (CopyVT != VA.getLocVT());
2351     }
2352
2353     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2354                                CopyVT, InFlag).getValue(1);
2355     SDValue Val = Chain.getValue(0);
2356
2357     if (RoundAfterCopy)
2358       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2359                         // This truncation won't change the value.
2360                         DAG.getIntPtrConstant(1, dl));
2361
2362     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2363       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2364
2365     InFlag = Chain.getValue(2);
2366     InVals.push_back(Val);
2367   }
2368
2369   return Chain;
2370 }
2371
2372 //===----------------------------------------------------------------------===//
2373 //                C & StdCall & Fast Calling Convention implementation
2374 //===----------------------------------------------------------------------===//
2375 //  StdCall calling convention seems to be standard for many Windows' API
2376 //  routines and around. It differs from C calling convention just a little:
2377 //  callee should clean up the stack, not caller. Symbols should be also
2378 //  decorated in some fancy way :) It doesn't support any vector arguments.
2379 //  For info on fast calling convention see Fast Calling Convention (tail call)
2380 //  implementation LowerX86_32FastCCCallTo.
2381
2382 /// CallIsStructReturn - Determines whether a call uses struct return
2383 /// semantics.
2384 enum StructReturnType {
2385   NotStructReturn,
2386   RegStructReturn,
2387   StackStructReturn
2388 };
2389 static StructReturnType
2390 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2391   if (Outs.empty())
2392     return NotStructReturn;
2393
2394   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2395   if (!Flags.isSRet())
2396     return NotStructReturn;
2397   if (Flags.isInReg())
2398     return RegStructReturn;
2399   return StackStructReturn;
2400 }
2401
2402 /// Determines whether a function uses struct return semantics.
2403 static StructReturnType
2404 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2405   if (Ins.empty())
2406     return NotStructReturn;
2407
2408   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2409   if (!Flags.isSRet())
2410     return NotStructReturn;
2411   if (Flags.isInReg())
2412     return RegStructReturn;
2413   return StackStructReturn;
2414 }
2415
2416 /// Make a copy of an aggregate at address specified by "Src" to address
2417 /// "Dst" with size and alignment information specified by the specific
2418 /// parameter attribute. The copy will be passed as a byval function parameter.
2419 static SDValue
2420 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2421                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2422                           SDLoc dl) {
2423   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2424
2425   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2426                        /*isVolatile*/false, /*AlwaysInline=*/true,
2427                        /*isTailCall*/false,
2428                        MachinePointerInfo(), MachinePointerInfo());
2429 }
2430
2431 /// Return true if the calling convention is one that
2432 /// supports tail call optimization.
2433 static bool IsTailCallConvention(CallingConv::ID CC) {
2434   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2435           CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2436 }
2437
2438 /// \brief Return true if the calling convention is a C calling convention.
2439 static bool IsCCallConvention(CallingConv::ID CC) {
2440   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2441           CC == CallingConv::X86_64_SysV);
2442 }
2443
2444 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2445   auto Attr =
2446       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2447   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2448     return false;
2449
2450   CallSite CS(CI);
2451   CallingConv::ID CalleeCC = CS.getCallingConv();
2452   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2453     return false;
2454
2455   return true;
2456 }
2457
2458 /// Return true if the function is being made into
2459 /// a tailcall target by changing its ABI.
2460 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2461                                    bool GuaranteedTailCallOpt) {
2462   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2463 }
2464
2465 SDValue
2466 X86TargetLowering::LowerMemArgument(SDValue Chain,
2467                                     CallingConv::ID CallConv,
2468                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2469                                     SDLoc dl, SelectionDAG &DAG,
2470                                     const CCValAssign &VA,
2471                                     MachineFrameInfo *MFI,
2472                                     unsigned i) const {
2473   // Create the nodes corresponding to a load from this parameter slot.
2474   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2475   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2476       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2477   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2478   EVT ValVT;
2479
2480   // If value is passed by pointer we have address passed instead of the value
2481   // itself.
2482   bool ExtendedInMem = VA.isExtInLoc() &&
2483     VA.getValVT().getScalarType() == MVT::i1;
2484
2485   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2486     ValVT = VA.getLocVT();
2487   else
2488     ValVT = VA.getValVT();
2489
2490   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2491   // changed with more analysis.
2492   // In case of tail call optimization mark all arguments mutable. Since they
2493   // could be overwritten by lowering of arguments in case of a tail call.
2494   if (Flags.isByVal()) {
2495     unsigned Bytes = Flags.getByValSize();
2496     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2497     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2498     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2499   } else {
2500     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2501                                     VA.getLocMemOffset(), isImmutable);
2502     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2503     SDValue Val = DAG.getLoad(
2504         ValVT, dl, Chain, FIN,
2505         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2506         false, false, 0);
2507     return ExtendedInMem ?
2508       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2509   }
2510 }
2511
2512 // FIXME: Get this from tablegen.
2513 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2514                                                 const X86Subtarget *Subtarget) {
2515   assert(Subtarget->is64Bit());
2516
2517   if (Subtarget->isCallingConvWin64(CallConv)) {
2518     static const MCPhysReg GPR64ArgRegsWin64[] = {
2519       X86::RCX, X86::RDX, X86::R8,  X86::R9
2520     };
2521     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2522   }
2523
2524   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2525     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2526   };
2527   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2528 }
2529
2530 // FIXME: Get this from tablegen.
2531 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2532                                                 CallingConv::ID CallConv,
2533                                                 const X86Subtarget *Subtarget) {
2534   assert(Subtarget->is64Bit());
2535   if (Subtarget->isCallingConvWin64(CallConv)) {
2536     // The XMM registers which might contain var arg parameters are shadowed
2537     // in their paired GPR.  So we only need to save the GPR to their home
2538     // slots.
2539     // TODO: __vectorcall will change this.
2540     return None;
2541   }
2542
2543   const Function *Fn = MF.getFunction();
2544   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2545   bool isSoftFloat = Subtarget->useSoftFloat();
2546   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2547          "SSE register cannot be used when SSE is disabled!");
2548   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2549     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2550     // registers.
2551     return None;
2552
2553   static const MCPhysReg XMMArgRegs64Bit[] = {
2554     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2555     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2556   };
2557   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2558 }
2559
2560 SDValue X86TargetLowering::LowerFormalArguments(
2561     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2562     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2563     SmallVectorImpl<SDValue> &InVals) const {
2564   MachineFunction &MF = DAG.getMachineFunction();
2565   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2566   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2567
2568   const Function* Fn = MF.getFunction();
2569   if (Fn->hasExternalLinkage() &&
2570       Subtarget->isTargetCygMing() &&
2571       Fn->getName() == "main")
2572     FuncInfo->setForceFramePointer(true);
2573
2574   MachineFrameInfo *MFI = MF.getFrameInfo();
2575   bool Is64Bit = Subtarget->is64Bit();
2576   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2577
2578   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2579          "Var args not supported with calling convention fastcc, ghc or hipe");
2580
2581   // Assign locations to all of the incoming arguments.
2582   SmallVector<CCValAssign, 16> ArgLocs;
2583   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2584
2585   // Allocate shadow area for Win64
2586   if (IsWin64)
2587     CCInfo.AllocateStack(32, 8);
2588
2589   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2590
2591   unsigned LastVal = ~0U;
2592   SDValue ArgValue;
2593   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2594     CCValAssign &VA = ArgLocs[i];
2595     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2596     // places.
2597     assert(VA.getValNo() != LastVal &&
2598            "Don't support value assigned to multiple locs yet");
2599     (void)LastVal;
2600     LastVal = VA.getValNo();
2601
2602     if (VA.isRegLoc()) {
2603       EVT RegVT = VA.getLocVT();
2604       const TargetRegisterClass *RC;
2605       if (RegVT == MVT::i32)
2606         RC = &X86::GR32RegClass;
2607       else if (Is64Bit && RegVT == MVT::i64)
2608         RC = &X86::GR64RegClass;
2609       else if (RegVT == MVT::f32)
2610         RC = &X86::FR32RegClass;
2611       else if (RegVT == MVT::f64)
2612         RC = &X86::FR64RegClass;
2613       else if (RegVT.is512BitVector())
2614         RC = &X86::VR512RegClass;
2615       else if (RegVT.is256BitVector())
2616         RC = &X86::VR256RegClass;
2617       else if (RegVT.is128BitVector())
2618         RC = &X86::VR128RegClass;
2619       else if (RegVT == MVT::x86mmx)
2620         RC = &X86::VR64RegClass;
2621       else if (RegVT == MVT::i1)
2622         RC = &X86::VK1RegClass;
2623       else if (RegVT == MVT::v8i1)
2624         RC = &X86::VK8RegClass;
2625       else if (RegVT == MVT::v16i1)
2626         RC = &X86::VK16RegClass;
2627       else if (RegVT == MVT::v32i1)
2628         RC = &X86::VK32RegClass;
2629       else if (RegVT == MVT::v64i1)
2630         RC = &X86::VK64RegClass;
2631       else
2632         llvm_unreachable("Unknown argument type!");
2633
2634       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2635       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2636
2637       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2638       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2639       // right size.
2640       if (VA.getLocInfo() == CCValAssign::SExt)
2641         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2642                                DAG.getValueType(VA.getValVT()));
2643       else if (VA.getLocInfo() == CCValAssign::ZExt)
2644         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2645                                DAG.getValueType(VA.getValVT()));
2646       else if (VA.getLocInfo() == CCValAssign::BCvt)
2647         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2648
2649       if (VA.isExtInLoc()) {
2650         // Handle MMX values passed in XMM regs.
2651         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2652           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2653         else
2654           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2655       }
2656     } else {
2657       assert(VA.isMemLoc());
2658       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2659     }
2660
2661     // If value is passed via pointer - do a load.
2662     if (VA.getLocInfo() == CCValAssign::Indirect)
2663       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2664                              MachinePointerInfo(), false, false, false, 0);
2665
2666     InVals.push_back(ArgValue);
2667   }
2668
2669   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2670     // All x86 ABIs require that for returning structs by value we copy the
2671     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2672     // the argument into a virtual register so that we can access it from the
2673     // return points.
2674     if (Ins[i].Flags.isSRet()) {
2675       unsigned Reg = FuncInfo->getSRetReturnReg();
2676       if (!Reg) {
2677         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2678         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2679         FuncInfo->setSRetReturnReg(Reg);
2680       }
2681       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2682       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2683       break;
2684     }
2685   }
2686
2687   unsigned StackSize = CCInfo.getNextStackOffset();
2688   // Align stack specially for tail calls.
2689   if (FuncIsMadeTailCallSafe(CallConv,
2690                              MF.getTarget().Options.GuaranteedTailCallOpt))
2691     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2692
2693   // If the function takes variable number of arguments, make a frame index for
2694   // the start of the first vararg value... for expansion of llvm.va_start. We
2695   // can skip this if there are no va_start calls.
2696   if (MFI->hasVAStart() &&
2697       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2698                    CallConv != CallingConv::X86_ThisCall))) {
2699     FuncInfo->setVarArgsFrameIndex(
2700         MFI->CreateFixedObject(1, StackSize, true));
2701   }
2702
2703   MachineModuleInfo &MMI = MF.getMMI();
2704
2705   // Figure out if XMM registers are in use.
2706   assert(!(Subtarget->useSoftFloat() &&
2707            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2708          "SSE register cannot be used when SSE is disabled!");
2709
2710   // 64-bit calling conventions support varargs and register parameters, so we
2711   // have to do extra work to spill them in the prologue.
2712   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2713     // Find the first unallocated argument registers.
2714     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2715     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2716     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2717     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2718     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2719            "SSE register cannot be used when SSE is disabled!");
2720
2721     // Gather all the live in physical registers.
2722     SmallVector<SDValue, 6> LiveGPRs;
2723     SmallVector<SDValue, 8> LiveXMMRegs;
2724     SDValue ALVal;
2725     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2726       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2727       LiveGPRs.push_back(
2728           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2729     }
2730     if (!ArgXMMs.empty()) {
2731       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2732       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2733       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2734         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2735         LiveXMMRegs.push_back(
2736             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2737       }
2738     }
2739
2740     if (IsWin64) {
2741       // Get to the caller-allocated home save location.  Add 8 to account
2742       // for the return address.
2743       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2744       FuncInfo->setRegSaveFrameIndex(
2745           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2746       // Fixup to set vararg frame on shadow area (4 x i64).
2747       if (NumIntRegs < 4)
2748         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2749     } else {
2750       // For X86-64, if there are vararg parameters that are passed via
2751       // registers, then we must store them to their spots on the stack so
2752       // they may be loaded by deferencing the result of va_next.
2753       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2754       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2755       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2756           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2757     }
2758
2759     // Store the integer parameter registers.
2760     SmallVector<SDValue, 8> MemOps;
2761     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2762                                       getPointerTy(DAG.getDataLayout()));
2763     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2764     for (SDValue Val : LiveGPRs) {
2765       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2766                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2767       SDValue Store =
2768           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2769                        MachinePointerInfo::getFixedStack(
2770                            DAG.getMachineFunction(),
2771                            FuncInfo->getRegSaveFrameIndex(), Offset),
2772                        false, false, 0);
2773       MemOps.push_back(Store);
2774       Offset += 8;
2775     }
2776
2777     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2778       // Now store the XMM (fp + vector) parameter registers.
2779       SmallVector<SDValue, 12> SaveXMMOps;
2780       SaveXMMOps.push_back(Chain);
2781       SaveXMMOps.push_back(ALVal);
2782       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2783                              FuncInfo->getRegSaveFrameIndex(), dl));
2784       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2785                              FuncInfo->getVarArgsFPOffset(), dl));
2786       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2787                         LiveXMMRegs.end());
2788       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2789                                    MVT::Other, SaveXMMOps));
2790     }
2791
2792     if (!MemOps.empty())
2793       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2794   }
2795
2796   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2797     // Find the largest legal vector type.
2798     MVT VecVT = MVT::Other;
2799     // FIXME: Only some x86_32 calling conventions support AVX512.
2800     if (Subtarget->hasAVX512() &&
2801         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2802                      CallConv == CallingConv::Intel_OCL_BI)))
2803       VecVT = MVT::v16f32;
2804     else if (Subtarget->hasAVX())
2805       VecVT = MVT::v8f32;
2806     else if (Subtarget->hasSSE2())
2807       VecVT = MVT::v4f32;
2808
2809     // We forward some GPRs and some vector types.
2810     SmallVector<MVT, 2> RegParmTypes;
2811     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2812     RegParmTypes.push_back(IntVT);
2813     if (VecVT != MVT::Other)
2814       RegParmTypes.push_back(VecVT);
2815
2816     // Compute the set of forwarded registers. The rest are scratch.
2817     SmallVectorImpl<ForwardedRegister> &Forwards =
2818         FuncInfo->getForwardedMustTailRegParms();
2819     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2820
2821     // Conservatively forward AL on x86_64, since it might be used for varargs.
2822     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2823       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2824       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2825     }
2826
2827     // Copy all forwards from physical to virtual registers.
2828     for (ForwardedRegister &F : Forwards) {
2829       // FIXME: Can we use a less constrained schedule?
2830       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2831       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2832       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2833     }
2834   }
2835
2836   // Some CCs need callee pop.
2837   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2838                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2839     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2840   } else {
2841     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2842     // If this is an sret function, the return should pop the hidden pointer.
2843     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2844         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2845         argsAreStructReturn(Ins) == StackStructReturn)
2846       FuncInfo->setBytesToPopOnReturn(4);
2847   }
2848
2849   if (!Is64Bit) {
2850     // RegSaveFrameIndex is X86-64 only.
2851     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2852     if (CallConv == CallingConv::X86_FastCall ||
2853         CallConv == CallingConv::X86_ThisCall)
2854       // fastcc functions can't have varargs.
2855       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2856   }
2857
2858   FuncInfo->setArgumentStackSize(StackSize);
2859
2860   if (MMI.hasWinEHFuncInfo(Fn)) {
2861     if (Is64Bit) {
2862       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2863       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2864       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2865       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2866       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2867                            MachinePointerInfo::getFixedStack(
2868                                DAG.getMachineFunction(), UnwindHelpFI),
2869                            /*isVolatile=*/true,
2870                            /*isNonTemporal=*/false, /*Alignment=*/0);
2871     } else {
2872       // Functions using Win32 EH are considered to have opaque SP adjustments
2873       // to force local variables to be addressed from the frame or base
2874       // pointers.
2875       MFI->setHasOpaqueSPAdjustment(true);
2876     }
2877   }
2878
2879   return Chain;
2880 }
2881
2882 SDValue
2883 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2884                                     SDValue StackPtr, SDValue Arg,
2885                                     SDLoc dl, SelectionDAG &DAG,
2886                                     const CCValAssign &VA,
2887                                     ISD::ArgFlagsTy Flags) const {
2888   unsigned LocMemOffset = VA.getLocMemOffset();
2889   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2890   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2891                        StackPtr, PtrOff);
2892   if (Flags.isByVal())
2893     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2894
2895   return DAG.getStore(
2896       Chain, dl, Arg, PtrOff,
2897       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2898       false, false, 0);
2899 }
2900
2901 /// Emit a load of return address if tail call
2902 /// optimization is performed and it is required.
2903 SDValue
2904 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2905                                            SDValue &OutRetAddr, SDValue Chain,
2906                                            bool IsTailCall, bool Is64Bit,
2907                                            int FPDiff, SDLoc dl) const {
2908   // Adjust the Return address stack slot.
2909   EVT VT = getPointerTy(DAG.getDataLayout());
2910   OutRetAddr = getReturnAddressFrameIndex(DAG);
2911
2912   // Load the "old" Return address.
2913   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2914                            false, false, false, 0);
2915   return SDValue(OutRetAddr.getNode(), 1);
2916 }
2917
2918 /// Emit a store of the return address if tail call
2919 /// optimization is performed and it is required (FPDiff!=0).
2920 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2921                                         SDValue Chain, SDValue RetAddrFrIdx,
2922                                         EVT PtrVT, unsigned SlotSize,
2923                                         int FPDiff, SDLoc dl) {
2924   // Store the return address to the appropriate stack slot.
2925   if (!FPDiff) return Chain;
2926   // Calculate the new stack slot for the return address.
2927   int NewReturnAddrFI =
2928     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2929                                          false);
2930   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2931   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2932                        MachinePointerInfo::getFixedStack(
2933                            DAG.getMachineFunction(), NewReturnAddrFI),
2934                        false, false, 0);
2935   return Chain;
2936 }
2937
2938 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2939 /// operation of specified width.
2940 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2941                        SDValue V2) {
2942   unsigned NumElems = VT.getVectorNumElements();
2943   SmallVector<int, 8> Mask;
2944   Mask.push_back(NumElems);
2945   for (unsigned i = 1; i != NumElems; ++i)
2946     Mask.push_back(i);
2947   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2948 }
2949
2950 SDValue
2951 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2952                              SmallVectorImpl<SDValue> &InVals) const {
2953   SelectionDAG &DAG                     = CLI.DAG;
2954   SDLoc &dl                             = CLI.DL;
2955   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2956   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2957   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2958   SDValue Chain                         = CLI.Chain;
2959   SDValue Callee                        = CLI.Callee;
2960   CallingConv::ID CallConv              = CLI.CallConv;
2961   bool &isTailCall                      = CLI.IsTailCall;
2962   bool isVarArg                         = CLI.IsVarArg;
2963
2964   MachineFunction &MF = DAG.getMachineFunction();
2965   bool Is64Bit        = Subtarget->is64Bit();
2966   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2967   StructReturnType SR = callIsStructReturn(Outs);
2968   bool IsSibcall      = false;
2969   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2970   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2971
2972   if (Attr.getValueAsString() == "true")
2973     isTailCall = false;
2974
2975   if (Subtarget->isPICStyleGOT() &&
2976       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2977     // If we are using a GOT, disable tail calls to external symbols with
2978     // default visibility. Tail calling such a symbol requires using a GOT
2979     // relocation, which forces early binding of the symbol. This breaks code
2980     // that require lazy function symbol resolution. Using musttail or
2981     // GuaranteedTailCallOpt will override this.
2982     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2983     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2984                G->getGlobal()->hasDefaultVisibility()))
2985       isTailCall = false;
2986   }
2987
2988   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2989   if (IsMustTail) {
2990     // Force this to be a tail call.  The verifier rules are enough to ensure
2991     // that we can lower this successfully without moving the return address
2992     // around.
2993     isTailCall = true;
2994   } else if (isTailCall) {
2995     // Check if it's really possible to do a tail call.
2996     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2997                     isVarArg, SR != NotStructReturn,
2998                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2999                     Outs, OutVals, Ins, DAG);
3000
3001     // Sibcalls are automatically detected tailcalls which do not require
3002     // ABI changes.
3003     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3004       IsSibcall = true;
3005
3006     if (isTailCall)
3007       ++NumTailCalls;
3008   }
3009
3010   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
3011          "Var args not supported with calling convention fastcc, ghc or hipe");
3012
3013   // Analyze operands of the call, assigning locations to each operand.
3014   SmallVector<CCValAssign, 16> ArgLocs;
3015   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3016
3017   // Allocate shadow area for Win64
3018   if (IsWin64)
3019     CCInfo.AllocateStack(32, 8);
3020
3021   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3022
3023   // Get a count of how many bytes are to be pushed on the stack.
3024   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3025   if (IsSibcall)
3026     // This is a sibcall. The memory operands are available in caller's
3027     // own caller's stack.
3028     NumBytes = 0;
3029   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3030            IsTailCallConvention(CallConv))
3031     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3032
3033   int FPDiff = 0;
3034   if (isTailCall && !IsSibcall && !IsMustTail) {
3035     // Lower arguments at fp - stackoffset + fpdiff.
3036     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3037
3038     FPDiff = NumBytesCallerPushed - NumBytes;
3039
3040     // Set the delta of movement of the returnaddr stackslot.
3041     // But only set if delta is greater than previous delta.
3042     if (FPDiff < X86Info->getTCReturnAddrDelta())
3043       X86Info->setTCReturnAddrDelta(FPDiff);
3044   }
3045
3046   unsigned NumBytesToPush = NumBytes;
3047   unsigned NumBytesToPop = NumBytes;
3048
3049   // If we have an inalloca argument, all stack space has already been allocated
3050   // for us and be right at the top of the stack.  We don't support multiple
3051   // arguments passed in memory when using inalloca.
3052   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3053     NumBytesToPush = 0;
3054     if (!ArgLocs.back().isMemLoc())
3055       report_fatal_error("cannot use inalloca attribute on a register "
3056                          "parameter");
3057     if (ArgLocs.back().getLocMemOffset() != 0)
3058       report_fatal_error("any parameter with the inalloca attribute must be "
3059                          "the only memory argument");
3060   }
3061
3062   if (!IsSibcall)
3063     Chain = DAG.getCALLSEQ_START(
3064         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3065
3066   SDValue RetAddrFrIdx;
3067   // Load return address for tail calls.
3068   if (isTailCall && FPDiff)
3069     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3070                                     Is64Bit, FPDiff, dl);
3071
3072   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3073   SmallVector<SDValue, 8> MemOpChains;
3074   SDValue StackPtr;
3075
3076   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3077   // of tail call optimization arguments are handle later.
3078   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3079   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3080     // Skip inalloca arguments, they have already been written.
3081     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3082     if (Flags.isInAlloca())
3083       continue;
3084
3085     CCValAssign &VA = ArgLocs[i];
3086     EVT RegVT = VA.getLocVT();
3087     SDValue Arg = OutVals[i];
3088     bool isByVal = Flags.isByVal();
3089
3090     // Promote the value if needed.
3091     switch (VA.getLocInfo()) {
3092     default: llvm_unreachable("Unknown loc info!");
3093     case CCValAssign::Full: break;
3094     case CCValAssign::SExt:
3095       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3096       break;
3097     case CCValAssign::ZExt:
3098       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3099       break;
3100     case CCValAssign::AExt:
3101       if (Arg.getValueType().isVector() &&
3102           Arg.getValueType().getScalarType() == MVT::i1)
3103         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3104       else if (RegVT.is128BitVector()) {
3105         // Special case: passing MMX values in XMM registers.
3106         Arg = DAG.getBitcast(MVT::i64, Arg);
3107         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3108         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3109       } else
3110         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3111       break;
3112     case CCValAssign::BCvt:
3113       Arg = DAG.getBitcast(RegVT, Arg);
3114       break;
3115     case CCValAssign::Indirect: {
3116       // Store the argument.
3117       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3118       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3119       Chain = DAG.getStore(
3120           Chain, dl, Arg, SpillSlot,
3121           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3122           false, false, 0);
3123       Arg = SpillSlot;
3124       break;
3125     }
3126     }
3127
3128     if (VA.isRegLoc()) {
3129       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3130       if (isVarArg && IsWin64) {
3131         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3132         // shadow reg if callee is a varargs function.
3133         unsigned ShadowReg = 0;
3134         switch (VA.getLocReg()) {
3135         case X86::XMM0: ShadowReg = X86::RCX; break;
3136         case X86::XMM1: ShadowReg = X86::RDX; break;
3137         case X86::XMM2: ShadowReg = X86::R8; break;
3138         case X86::XMM3: ShadowReg = X86::R9; break;
3139         }
3140         if (ShadowReg)
3141           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3142       }
3143     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3144       assert(VA.isMemLoc());
3145       if (!StackPtr.getNode())
3146         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3147                                       getPointerTy(DAG.getDataLayout()));
3148       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3149                                              dl, DAG, VA, Flags));
3150     }
3151   }
3152
3153   if (!MemOpChains.empty())
3154     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3155
3156   if (Subtarget->isPICStyleGOT()) {
3157     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3158     // GOT pointer.
3159     if (!isTailCall) {
3160       RegsToPass.push_back(std::make_pair(
3161           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3162                                           getPointerTy(DAG.getDataLayout()))));
3163     } else {
3164       // If we are tail calling and generating PIC/GOT style code load the
3165       // address of the callee into ECX. The value in ecx is used as target of
3166       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3167       // for tail calls on PIC/GOT architectures. Normally we would just put the
3168       // address of GOT into ebx and then call target@PLT. But for tail calls
3169       // ebx would be restored (since ebx is callee saved) before jumping to the
3170       // target@PLT.
3171
3172       // Note: The actual moving to ECX is done further down.
3173       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3174       if (G && !G->getGlobal()->hasLocalLinkage() &&
3175           G->getGlobal()->hasDefaultVisibility())
3176         Callee = LowerGlobalAddress(Callee, DAG);
3177       else if (isa<ExternalSymbolSDNode>(Callee))
3178         Callee = LowerExternalSymbol(Callee, DAG);
3179     }
3180   }
3181
3182   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3183     // From AMD64 ABI document:
3184     // For calls that may call functions that use varargs or stdargs
3185     // (prototype-less calls or calls to functions containing ellipsis (...) in
3186     // the declaration) %al is used as hidden argument to specify the number
3187     // of SSE registers used. The contents of %al do not need to match exactly
3188     // the number of registers, but must be an ubound on the number of SSE
3189     // registers used and is in the range 0 - 8 inclusive.
3190
3191     // Count the number of XMM registers allocated.
3192     static const MCPhysReg XMMArgRegs[] = {
3193       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3194       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3195     };
3196     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3197     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3198            && "SSE registers cannot be used when SSE is disabled");
3199
3200     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3201                                         DAG.getConstant(NumXMMRegs, dl,
3202                                                         MVT::i8)));
3203   }
3204
3205   if (isVarArg && IsMustTail) {
3206     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3207     for (const auto &F : Forwards) {
3208       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3209       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3210     }
3211   }
3212
3213   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3214   // don't need this because the eligibility check rejects calls that require
3215   // shuffling arguments passed in memory.
3216   if (!IsSibcall && isTailCall) {
3217     // Force all the incoming stack arguments to be loaded from the stack
3218     // before any new outgoing arguments are stored to the stack, because the
3219     // outgoing stack slots may alias the incoming argument stack slots, and
3220     // the alias isn't otherwise explicit. This is slightly more conservative
3221     // than necessary, because it means that each store effectively depends
3222     // on every argument instead of just those arguments it would clobber.
3223     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3224
3225     SmallVector<SDValue, 8> MemOpChains2;
3226     SDValue FIN;
3227     int FI = 0;
3228     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3229       CCValAssign &VA = ArgLocs[i];
3230       if (VA.isRegLoc())
3231         continue;
3232       assert(VA.isMemLoc());
3233       SDValue Arg = OutVals[i];
3234       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3235       // Skip inalloca arguments.  They don't require any work.
3236       if (Flags.isInAlloca())
3237         continue;
3238       // Create frame index.
3239       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3240       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3241       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3242       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3243
3244       if (Flags.isByVal()) {
3245         // Copy relative to framepointer.
3246         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3247         if (!StackPtr.getNode())
3248           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3249                                         getPointerTy(DAG.getDataLayout()));
3250         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3251                              StackPtr, Source);
3252
3253         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3254                                                          ArgChain,
3255                                                          Flags, DAG, dl));
3256       } else {
3257         // Store relative to framepointer.
3258         MemOpChains2.push_back(DAG.getStore(
3259             ArgChain, dl, Arg, FIN,
3260             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3261             false, false, 0));
3262       }
3263     }
3264
3265     if (!MemOpChains2.empty())
3266       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3267
3268     // Store the return address to the appropriate stack slot.
3269     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3270                                      getPointerTy(DAG.getDataLayout()),
3271                                      RegInfo->getSlotSize(), FPDiff, dl);
3272   }
3273
3274   // Build a sequence of copy-to-reg nodes chained together with token chain
3275   // and flag operands which copy the outgoing args into registers.
3276   SDValue InFlag;
3277   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3278     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3279                              RegsToPass[i].second, InFlag);
3280     InFlag = Chain.getValue(1);
3281   }
3282
3283   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3284     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3285     // In the 64-bit large code model, we have to make all calls
3286     // through a register, since the call instruction's 32-bit
3287     // pc-relative offset may not be large enough to hold the whole
3288     // address.
3289   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3290     // If the callee is a GlobalAddress node (quite common, every direct call
3291     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3292     // it.
3293     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3294
3295     // We should use extra load for direct calls to dllimported functions in
3296     // non-JIT mode.
3297     const GlobalValue *GV = G->getGlobal();
3298     if (!GV->hasDLLImportStorageClass()) {
3299       unsigned char OpFlags = 0;
3300       bool ExtraLoad = false;
3301       unsigned WrapperKind = ISD::DELETED_NODE;
3302
3303       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3304       // external symbols most go through the PLT in PIC mode.  If the symbol
3305       // has hidden or protected visibility, or if it is static or local, then
3306       // we don't need to use the PLT - we can directly call it.
3307       if (Subtarget->isTargetELF() &&
3308           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3309           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3310         OpFlags = X86II::MO_PLT;
3311       } else if (Subtarget->isPICStyleStubAny() &&
3312                  !GV->isStrongDefinitionForLinker() &&
3313                  (!Subtarget->getTargetTriple().isMacOSX() ||
3314                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3315         // PC-relative references to external symbols should go through $stub,
3316         // unless we're building with the leopard linker or later, which
3317         // automatically synthesizes these stubs.
3318         OpFlags = X86II::MO_DARWIN_STUB;
3319       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3320                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3321         // If the function is marked as non-lazy, generate an indirect call
3322         // which loads from the GOT directly. This avoids runtime overhead
3323         // at the cost of eager binding (and one extra byte of encoding).
3324         OpFlags = X86II::MO_GOTPCREL;
3325         WrapperKind = X86ISD::WrapperRIP;
3326         ExtraLoad = true;
3327       }
3328
3329       Callee = DAG.getTargetGlobalAddress(
3330           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3331
3332       // Add a wrapper if needed.
3333       if (WrapperKind != ISD::DELETED_NODE)
3334         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3335                              getPointerTy(DAG.getDataLayout()), Callee);
3336       // Add extra indirection if needed.
3337       if (ExtraLoad)
3338         Callee = DAG.getLoad(
3339             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3340             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3341             false, 0);
3342     }
3343   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3344     unsigned char OpFlags = 0;
3345
3346     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3347     // external symbols should go through the PLT.
3348     if (Subtarget->isTargetELF() &&
3349         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3350       OpFlags = X86II::MO_PLT;
3351     } else if (Subtarget->isPICStyleStubAny() &&
3352                (!Subtarget->getTargetTriple().isMacOSX() ||
3353                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3354       // PC-relative references to external symbols should go through $stub,
3355       // unless we're building with the leopard linker or later, which
3356       // automatically synthesizes these stubs.
3357       OpFlags = X86II::MO_DARWIN_STUB;
3358     }
3359
3360     Callee = DAG.getTargetExternalSymbol(
3361         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3362   } else if (Subtarget->isTarget64BitILP32() &&
3363              Callee->getValueType(0) == MVT::i32) {
3364     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3365     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3366   }
3367
3368   // Returns a chain & a flag for retval copy to use.
3369   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3370   SmallVector<SDValue, 8> Ops;
3371
3372   if (!IsSibcall && isTailCall) {
3373     Chain = DAG.getCALLSEQ_END(Chain,
3374                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3375                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3376     InFlag = Chain.getValue(1);
3377   }
3378
3379   Ops.push_back(Chain);
3380   Ops.push_back(Callee);
3381
3382   if (isTailCall)
3383     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3384
3385   // Add argument registers to the end of the list so that they are known live
3386   // into the call.
3387   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3388     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3389                                   RegsToPass[i].second.getValueType()));
3390
3391   // Add a register mask operand representing the call-preserved registers.
3392   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3393   assert(Mask && "Missing call preserved mask for calling convention");
3394
3395   // If this is an invoke in a 32-bit function using a funclet-based
3396   // personality, assume the function clobbers all registers. If an exception
3397   // is thrown, the runtime will not restore CSRs.
3398   // FIXME: Model this more precisely so that we can register allocate across
3399   // the normal edge and spill and fill across the exceptional edge.
3400   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3401     const Function *CallerFn = MF.getFunction();
3402     EHPersonality Pers =
3403         CallerFn->hasPersonalityFn()
3404             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3405             : EHPersonality::Unknown;
3406     if (isFuncletEHPersonality(Pers))
3407       Mask = RegInfo->getNoPreservedMask();
3408   }
3409
3410   Ops.push_back(DAG.getRegisterMask(Mask));
3411
3412   if (InFlag.getNode())
3413     Ops.push_back(InFlag);
3414
3415   if (isTailCall) {
3416     // We used to do:
3417     //// If this is the first return lowered for this function, add the regs
3418     //// to the liveout set for the function.
3419     // This isn't right, although it's probably harmless on x86; liveouts
3420     // should be computed from returns not tail calls.  Consider a void
3421     // function making a tail call to a function returning int.
3422     MF.getFrameInfo()->setHasTailCall();
3423     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3424   }
3425
3426   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3427   InFlag = Chain.getValue(1);
3428
3429   // Create the CALLSEQ_END node.
3430   unsigned NumBytesForCalleeToPop;
3431   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3432                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3433     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3434   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3435            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3436            SR == StackStructReturn)
3437     // If this is a call to a struct-return function, the callee
3438     // pops the hidden struct pointer, so we have to push it back.
3439     // This is common for Darwin/X86, Linux & Mingw32 targets.
3440     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3441     NumBytesForCalleeToPop = 4;
3442   else
3443     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3444
3445   // Returns a flag for retval copy to use.
3446   if (!IsSibcall) {
3447     Chain = DAG.getCALLSEQ_END(Chain,
3448                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3449                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3450                                                      true),
3451                                InFlag, dl);
3452     InFlag = Chain.getValue(1);
3453   }
3454
3455   // Handle result values, copying them out of physregs into vregs that we
3456   // return.
3457   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3458                          Ins, dl, DAG, InVals);
3459 }
3460
3461 //===----------------------------------------------------------------------===//
3462 //                Fast Calling Convention (tail call) implementation
3463 //===----------------------------------------------------------------------===//
3464
3465 //  Like std call, callee cleans arguments, convention except that ECX is
3466 //  reserved for storing the tail called function address. Only 2 registers are
3467 //  free for argument passing (inreg). Tail call optimization is performed
3468 //  provided:
3469 //                * tailcallopt is enabled
3470 //                * caller/callee are fastcc
3471 //  On X86_64 architecture with GOT-style position independent code only local
3472 //  (within module) calls are supported at the moment.
3473 //  To keep the stack aligned according to platform abi the function
3474 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3475 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3476 //  If a tail called function callee has more arguments than the caller the
3477 //  caller needs to make sure that there is room to move the RETADDR to. This is
3478 //  achieved by reserving an area the size of the argument delta right after the
3479 //  original RETADDR, but before the saved framepointer or the spilled registers
3480 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3481 //  stack layout:
3482 //    arg1
3483 //    arg2
3484 //    RETADDR
3485 //    [ new RETADDR
3486 //      move area ]
3487 //    (possible EBP)
3488 //    ESI
3489 //    EDI
3490 //    local1 ..
3491
3492 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3493 /// requirement.
3494 unsigned
3495 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3496                                                SelectionDAG& DAG) const {
3497   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3498   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3499   unsigned StackAlignment = TFI.getStackAlignment();
3500   uint64_t AlignMask = StackAlignment - 1;
3501   int64_t Offset = StackSize;
3502   unsigned SlotSize = RegInfo->getSlotSize();
3503   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3504     // Number smaller than 12 so just add the difference.
3505     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3506   } else {
3507     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3508     Offset = ((~AlignMask) & Offset) + StackAlignment +
3509       (StackAlignment-SlotSize);
3510   }
3511   return Offset;
3512 }
3513
3514 /// Return true if the given stack call argument is already available in the
3515 /// same position (relatively) of the caller's incoming argument stack.
3516 static
3517 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3518                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3519                          const X86InstrInfo *TII) {
3520   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3521   int FI = INT_MAX;
3522   if (Arg.getOpcode() == ISD::CopyFromReg) {
3523     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3524     if (!TargetRegisterInfo::isVirtualRegister(VR))
3525       return false;
3526     MachineInstr *Def = MRI->getVRegDef(VR);
3527     if (!Def)
3528       return false;
3529     if (!Flags.isByVal()) {
3530       if (!TII->isLoadFromStackSlot(Def, FI))
3531         return false;
3532     } else {
3533       unsigned Opcode = Def->getOpcode();
3534       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3535            Opcode == X86::LEA64_32r) &&
3536           Def->getOperand(1).isFI()) {
3537         FI = Def->getOperand(1).getIndex();
3538         Bytes = Flags.getByValSize();
3539       } else
3540         return false;
3541     }
3542   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3543     if (Flags.isByVal())
3544       // ByVal argument is passed in as a pointer but it's now being
3545       // dereferenced. e.g.
3546       // define @foo(%struct.X* %A) {
3547       //   tail call @bar(%struct.X* byval %A)
3548       // }
3549       return false;
3550     SDValue Ptr = Ld->getBasePtr();
3551     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3552     if (!FINode)
3553       return false;
3554     FI = FINode->getIndex();
3555   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3556     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3557     FI = FINode->getIndex();
3558     Bytes = Flags.getByValSize();
3559   } else
3560     return false;
3561
3562   assert(FI != INT_MAX);
3563   if (!MFI->isFixedObjectIndex(FI))
3564     return false;
3565   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3566 }
3567
3568 /// Check whether the call is eligible for tail call optimization. Targets
3569 /// that want to do tail call optimization should implement this function.
3570 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3571     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3572     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3573     const SmallVectorImpl<ISD::OutputArg> &Outs,
3574     const SmallVectorImpl<SDValue> &OutVals,
3575     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3576   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3577     return false;
3578
3579   // If -tailcallopt is specified, make fastcc functions tail-callable.
3580   const MachineFunction &MF = DAG.getMachineFunction();
3581   const Function *CallerF = MF.getFunction();
3582
3583   // If the function return type is x86_fp80 and the callee return type is not,
3584   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3585   // perform a tailcall optimization here.
3586   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3587     return false;
3588
3589   CallingConv::ID CallerCC = CallerF->getCallingConv();
3590   bool CCMatch = CallerCC == CalleeCC;
3591   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3592   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3593
3594   // Win64 functions have extra shadow space for argument homing. Don't do the
3595   // sibcall if the caller and callee have mismatched expectations for this
3596   // space.
3597   if (IsCalleeWin64 != IsCallerWin64)
3598     return false;
3599
3600   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3601     if (IsTailCallConvention(CalleeCC) && CCMatch)
3602       return true;
3603     return false;
3604   }
3605
3606   // Look for obvious safe cases to perform tail call optimization that do not
3607   // require ABI changes. This is what gcc calls sibcall.
3608
3609   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3610   // emit a special epilogue.
3611   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3612   if (RegInfo->needsStackRealignment(MF))
3613     return false;
3614
3615   // Also avoid sibcall optimization if either caller or callee uses struct
3616   // return semantics.
3617   if (isCalleeStructRet || isCallerStructRet)
3618     return false;
3619
3620   // An stdcall/thiscall caller is expected to clean up its arguments; the
3621   // callee isn't going to do that.
3622   // FIXME: this is more restrictive than needed. We could produce a tailcall
3623   // when the stack adjustment matches. For example, with a thiscall that takes
3624   // only one argument.
3625   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3626                    CallerCC == CallingConv::X86_ThisCall))
3627     return false;
3628
3629   // Do not sibcall optimize vararg calls unless all arguments are passed via
3630   // registers.
3631   if (isVarArg && !Outs.empty()) {
3632
3633     // Optimizing for varargs on Win64 is unlikely to be safe without
3634     // additional testing.
3635     if (IsCalleeWin64 || IsCallerWin64)
3636       return false;
3637
3638     SmallVector<CCValAssign, 16> ArgLocs;
3639     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3640                    *DAG.getContext());
3641
3642     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3643     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3644       if (!ArgLocs[i].isRegLoc())
3645         return false;
3646   }
3647
3648   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3649   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3650   // this into a sibcall.
3651   bool Unused = false;
3652   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3653     if (!Ins[i].Used) {
3654       Unused = true;
3655       break;
3656     }
3657   }
3658   if (Unused) {
3659     SmallVector<CCValAssign, 16> RVLocs;
3660     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3661                    *DAG.getContext());
3662     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3663     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3664       CCValAssign &VA = RVLocs[i];
3665       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3666         return false;
3667     }
3668   }
3669
3670   // If the calling conventions do not match, then we'd better make sure the
3671   // results are returned in the same way as what the caller expects.
3672   if (!CCMatch) {
3673     SmallVector<CCValAssign, 16> RVLocs1;
3674     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3675                     *DAG.getContext());
3676     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3677
3678     SmallVector<CCValAssign, 16> RVLocs2;
3679     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3680                     *DAG.getContext());
3681     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3682
3683     if (RVLocs1.size() != RVLocs2.size())
3684       return false;
3685     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3686       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3687         return false;
3688       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3689         return false;
3690       if (RVLocs1[i].isRegLoc()) {
3691         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3692           return false;
3693       } else {
3694         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3695           return false;
3696       }
3697     }
3698   }
3699
3700   // If the callee takes no arguments then go on to check the results of the
3701   // call.
3702   if (!Outs.empty()) {
3703     // Check if stack adjustment is needed. For now, do not do this if any
3704     // argument is passed on the stack.
3705     SmallVector<CCValAssign, 16> ArgLocs;
3706     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3707                    *DAG.getContext());
3708
3709     // Allocate shadow area for Win64
3710     if (IsCalleeWin64)
3711       CCInfo.AllocateStack(32, 8);
3712
3713     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3714     if (CCInfo.getNextStackOffset()) {
3715       MachineFunction &MF = DAG.getMachineFunction();
3716       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3717         return false;
3718
3719       // Check if the arguments are already laid out in the right way as
3720       // the caller's fixed stack objects.
3721       MachineFrameInfo *MFI = MF.getFrameInfo();
3722       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3723       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3724       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3725         CCValAssign &VA = ArgLocs[i];
3726         SDValue Arg = OutVals[i];
3727         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3728         if (VA.getLocInfo() == CCValAssign::Indirect)
3729           return false;
3730         if (!VA.isRegLoc()) {
3731           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3732                                    MFI, MRI, TII))
3733             return false;
3734         }
3735       }
3736     }
3737
3738     // If the tailcall address may be in a register, then make sure it's
3739     // possible to register allocate for it. In 32-bit, the call address can
3740     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3741     // callee-saved registers are restored. These happen to be the same
3742     // registers used to pass 'inreg' arguments so watch out for those.
3743     if (!Subtarget->is64Bit() &&
3744         ((!isa<GlobalAddressSDNode>(Callee) &&
3745           !isa<ExternalSymbolSDNode>(Callee)) ||
3746          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3747       unsigned NumInRegs = 0;
3748       // In PIC we need an extra register to formulate the address computation
3749       // for the callee.
3750       unsigned MaxInRegs =
3751         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3752
3753       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3754         CCValAssign &VA = ArgLocs[i];
3755         if (!VA.isRegLoc())
3756           continue;
3757         unsigned Reg = VA.getLocReg();
3758         switch (Reg) {
3759         default: break;
3760         case X86::EAX: case X86::EDX: case X86::ECX:
3761           if (++NumInRegs == MaxInRegs)
3762             return false;
3763           break;
3764         }
3765       }
3766     }
3767   }
3768
3769   return true;
3770 }
3771
3772 FastISel *
3773 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3774                                   const TargetLibraryInfo *libInfo) const {
3775   return X86::createFastISel(funcInfo, libInfo);
3776 }
3777
3778 //===----------------------------------------------------------------------===//
3779 //                           Other Lowering Hooks
3780 //===----------------------------------------------------------------------===//
3781
3782 static bool MayFoldLoad(SDValue Op) {
3783   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3784 }
3785
3786 static bool MayFoldIntoStore(SDValue Op) {
3787   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3788 }
3789
3790 static bool isTargetShuffle(unsigned Opcode) {
3791   switch(Opcode) {
3792   default: return false;
3793   case X86ISD::BLENDI:
3794   case X86ISD::PSHUFB:
3795   case X86ISD::PSHUFD:
3796   case X86ISD::PSHUFHW:
3797   case X86ISD::PSHUFLW:
3798   case X86ISD::SHUFP:
3799   case X86ISD::PALIGNR:
3800   case X86ISD::MOVLHPS:
3801   case X86ISD::MOVLHPD:
3802   case X86ISD::MOVHLPS:
3803   case X86ISD::MOVLPS:
3804   case X86ISD::MOVLPD:
3805   case X86ISD::MOVSHDUP:
3806   case X86ISD::MOVSLDUP:
3807   case X86ISD::MOVDDUP:
3808   case X86ISD::MOVSS:
3809   case X86ISD::MOVSD:
3810   case X86ISD::UNPCKL:
3811   case X86ISD::UNPCKH:
3812   case X86ISD::VPERMILPI:
3813   case X86ISD::VPERM2X128:
3814   case X86ISD::VPERMI:
3815   case X86ISD::VPERMV:
3816   case X86ISD::VPERMV3:
3817     return true;
3818   }
3819 }
3820
3821 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3822                                     SDValue V1, unsigned TargetMask,
3823                                     SelectionDAG &DAG) {
3824   switch(Opc) {
3825   default: llvm_unreachable("Unknown x86 shuffle node");
3826   case X86ISD::PSHUFD:
3827   case X86ISD::PSHUFHW:
3828   case X86ISD::PSHUFLW:
3829   case X86ISD::VPERMILPI:
3830   case X86ISD::VPERMI:
3831     return DAG.getNode(Opc, dl, VT, V1,
3832                        DAG.getConstant(TargetMask, dl, MVT::i8));
3833   }
3834 }
3835
3836 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3837                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3838   switch(Opc) {
3839   default: llvm_unreachable("Unknown x86 shuffle node");
3840   case X86ISD::MOVLHPS:
3841   case X86ISD::MOVLHPD:
3842   case X86ISD::MOVHLPS:
3843   case X86ISD::MOVLPS:
3844   case X86ISD::MOVLPD:
3845   case X86ISD::MOVSS:
3846   case X86ISD::MOVSD:
3847   case X86ISD::UNPCKL:
3848   case X86ISD::UNPCKH:
3849     return DAG.getNode(Opc, dl, VT, V1, V2);
3850   }
3851 }
3852
3853 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3854   MachineFunction &MF = DAG.getMachineFunction();
3855   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3856   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3857   int ReturnAddrIndex = FuncInfo->getRAIndex();
3858
3859   if (ReturnAddrIndex == 0) {
3860     // Set up a frame object for the return address.
3861     unsigned SlotSize = RegInfo->getSlotSize();
3862     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3863                                                            -(int64_t)SlotSize,
3864                                                            false);
3865     FuncInfo->setRAIndex(ReturnAddrIndex);
3866   }
3867
3868   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3869 }
3870
3871 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3872                                        bool hasSymbolicDisplacement) {
3873   // Offset should fit into 32 bit immediate field.
3874   if (!isInt<32>(Offset))
3875     return false;
3876
3877   // If we don't have a symbolic displacement - we don't have any extra
3878   // restrictions.
3879   if (!hasSymbolicDisplacement)
3880     return true;
3881
3882   // FIXME: Some tweaks might be needed for medium code model.
3883   if (M != CodeModel::Small && M != CodeModel::Kernel)
3884     return false;
3885
3886   // For small code model we assume that latest object is 16MB before end of 31
3887   // bits boundary. We may also accept pretty large negative constants knowing
3888   // that all objects are in the positive half of address space.
3889   if (M == CodeModel::Small && Offset < 16*1024*1024)
3890     return true;
3891
3892   // For kernel code model we know that all object resist in the negative half
3893   // of 32bits address space. We may not accept negative offsets, since they may
3894   // be just off and we may accept pretty large positive ones.
3895   if (M == CodeModel::Kernel && Offset >= 0)
3896     return true;
3897
3898   return false;
3899 }
3900
3901 /// Determines whether the callee is required to pop its own arguments.
3902 /// Callee pop is necessary to support tail calls.
3903 bool X86::isCalleePop(CallingConv::ID CallingConv,
3904                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3905
3906   if (IsTailCallConvention(CallingConv))
3907     return IsVarArg ? false : TailCallOpt;
3908
3909   switch (CallingConv) {
3910   default:
3911     return false;
3912   case CallingConv::X86_StdCall:
3913   case CallingConv::X86_FastCall:
3914   case CallingConv::X86_ThisCall:
3915     return !is64Bit;
3916   }
3917 }
3918
3919 /// \brief Return true if the condition is an unsigned comparison operation.
3920 static bool isX86CCUnsigned(unsigned X86CC) {
3921   switch (X86CC) {
3922   default: llvm_unreachable("Invalid integer condition!");
3923   case X86::COND_E:     return true;
3924   case X86::COND_G:     return false;
3925   case X86::COND_GE:    return false;
3926   case X86::COND_L:     return false;
3927   case X86::COND_LE:    return false;
3928   case X86::COND_NE:    return true;
3929   case X86::COND_B:     return true;
3930   case X86::COND_A:     return true;
3931   case X86::COND_BE:    return true;
3932   case X86::COND_AE:    return true;
3933   }
3934   llvm_unreachable("covered switch fell through?!");
3935 }
3936
3937 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3938 /// condition code, returning the condition code and the LHS/RHS of the
3939 /// comparison to make.
3940 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3941                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3942   if (!isFP) {
3943     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3944       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3945         // X > -1   -> X == 0, jump !sign.
3946         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3947         return X86::COND_NS;
3948       }
3949       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3950         // X < 0   -> X == 0, jump on sign.
3951         return X86::COND_S;
3952       }
3953       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3954         // X < 1   -> X <= 0
3955         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3956         return X86::COND_LE;
3957       }
3958     }
3959
3960     switch (SetCCOpcode) {
3961     default: llvm_unreachable("Invalid integer condition!");
3962     case ISD::SETEQ:  return X86::COND_E;
3963     case ISD::SETGT:  return X86::COND_G;
3964     case ISD::SETGE:  return X86::COND_GE;
3965     case ISD::SETLT:  return X86::COND_L;
3966     case ISD::SETLE:  return X86::COND_LE;
3967     case ISD::SETNE:  return X86::COND_NE;
3968     case ISD::SETULT: return X86::COND_B;
3969     case ISD::SETUGT: return X86::COND_A;
3970     case ISD::SETULE: return X86::COND_BE;
3971     case ISD::SETUGE: return X86::COND_AE;
3972     }
3973   }
3974
3975   // First determine if it is required or is profitable to flip the operands.
3976
3977   // If LHS is a foldable load, but RHS is not, flip the condition.
3978   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3979       !ISD::isNON_EXTLoad(RHS.getNode())) {
3980     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3981     std::swap(LHS, RHS);
3982   }
3983
3984   switch (SetCCOpcode) {
3985   default: break;
3986   case ISD::SETOLT:
3987   case ISD::SETOLE:
3988   case ISD::SETUGT:
3989   case ISD::SETUGE:
3990     std::swap(LHS, RHS);
3991     break;
3992   }
3993
3994   // On a floating point condition, the flags are set as follows:
3995   // ZF  PF  CF   op
3996   //  0 | 0 | 0 | X > Y
3997   //  0 | 0 | 1 | X < Y
3998   //  1 | 0 | 0 | X == Y
3999   //  1 | 1 | 1 | unordered
4000   switch (SetCCOpcode) {
4001   default: llvm_unreachable("Condcode should be pre-legalized away");
4002   case ISD::SETUEQ:
4003   case ISD::SETEQ:   return X86::COND_E;
4004   case ISD::SETOLT:              // flipped
4005   case ISD::SETOGT:
4006   case ISD::SETGT:   return X86::COND_A;
4007   case ISD::SETOLE:              // flipped
4008   case ISD::SETOGE:
4009   case ISD::SETGE:   return X86::COND_AE;
4010   case ISD::SETUGT:              // flipped
4011   case ISD::SETULT:
4012   case ISD::SETLT:   return X86::COND_B;
4013   case ISD::SETUGE:              // flipped
4014   case ISD::SETULE:
4015   case ISD::SETLE:   return X86::COND_BE;
4016   case ISD::SETONE:
4017   case ISD::SETNE:   return X86::COND_NE;
4018   case ISD::SETUO:   return X86::COND_P;
4019   case ISD::SETO:    return X86::COND_NP;
4020   case ISD::SETOEQ:
4021   case ISD::SETUNE:  return X86::COND_INVALID;
4022   }
4023 }
4024
4025 /// Is there a floating point cmov for the specific X86 condition code?
4026 /// Current x86 isa includes the following FP cmov instructions:
4027 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4028 static bool hasFPCMov(unsigned X86CC) {
4029   switch (X86CC) {
4030   default:
4031     return false;
4032   case X86::COND_B:
4033   case X86::COND_BE:
4034   case X86::COND_E:
4035   case X86::COND_P:
4036   case X86::COND_A:
4037   case X86::COND_AE:
4038   case X86::COND_NE:
4039   case X86::COND_NP:
4040     return true;
4041   }
4042 }
4043
4044 /// Returns true if the target can instruction select the
4045 /// specified FP immediate natively. If false, the legalizer will
4046 /// materialize the FP immediate as a load from a constant pool.
4047 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4048   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4049     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4050       return true;
4051   }
4052   return false;
4053 }
4054
4055 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4056                                               ISD::LoadExtType ExtTy,
4057                                               EVT NewVT) const {
4058   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4059   // relocation target a movq or addq instruction: don't let the load shrink.
4060   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4061   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4062     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4063       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4064   return true;
4065 }
4066
4067 /// \brief Returns true if it is beneficial to convert a load of a constant
4068 /// to just the constant itself.
4069 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4070                                                           Type *Ty) const {
4071   assert(Ty->isIntegerTy());
4072
4073   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4074   if (BitSize == 0 || BitSize > 64)
4075     return false;
4076   return true;
4077 }
4078
4079 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4080                                                 unsigned Index) const {
4081   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4082     return false;
4083
4084   return (Index == 0 || Index == ResVT.getVectorNumElements());
4085 }
4086
4087 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4088   // Speculate cttz only if we can directly use TZCNT.
4089   return Subtarget->hasBMI();
4090 }
4091
4092 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4093   // Speculate ctlz only if we can directly use LZCNT.
4094   return Subtarget->hasLZCNT();
4095 }
4096
4097 /// Return true if every element in Mask, beginning
4098 /// from position Pos and ending in Pos+Size is undef.
4099 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4100   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4101     if (0 <= Mask[i])
4102       return false;
4103   return true;
4104 }
4105
4106 /// Return true if Val is undef or if its value falls within the
4107 /// specified range (L, H].
4108 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4109   return (Val < 0) || (Val >= Low && Val < Hi);
4110 }
4111
4112 /// Val is either less than zero (undef) or equal to the specified value.
4113 static bool isUndefOrEqual(int Val, int CmpVal) {
4114   return (Val < 0 || Val == CmpVal);
4115 }
4116
4117 /// Return true if every element in Mask, beginning
4118 /// from position Pos and ending in Pos+Size, falls within the specified
4119 /// sequential range (Low, Low+Size]. or is undef.
4120 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4121                                        unsigned Pos, unsigned Size, int Low) {
4122   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4123     if (!isUndefOrEqual(Mask[i], Low))
4124       return false;
4125   return true;
4126 }
4127
4128 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4129 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4130 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4131   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4132   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4133     return false;
4134
4135   // The index should be aligned on a vecWidth-bit boundary.
4136   uint64_t Index =
4137     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4138
4139   MVT VT = N->getSimpleValueType(0);
4140   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4141   bool Result = (Index * ElSize) % vecWidth == 0;
4142
4143   return Result;
4144 }
4145
4146 /// Return true if the specified INSERT_SUBVECTOR
4147 /// operand specifies a subvector insert that is suitable for input to
4148 /// insertion of 128 or 256-bit subvectors
4149 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4150   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4151   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4152     return false;
4153   // The index should be aligned on a vecWidth-bit boundary.
4154   uint64_t Index =
4155     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4156
4157   MVT VT = N->getSimpleValueType(0);
4158   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4159   bool Result = (Index * ElSize) % vecWidth == 0;
4160
4161   return Result;
4162 }
4163
4164 bool X86::isVINSERT128Index(SDNode *N) {
4165   return isVINSERTIndex(N, 128);
4166 }
4167
4168 bool X86::isVINSERT256Index(SDNode *N) {
4169   return isVINSERTIndex(N, 256);
4170 }
4171
4172 bool X86::isVEXTRACT128Index(SDNode *N) {
4173   return isVEXTRACTIndex(N, 128);
4174 }
4175
4176 bool X86::isVEXTRACT256Index(SDNode *N) {
4177   return isVEXTRACTIndex(N, 256);
4178 }
4179
4180 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4181   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4182   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4183     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4184
4185   uint64_t Index =
4186     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4187
4188   MVT VecVT = N->getOperand(0).getSimpleValueType();
4189   MVT ElVT = VecVT.getVectorElementType();
4190
4191   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4192   return Index / NumElemsPerChunk;
4193 }
4194
4195 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4196   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4197   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4198     llvm_unreachable("Illegal insert subvector for VINSERT");
4199
4200   uint64_t Index =
4201     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4202
4203   MVT VecVT = N->getSimpleValueType(0);
4204   MVT ElVT = VecVT.getVectorElementType();
4205
4206   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4207   return Index / NumElemsPerChunk;
4208 }
4209
4210 /// Return the appropriate immediate to extract the specified
4211 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4212 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4213   return getExtractVEXTRACTImmediate(N, 128);
4214 }
4215
4216 /// Return the appropriate immediate to extract the specified
4217 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4218 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4219   return getExtractVEXTRACTImmediate(N, 256);
4220 }
4221
4222 /// Return the appropriate immediate to insert at the specified
4223 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4224 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4225   return getInsertVINSERTImmediate(N, 128);
4226 }
4227
4228 /// Return the appropriate immediate to insert at the specified
4229 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4230 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4231   return getInsertVINSERTImmediate(N, 256);
4232 }
4233
4234 /// Returns true if V is a constant integer zero.
4235 static bool isZero(SDValue V) {
4236   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4237   return C && C->isNullValue();
4238 }
4239
4240 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4241 bool X86::isZeroNode(SDValue Elt) {
4242   if (isZero(Elt))
4243     return true;
4244   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4245     return CFP->getValueAPF().isPosZero();
4246   return false;
4247 }
4248
4249 // Build a vector of constants
4250 // Use an UNDEF node if MaskElt == -1.
4251 // Spilt 64-bit constants in the 32-bit mode.
4252 static SDValue getConstVector(ArrayRef<int> Values, EVT VT,
4253                               SelectionDAG &DAG,
4254                               SDLoc dl, bool IsMask = false) {
4255
4256   SmallVector<SDValue, 32>  Ops;
4257   bool Split = false;
4258
4259   EVT ConstVecVT = VT;
4260   unsigned NumElts = VT.getVectorNumElements();
4261   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4262   if (!In64BitMode && VT.getScalarType() == MVT::i64) {
4263     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4264     Split = true;
4265   }
4266
4267   EVT EltVT = ConstVecVT.getScalarType();
4268   for (unsigned i = 0; i < NumElts; ++i) {
4269     bool IsUndef = Values[i] < 0 && IsMask;
4270     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4271       DAG.getConstant(Values[i], dl, EltVT);
4272     Ops.push_back(OpNode);
4273     if (Split)
4274       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4275                     DAG.getConstant(0, dl, EltVT));
4276   }
4277   SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4278   if (Split)
4279     ConstsNode = DAG.getBitcast(VT, ConstsNode);
4280   return ConstsNode;
4281 }
4282
4283 /// Returns a vector of specified type with all zero elements.
4284 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4285                              SelectionDAG &DAG, SDLoc dl) {
4286   assert(VT.isVector() && "Expected a vector type");
4287
4288   // Always build SSE zero vectors as <4 x i32> bitcasted
4289   // to their dest type. This ensures they get CSE'd.
4290   SDValue Vec;
4291   if (VT.is128BitVector()) {  // SSE
4292     if (Subtarget->hasSSE2()) {  // SSE2
4293       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4294       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4295     } else { // SSE1
4296       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4297       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4298     }
4299   } else if (VT.is256BitVector()) { // AVX
4300     if (Subtarget->hasInt256()) { // AVX2
4301       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4302       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4303       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4304     } else {
4305       // 256-bit logic and arithmetic instructions in AVX are all
4306       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4307       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4308       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4309       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4310     }
4311   } else if (VT.is512BitVector()) { // AVX-512
4312       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4313       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4314                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4315       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4316   } else if (VT.getScalarType() == MVT::i1) {
4317
4318     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4319             && "Unexpected vector type");
4320     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4321             && "Unexpected vector type");
4322     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4323     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4324     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4325   } else
4326     llvm_unreachable("Unexpected vector type");
4327
4328   return DAG.getBitcast(VT, Vec);
4329 }
4330
4331 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4332                                 SelectionDAG &DAG, SDLoc dl,
4333                                 unsigned vectorWidth) {
4334   assert((vectorWidth == 128 || vectorWidth == 256) &&
4335          "Unsupported vector width");
4336   EVT VT = Vec.getValueType();
4337   EVT ElVT = VT.getVectorElementType();
4338   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4339   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4340                                   VT.getVectorNumElements()/Factor);
4341
4342   // Extract from UNDEF is UNDEF.
4343   if (Vec.getOpcode() == ISD::UNDEF)
4344     return DAG.getUNDEF(ResultVT);
4345
4346   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4347   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4348
4349   // This is the index of the first element of the vectorWidth-bit chunk
4350   // we want.
4351   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4352                                * ElemsPerChunk);
4353
4354   // If the input is a buildvector just emit a smaller one.
4355   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4356     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4357                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4358                                     ElemsPerChunk));
4359
4360   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4361   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4362 }
4363
4364 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4365 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4366 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4367 /// instructions or a simple subregister reference. Idx is an index in the
4368 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4369 /// lowering EXTRACT_VECTOR_ELT operations easier.
4370 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4371                                    SelectionDAG &DAG, SDLoc dl) {
4372   assert((Vec.getValueType().is256BitVector() ||
4373           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4374   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4375 }
4376
4377 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4378 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4379                                    SelectionDAG &DAG, SDLoc dl) {
4380   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4381   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4382 }
4383
4384 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4385                                unsigned IdxVal, SelectionDAG &DAG,
4386                                SDLoc dl, unsigned vectorWidth) {
4387   assert((vectorWidth == 128 || vectorWidth == 256) &&
4388          "Unsupported vector width");
4389   // Inserting UNDEF is Result
4390   if (Vec.getOpcode() == ISD::UNDEF)
4391     return Result;
4392   EVT VT = Vec.getValueType();
4393   EVT ElVT = VT.getVectorElementType();
4394   EVT ResultVT = Result.getValueType();
4395
4396   // Insert the relevant vectorWidth bits.
4397   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4398
4399   // This is the index of the first element of the vectorWidth-bit chunk
4400   // we want.
4401   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4402                                * ElemsPerChunk);
4403
4404   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4405   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4406 }
4407
4408 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4409 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4410 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4411 /// simple superregister reference.  Idx is an index in the 128 bits
4412 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4413 /// lowering INSERT_VECTOR_ELT operations easier.
4414 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4415                                   SelectionDAG &DAG, SDLoc dl) {
4416   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4417
4418   // For insertion into the zero index (low half) of a 256-bit vector, it is
4419   // more efficient to generate a blend with immediate instead of an insert*128.
4420   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4421   // extend the subvector to the size of the result vector. Make sure that
4422   // we are not recursing on that node by checking for undef here.
4423   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4424       Result.getOpcode() != ISD::UNDEF) {
4425     EVT ResultVT = Result.getValueType();
4426     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4427     SDValue Undef = DAG.getUNDEF(ResultVT);
4428     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4429                                  Vec, ZeroIndex);
4430
4431     // The blend instruction, and therefore its mask, depend on the data type.
4432     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4433     if (ScalarType.isFloatingPoint()) {
4434       // Choose either vblendps (float) or vblendpd (double).
4435       unsigned ScalarSize = ScalarType.getSizeInBits();
4436       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4437       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4438       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4439       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4440     }
4441
4442     const X86Subtarget &Subtarget =
4443     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4444
4445     // AVX2 is needed for 256-bit integer blend support.
4446     // Integers must be cast to 32-bit because there is only vpblendd;
4447     // vpblendw can't be used for this because it has a handicapped mask.
4448
4449     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4450     // is still more efficient than using the wrong domain vinsertf128 that
4451     // will be created by InsertSubVector().
4452     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4453
4454     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4455     Vec256 = DAG.getBitcast(CastVT, Vec256);
4456     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4457     return DAG.getBitcast(ResultVT, Vec256);
4458   }
4459
4460   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4461 }
4462
4463 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4464                                   SelectionDAG &DAG, SDLoc dl) {
4465   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4466   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4467 }
4468
4469 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4470 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4471 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4472 /// large BUILD_VECTORS.
4473 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4474                                    unsigned NumElems, SelectionDAG &DAG,
4475                                    SDLoc dl) {
4476   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4477   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4478 }
4479
4480 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4481                                    unsigned NumElems, SelectionDAG &DAG,
4482                                    SDLoc dl) {
4483   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4484   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4485 }
4486
4487 /// Returns a vector of specified type with all bits set.
4488 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4489 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4490 /// Then bitcast to their original type, ensuring they get CSE'd.
4491 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4492                              SelectionDAG &DAG, SDLoc dl) {
4493   assert(VT.isVector() && "Expected a vector type");
4494
4495   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4496   SDValue Vec;
4497   if (VT.is512BitVector()) {
4498     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4499                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4500     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4501   } else if (VT.is256BitVector()) {
4502     if (Subtarget->hasInt256()) { // AVX2
4503       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4504       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4505     } else { // AVX
4506       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4507       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4508     }
4509   } else if (VT.is128BitVector()) {
4510     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4511   } else
4512     llvm_unreachable("Unexpected vector type");
4513
4514   return DAG.getBitcast(VT, Vec);
4515 }
4516
4517 /// Returns a vector_shuffle node for an unpackl operation.
4518 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4519                           SDValue V2) {
4520   unsigned NumElems = VT.getVectorNumElements();
4521   SmallVector<int, 8> Mask;
4522   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4523     Mask.push_back(i);
4524     Mask.push_back(i + NumElems);
4525   }
4526   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4527 }
4528
4529 /// Returns a vector_shuffle node for an unpackh operation.
4530 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4531                           SDValue V2) {
4532   unsigned NumElems = VT.getVectorNumElements();
4533   SmallVector<int, 8> Mask;
4534   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4535     Mask.push_back(i + Half);
4536     Mask.push_back(i + NumElems + Half);
4537   }
4538   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4539 }
4540
4541 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4542 /// This produces a shuffle where the low element of V2 is swizzled into the
4543 /// zero/undef vector, landing at element Idx.
4544 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4545 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4546                                            bool IsZero,
4547                                            const X86Subtarget *Subtarget,
4548                                            SelectionDAG &DAG) {
4549   MVT VT = V2.getSimpleValueType();
4550   SDValue V1 = IsZero
4551     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4552   unsigned NumElems = VT.getVectorNumElements();
4553   SmallVector<int, 16> MaskVec;
4554   for (unsigned i = 0; i != NumElems; ++i)
4555     // If this is the insertion idx, put the low elt of V2 here.
4556     MaskVec.push_back(i == Idx ? NumElems : i);
4557   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4558 }
4559
4560 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4561 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4562 /// uses one source. Note that this will set IsUnary for shuffles which use a
4563 /// single input multiple times, and in those cases it will
4564 /// adjust the mask to only have indices within that single input.
4565 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4566 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4567                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4568   unsigned NumElems = VT.getVectorNumElements();
4569   SDValue ImmN;
4570
4571   IsUnary = false;
4572   bool IsFakeUnary = false;
4573   switch(N->getOpcode()) {
4574   case X86ISD::BLENDI:
4575     ImmN = N->getOperand(N->getNumOperands()-1);
4576     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4577     break;
4578   case X86ISD::SHUFP:
4579     ImmN = N->getOperand(N->getNumOperands()-1);
4580     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4581     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4582     break;
4583   case X86ISD::UNPCKH:
4584     DecodeUNPCKHMask(VT, Mask);
4585     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4586     break;
4587   case X86ISD::UNPCKL:
4588     DecodeUNPCKLMask(VT, Mask);
4589     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4590     break;
4591   case X86ISD::MOVHLPS:
4592     DecodeMOVHLPSMask(NumElems, Mask);
4593     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4594     break;
4595   case X86ISD::MOVLHPS:
4596     DecodeMOVLHPSMask(NumElems, Mask);
4597     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4598     break;
4599   case X86ISD::PALIGNR:
4600     ImmN = N->getOperand(N->getNumOperands()-1);
4601     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4602     break;
4603   case X86ISD::PSHUFD:
4604   case X86ISD::VPERMILPI:
4605     ImmN = N->getOperand(N->getNumOperands()-1);
4606     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4607     IsUnary = true;
4608     break;
4609   case X86ISD::PSHUFHW:
4610     ImmN = N->getOperand(N->getNumOperands()-1);
4611     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4612     IsUnary = true;
4613     break;
4614   case X86ISD::PSHUFLW:
4615     ImmN = N->getOperand(N->getNumOperands()-1);
4616     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4617     IsUnary = true;
4618     break;
4619   case X86ISD::PSHUFB: {
4620     IsUnary = true;
4621     SDValue MaskNode = N->getOperand(1);
4622     while (MaskNode->getOpcode() == ISD::BITCAST)
4623       MaskNode = MaskNode->getOperand(0);
4624
4625     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4626       // If we have a build-vector, then things are easy.
4627       EVT VT = MaskNode.getValueType();
4628       assert(VT.isVector() &&
4629              "Can't produce a non-vector with a build_vector!");
4630       if (!VT.isInteger())
4631         return false;
4632
4633       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4634
4635       SmallVector<uint64_t, 32> RawMask;
4636       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4637         SDValue Op = MaskNode->getOperand(i);
4638         if (Op->getOpcode() == ISD::UNDEF) {
4639           RawMask.push_back((uint64_t)SM_SentinelUndef);
4640           continue;
4641         }
4642         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4643         if (!CN)
4644           return false;
4645         APInt MaskElement = CN->getAPIntValue();
4646
4647         // We now have to decode the element which could be any integer size and
4648         // extract each byte of it.
4649         for (int j = 0; j < NumBytesPerElement; ++j) {
4650           // Note that this is x86 and so always little endian: the low byte is
4651           // the first byte of the mask.
4652           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4653           MaskElement = MaskElement.lshr(8);
4654         }
4655       }
4656       DecodePSHUFBMask(RawMask, Mask);
4657       break;
4658     }
4659
4660     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4661     if (!MaskLoad)
4662       return false;
4663
4664     SDValue Ptr = MaskLoad->getBasePtr();
4665     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4666         Ptr->getOpcode() == X86ISD::WrapperRIP)
4667       Ptr = Ptr->getOperand(0);
4668
4669     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4670     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4671       return false;
4672
4673     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4674       DecodePSHUFBMask(C, Mask);
4675       if (Mask.empty())
4676         return false;
4677       break;
4678     }
4679
4680     return false;
4681   }
4682   case X86ISD::VPERMI:
4683     ImmN = N->getOperand(N->getNumOperands()-1);
4684     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4685     IsUnary = true;
4686     break;
4687   case X86ISD::MOVSS:
4688   case X86ISD::MOVSD:
4689     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4690     break;
4691   case X86ISD::VPERM2X128:
4692     ImmN = N->getOperand(N->getNumOperands()-1);
4693     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4694     if (Mask.empty()) return false;
4695     // Mask only contains negative index if an element is zero.
4696     if (std::any_of(Mask.begin(), Mask.end(),
4697                     [](int M){ return M == SM_SentinelZero; }))
4698       return false;
4699     break;
4700   case X86ISD::MOVSLDUP:
4701     DecodeMOVSLDUPMask(VT, Mask);
4702     IsUnary = true;
4703     break;
4704   case X86ISD::MOVSHDUP:
4705     DecodeMOVSHDUPMask(VT, Mask);
4706     IsUnary = true;
4707     break;
4708   case X86ISD::MOVDDUP:
4709     DecodeMOVDDUPMask(VT, Mask);
4710     IsUnary = true;
4711     break;
4712   case X86ISD::MOVLHPD:
4713   case X86ISD::MOVLPD:
4714   case X86ISD::MOVLPS:
4715     // Not yet implemented
4716     return false;
4717   case X86ISD::VPERMV: {
4718     IsUnary = true;
4719     SDValue MaskNode = N->getOperand(0);
4720     while (MaskNode->getOpcode() == ISD::BITCAST)
4721       MaskNode = MaskNode->getOperand(0);
4722
4723     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4724     SmallVector<uint64_t, 32> RawMask;
4725     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4726       // If we have a build-vector, then things are easy.
4727       assert(MaskNode.getValueType().isInteger() &&
4728              MaskNode.getValueType().getVectorNumElements() ==
4729              VT.getVectorNumElements());
4730
4731       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4732         SDValue Op = MaskNode->getOperand(i);
4733         if (Op->getOpcode() == ISD::UNDEF)
4734           RawMask.push_back((uint64_t)SM_SentinelUndef);
4735         else if (isa<ConstantSDNode>(Op)) {
4736           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4737           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4738         } else
4739           return false;
4740       }
4741       DecodeVPERMVMask(RawMask, Mask);
4742       break;
4743     }
4744     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4745       unsigned NumEltsInMask = MaskNode->getNumOperands();
4746       MaskNode = MaskNode->getOperand(0);
4747       auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4748       if (CN) {
4749         APInt MaskEltValue = CN->getAPIntValue();
4750         for (unsigned i = 0; i < NumEltsInMask; ++i)
4751           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4752         DecodeVPERMVMask(RawMask, Mask);
4753         break;
4754       }
4755       // It may be a scalar load
4756     }
4757
4758     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4759     if (!MaskLoad)
4760       return false;
4761
4762     SDValue Ptr = MaskLoad->getBasePtr();
4763     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4764         Ptr->getOpcode() == X86ISD::WrapperRIP)
4765       Ptr = Ptr->getOperand(0);
4766
4767     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4768     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4769       return false;
4770
4771     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4772     if (C) {
4773       DecodeVPERMVMask(C, VT, Mask);
4774       if (Mask.empty())
4775         return false;
4776       break;
4777     }
4778     return false;
4779   }
4780   case X86ISD::VPERMV3: {
4781     IsUnary = false;
4782     SDValue MaskNode = N->getOperand(1);
4783     while (MaskNode->getOpcode() == ISD::BITCAST)
4784       MaskNode = MaskNode->getOperand(1);
4785
4786     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4787       // If we have a build-vector, then things are easy.
4788       assert(MaskNode.getValueType().isInteger() &&
4789              MaskNode.getValueType().getVectorNumElements() ==
4790              VT.getVectorNumElements());
4791
4792       SmallVector<uint64_t, 32> RawMask;
4793       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4794
4795       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4796         SDValue Op = MaskNode->getOperand(i);
4797         if (Op->getOpcode() == ISD::UNDEF)
4798           RawMask.push_back((uint64_t)SM_SentinelUndef);
4799         else {
4800           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4801           if (!CN)
4802             return false;
4803           APInt MaskElement = CN->getAPIntValue();
4804           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4805         }
4806       }
4807       DecodeVPERMV3Mask(RawMask, Mask);
4808       break;
4809     }
4810
4811     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4812     if (!MaskLoad)
4813       return false;
4814
4815     SDValue Ptr = MaskLoad->getBasePtr();
4816     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4817         Ptr->getOpcode() == X86ISD::WrapperRIP)
4818       Ptr = Ptr->getOperand(0);
4819
4820     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4821     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4822       return false;
4823
4824     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4825     if (C) {
4826       DecodeVPERMV3Mask(C, VT, Mask);
4827       if (Mask.empty())
4828         return false;
4829       break;
4830     }
4831     return false;
4832   }
4833   default: llvm_unreachable("unknown target shuffle node");
4834   }
4835
4836   // If we have a fake unary shuffle, the shuffle mask is spread across two
4837   // inputs that are actually the same node. Re-map the mask to always point
4838   // into the first input.
4839   if (IsFakeUnary)
4840     for (int &M : Mask)
4841       if (M >= (int)Mask.size())
4842         M -= Mask.size();
4843
4844   return true;
4845 }
4846
4847 /// Returns the scalar element that will make up the ith
4848 /// element of the result of the vector shuffle.
4849 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4850                                    unsigned Depth) {
4851   if (Depth == 6)
4852     return SDValue();  // Limit search depth.
4853
4854   SDValue V = SDValue(N, 0);
4855   EVT VT = V.getValueType();
4856   unsigned Opcode = V.getOpcode();
4857
4858   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4859   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4860     int Elt = SV->getMaskElt(Index);
4861
4862     if (Elt < 0)
4863       return DAG.getUNDEF(VT.getVectorElementType());
4864
4865     unsigned NumElems = VT.getVectorNumElements();
4866     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4867                                          : SV->getOperand(1);
4868     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4869   }
4870
4871   // Recurse into target specific vector shuffles to find scalars.
4872   if (isTargetShuffle(Opcode)) {
4873     MVT ShufVT = V.getSimpleValueType();
4874     unsigned NumElems = ShufVT.getVectorNumElements();
4875     SmallVector<int, 16> ShuffleMask;
4876     bool IsUnary;
4877
4878     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4879       return SDValue();
4880
4881     int Elt = ShuffleMask[Index];
4882     if (Elt < 0)
4883       return DAG.getUNDEF(ShufVT.getVectorElementType());
4884
4885     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4886                                          : N->getOperand(1);
4887     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4888                                Depth+1);
4889   }
4890
4891   // Actual nodes that may contain scalar elements
4892   if (Opcode == ISD::BITCAST) {
4893     V = V.getOperand(0);
4894     EVT SrcVT = V.getValueType();
4895     unsigned NumElems = VT.getVectorNumElements();
4896
4897     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4898       return SDValue();
4899   }
4900
4901   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4902     return (Index == 0) ? V.getOperand(0)
4903                         : DAG.getUNDEF(VT.getVectorElementType());
4904
4905   if (V.getOpcode() == ISD::BUILD_VECTOR)
4906     return V.getOperand(Index);
4907
4908   return SDValue();
4909 }
4910
4911 /// Custom lower build_vector of v16i8.
4912 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4913                                        unsigned NumNonZero, unsigned NumZero,
4914                                        SelectionDAG &DAG,
4915                                        const X86Subtarget* Subtarget,
4916                                        const TargetLowering &TLI) {
4917   if (NumNonZero > 8)
4918     return SDValue();
4919
4920   SDLoc dl(Op);
4921   SDValue V;
4922   bool First = true;
4923
4924   // SSE4.1 - use PINSRB to insert each byte directly.
4925   if (Subtarget->hasSSE41()) {
4926     for (unsigned i = 0; i < 16; ++i) {
4927       bool isNonZero = (NonZeros & (1 << i)) != 0;
4928       if (isNonZero) {
4929         if (First) {
4930           if (NumZero)
4931             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4932           else
4933             V = DAG.getUNDEF(MVT::v16i8);
4934           First = false;
4935         }
4936         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4937                         MVT::v16i8, V, Op.getOperand(i),
4938                         DAG.getIntPtrConstant(i, dl));
4939       }
4940     }
4941
4942     return V;
4943   }
4944
4945   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4946   for (unsigned i = 0; i < 16; ++i) {
4947     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4948     if (ThisIsNonZero && First) {
4949       if (NumZero)
4950         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4951       else
4952         V = DAG.getUNDEF(MVT::v8i16);
4953       First = false;
4954     }
4955
4956     if ((i & 1) != 0) {
4957       SDValue ThisElt, LastElt;
4958       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4959       if (LastIsNonZero) {
4960         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4961                               MVT::i16, Op.getOperand(i-1));
4962       }
4963       if (ThisIsNonZero) {
4964         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4965         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4966                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4967         if (LastIsNonZero)
4968           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4969       } else
4970         ThisElt = LastElt;
4971
4972       if (ThisElt.getNode())
4973         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4974                         DAG.getIntPtrConstant(i/2, dl));
4975     }
4976   }
4977
4978   return DAG.getBitcast(MVT::v16i8, V);
4979 }
4980
4981 /// Custom lower build_vector of v8i16.
4982 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4983                                      unsigned NumNonZero, unsigned NumZero,
4984                                      SelectionDAG &DAG,
4985                                      const X86Subtarget* Subtarget,
4986                                      const TargetLowering &TLI) {
4987   if (NumNonZero > 4)
4988     return SDValue();
4989
4990   SDLoc dl(Op);
4991   SDValue V;
4992   bool First = true;
4993   for (unsigned i = 0; i < 8; ++i) {
4994     bool isNonZero = (NonZeros & (1 << i)) != 0;
4995     if (isNonZero) {
4996       if (First) {
4997         if (NumZero)
4998           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4999         else
5000           V = DAG.getUNDEF(MVT::v8i16);
5001         First = false;
5002       }
5003       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5004                       MVT::v8i16, V, Op.getOperand(i),
5005                       DAG.getIntPtrConstant(i, dl));
5006     }
5007   }
5008
5009   return V;
5010 }
5011
5012 /// Custom lower build_vector of v4i32 or v4f32.
5013 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5014                                      const X86Subtarget *Subtarget,
5015                                      const TargetLowering &TLI) {
5016   // Find all zeroable elements.
5017   std::bitset<4> Zeroable;
5018   for (int i=0; i < 4; ++i) {
5019     SDValue Elt = Op->getOperand(i);
5020     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5021   }
5022   assert(Zeroable.size() - Zeroable.count() > 1 &&
5023          "We expect at least two non-zero elements!");
5024
5025   // We only know how to deal with build_vector nodes where elements are either
5026   // zeroable or extract_vector_elt with constant index.
5027   SDValue FirstNonZero;
5028   unsigned FirstNonZeroIdx;
5029   for (unsigned i=0; i < 4; ++i) {
5030     if (Zeroable[i])
5031       continue;
5032     SDValue Elt = Op->getOperand(i);
5033     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5034         !isa<ConstantSDNode>(Elt.getOperand(1)))
5035       return SDValue();
5036     // Make sure that this node is extracting from a 128-bit vector.
5037     MVT VT = Elt.getOperand(0).getSimpleValueType();
5038     if (!VT.is128BitVector())
5039       return SDValue();
5040     if (!FirstNonZero.getNode()) {
5041       FirstNonZero = Elt;
5042       FirstNonZeroIdx = i;
5043     }
5044   }
5045
5046   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5047   SDValue V1 = FirstNonZero.getOperand(0);
5048   MVT VT = V1.getSimpleValueType();
5049
5050   // See if this build_vector can be lowered as a blend with zero.
5051   SDValue Elt;
5052   unsigned EltMaskIdx, EltIdx;
5053   int Mask[4];
5054   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5055     if (Zeroable[EltIdx]) {
5056       // The zero vector will be on the right hand side.
5057       Mask[EltIdx] = EltIdx+4;
5058       continue;
5059     }
5060
5061     Elt = Op->getOperand(EltIdx);
5062     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5063     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5064     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5065       break;
5066     Mask[EltIdx] = EltIdx;
5067   }
5068
5069   if (EltIdx == 4) {
5070     // Let the shuffle legalizer deal with blend operations.
5071     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5072     if (V1.getSimpleValueType() != VT)
5073       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5074     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5075   }
5076
5077   // See if we can lower this build_vector to a INSERTPS.
5078   if (!Subtarget->hasSSE41())
5079     return SDValue();
5080
5081   SDValue V2 = Elt.getOperand(0);
5082   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5083     V1 = SDValue();
5084
5085   bool CanFold = true;
5086   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5087     if (Zeroable[i])
5088       continue;
5089
5090     SDValue Current = Op->getOperand(i);
5091     SDValue SrcVector = Current->getOperand(0);
5092     if (!V1.getNode())
5093       V1 = SrcVector;
5094     CanFold = SrcVector == V1 &&
5095       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5096   }
5097
5098   if (!CanFold)
5099     return SDValue();
5100
5101   assert(V1.getNode() && "Expected at least two non-zero elements!");
5102   if (V1.getSimpleValueType() != MVT::v4f32)
5103     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5104   if (V2.getSimpleValueType() != MVT::v4f32)
5105     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5106
5107   // Ok, we can emit an INSERTPS instruction.
5108   unsigned ZMask = Zeroable.to_ulong();
5109
5110   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5111   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5112   SDLoc DL(Op);
5113   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5114                                DAG.getIntPtrConstant(InsertPSMask, DL));
5115   return DAG.getBitcast(VT, Result);
5116 }
5117
5118 /// Return a vector logical shift node.
5119 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5120                          unsigned NumBits, SelectionDAG &DAG,
5121                          const TargetLowering &TLI, SDLoc dl) {
5122   assert(VT.is128BitVector() && "Unknown type for VShift");
5123   MVT ShVT = MVT::v2i64;
5124   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5125   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5126   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5127   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5128   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5129   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5130 }
5131
5132 static SDValue
5133 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5134
5135   // Check if the scalar load can be widened into a vector load. And if
5136   // the address is "base + cst" see if the cst can be "absorbed" into
5137   // the shuffle mask.
5138   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5139     SDValue Ptr = LD->getBasePtr();
5140     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5141       return SDValue();
5142     EVT PVT = LD->getValueType(0);
5143     if (PVT != MVT::i32 && PVT != MVT::f32)
5144       return SDValue();
5145
5146     int FI = -1;
5147     int64_t Offset = 0;
5148     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5149       FI = FINode->getIndex();
5150       Offset = 0;
5151     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5152                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5153       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5154       Offset = Ptr.getConstantOperandVal(1);
5155       Ptr = Ptr.getOperand(0);
5156     } else {
5157       return SDValue();
5158     }
5159
5160     // FIXME: 256-bit vector instructions don't require a strict alignment,
5161     // improve this code to support it better.
5162     unsigned RequiredAlign = VT.getSizeInBits()/8;
5163     SDValue Chain = LD->getChain();
5164     // Make sure the stack object alignment is at least 16 or 32.
5165     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5166     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5167       if (MFI->isFixedObjectIndex(FI)) {
5168         // Can't change the alignment. FIXME: It's possible to compute
5169         // the exact stack offset and reference FI + adjust offset instead.
5170         // If someone *really* cares about this. That's the way to implement it.
5171         return SDValue();
5172       } else {
5173         MFI->setObjectAlignment(FI, RequiredAlign);
5174       }
5175     }
5176
5177     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5178     // Ptr + (Offset & ~15).
5179     if (Offset < 0)
5180       return SDValue();
5181     if ((Offset % RequiredAlign) & 3)
5182       return SDValue();
5183     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5184     if (StartOffset) {
5185       SDLoc DL(Ptr);
5186       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5187                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5188     }
5189
5190     int EltNo = (Offset - StartOffset) >> 2;
5191     unsigned NumElems = VT.getVectorNumElements();
5192
5193     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5194     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5195                              LD->getPointerInfo().getWithOffset(StartOffset),
5196                              false, false, false, 0);
5197
5198     SmallVector<int, 8> Mask(NumElems, EltNo);
5199
5200     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5201   }
5202
5203   return SDValue();
5204 }
5205
5206 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5207 /// elements can be replaced by a single large load which has the same value as
5208 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5209 ///
5210 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5211 ///
5212 /// FIXME: we'd also like to handle the case where the last elements are zero
5213 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5214 /// There's even a handy isZeroNode for that purpose.
5215 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5216                                         SDLoc &DL, SelectionDAG &DAG,
5217                                         bool isAfterLegalize) {
5218   unsigned NumElems = Elts.size();
5219
5220   LoadSDNode *LDBase = nullptr;
5221   unsigned LastLoadedElt = -1U;
5222
5223   // For each element in the initializer, see if we've found a load or an undef.
5224   // If we don't find an initial load element, or later load elements are
5225   // non-consecutive, bail out.
5226   for (unsigned i = 0; i < NumElems; ++i) {
5227     SDValue Elt = Elts[i];
5228     // Look through a bitcast.
5229     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5230       Elt = Elt.getOperand(0);
5231     if (!Elt.getNode() ||
5232         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5233       return SDValue();
5234     if (!LDBase) {
5235       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5236         return SDValue();
5237       LDBase = cast<LoadSDNode>(Elt.getNode());
5238       LastLoadedElt = i;
5239       continue;
5240     }
5241     if (Elt.getOpcode() == ISD::UNDEF)
5242       continue;
5243
5244     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5245     EVT LdVT = Elt.getValueType();
5246     // Each loaded element must be the correct fractional portion of the
5247     // requested vector load.
5248     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5249       return SDValue();
5250     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5251       return SDValue();
5252     LastLoadedElt = i;
5253   }
5254
5255   // If we have found an entire vector of loads and undefs, then return a large
5256   // load of the entire vector width starting at the base pointer.  If we found
5257   // consecutive loads for the low half, generate a vzext_load node.
5258   if (LastLoadedElt == NumElems - 1) {
5259     assert(LDBase && "Did not find base load for merging consecutive loads");
5260     EVT EltVT = LDBase->getValueType(0);
5261     // Ensure that the input vector size for the merged loads matches the
5262     // cumulative size of the input elements.
5263     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5264       return SDValue();
5265
5266     if (isAfterLegalize &&
5267         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5268       return SDValue();
5269
5270     SDValue NewLd = SDValue();
5271
5272     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5273                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5274                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5275                         LDBase->getAlignment());
5276
5277     if (LDBase->hasAnyUseOfValue(1)) {
5278       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5279                                      SDValue(LDBase, 1),
5280                                      SDValue(NewLd.getNode(), 1));
5281       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5282       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5283                              SDValue(NewLd.getNode(), 1));
5284     }
5285
5286     return NewLd;
5287   }
5288
5289   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5290   //of a v4i32 / v4f32. It's probably worth generalizing.
5291   EVT EltVT = VT.getVectorElementType();
5292   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5293       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5294     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5295     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5296     SDValue ResNode =
5297         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5298                                 LDBase->getPointerInfo(),
5299                                 LDBase->getAlignment(),
5300                                 false/*isVolatile*/, true/*ReadMem*/,
5301                                 false/*WriteMem*/);
5302
5303     // Make sure the newly-created LOAD is in the same position as LDBase in
5304     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5305     // update uses of LDBase's output chain to use the TokenFactor.
5306     if (LDBase->hasAnyUseOfValue(1)) {
5307       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5308                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5309       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5310       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5311                              SDValue(ResNode.getNode(), 1));
5312     }
5313
5314     return DAG.getBitcast(VT, ResNode);
5315   }
5316   return SDValue();
5317 }
5318
5319 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5320 /// to generate a splat value for the following cases:
5321 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5322 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5323 /// a scalar load, or a constant.
5324 /// The VBROADCAST node is returned when a pattern is found,
5325 /// or SDValue() otherwise.
5326 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5327                                     SelectionDAG &DAG) {
5328   // VBROADCAST requires AVX.
5329   // TODO: Splats could be generated for non-AVX CPUs using SSE
5330   // instructions, but there's less potential gain for only 128-bit vectors.
5331   if (!Subtarget->hasAVX())
5332     return SDValue();
5333
5334   MVT VT = Op.getSimpleValueType();
5335   SDLoc dl(Op);
5336
5337   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5338          "Unsupported vector type for broadcast.");
5339
5340   SDValue Ld;
5341   bool ConstSplatVal;
5342
5343   switch (Op.getOpcode()) {
5344     default:
5345       // Unknown pattern found.
5346       return SDValue();
5347
5348     case ISD::BUILD_VECTOR: {
5349       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5350       BitVector UndefElements;
5351       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5352
5353       // We need a splat of a single value to use broadcast, and it doesn't
5354       // make any sense if the value is only in one element of the vector.
5355       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5356         return SDValue();
5357
5358       Ld = Splat;
5359       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5360                        Ld.getOpcode() == ISD::ConstantFP);
5361
5362       // Make sure that all of the users of a non-constant load are from the
5363       // BUILD_VECTOR node.
5364       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5365         return SDValue();
5366       break;
5367     }
5368
5369     case ISD::VECTOR_SHUFFLE: {
5370       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5371
5372       // Shuffles must have a splat mask where the first element is
5373       // broadcasted.
5374       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5375         return SDValue();
5376
5377       SDValue Sc = Op.getOperand(0);
5378       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5379           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5380
5381         if (!Subtarget->hasInt256())
5382           return SDValue();
5383
5384         // Use the register form of the broadcast instruction available on AVX2.
5385         if (VT.getSizeInBits() >= 256)
5386           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5387         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5388       }
5389
5390       Ld = Sc.getOperand(0);
5391       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5392                        Ld.getOpcode() == ISD::ConstantFP);
5393
5394       // The scalar_to_vector node and the suspected
5395       // load node must have exactly one user.
5396       // Constants may have multiple users.
5397
5398       // AVX-512 has register version of the broadcast
5399       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5400         Ld.getValueType().getSizeInBits() >= 32;
5401       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5402           !hasRegVer))
5403         return SDValue();
5404       break;
5405     }
5406   }
5407
5408   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5409   bool IsGE256 = (VT.getSizeInBits() >= 256);
5410
5411   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5412   // instruction to save 8 or more bytes of constant pool data.
5413   // TODO: If multiple splats are generated to load the same constant,
5414   // it may be detrimental to overall size. There needs to be a way to detect
5415   // that condition to know if this is truly a size win.
5416   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5417
5418   // Handle broadcasting a single constant scalar from the constant pool
5419   // into a vector.
5420   // On Sandybridge (no AVX2), it is still better to load a constant vector
5421   // from the constant pool and not to broadcast it from a scalar.
5422   // But override that restriction when optimizing for size.
5423   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5424   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5425     EVT CVT = Ld.getValueType();
5426     assert(!CVT.isVector() && "Must not broadcast a vector type");
5427
5428     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5429     // For size optimization, also splat v2f64 and v2i64, and for size opt
5430     // with AVX2, also splat i8 and i16.
5431     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5432     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5433         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5434       const Constant *C = nullptr;
5435       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5436         C = CI->getConstantIntValue();
5437       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5438         C = CF->getConstantFPValue();
5439
5440       assert(C && "Invalid constant type");
5441
5442       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5443       SDValue CP =
5444           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5445       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5446       Ld = DAG.getLoad(
5447           CVT, dl, DAG.getEntryNode(), CP,
5448           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5449           false, false, Alignment);
5450
5451       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5452     }
5453   }
5454
5455   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5456
5457   // Handle AVX2 in-register broadcasts.
5458   if (!IsLoad && Subtarget->hasInt256() &&
5459       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5460     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5461
5462   // The scalar source must be a normal load.
5463   if (!IsLoad)
5464     return SDValue();
5465
5466   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5467       (Subtarget->hasVLX() && ScalarSize == 64))
5468     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5469
5470   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5471   // double since there is no vbroadcastsd xmm
5472   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5473     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5474       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5475   }
5476
5477   // Unsupported broadcast.
5478   return SDValue();
5479 }
5480
5481 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5482 /// underlying vector and index.
5483 ///
5484 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5485 /// index.
5486 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5487                                          SDValue ExtIdx) {
5488   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5489   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5490     return Idx;
5491
5492   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5493   // lowered this:
5494   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5495   // to:
5496   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5497   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5498   //                           undef)
5499   //                       Constant<0>)
5500   // In this case the vector is the extract_subvector expression and the index
5501   // is 2, as specified by the shuffle.
5502   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5503   SDValue ShuffleVec = SVOp->getOperand(0);
5504   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5505   assert(ShuffleVecVT.getVectorElementType() ==
5506          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5507
5508   int ShuffleIdx = SVOp->getMaskElt(Idx);
5509   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5510     ExtractedFromVec = ShuffleVec;
5511     return ShuffleIdx;
5512   }
5513   return Idx;
5514 }
5515
5516 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5517   MVT VT = Op.getSimpleValueType();
5518
5519   // Skip if insert_vec_elt is not supported.
5520   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5521   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5522     return SDValue();
5523
5524   SDLoc DL(Op);
5525   unsigned NumElems = Op.getNumOperands();
5526
5527   SDValue VecIn1;
5528   SDValue VecIn2;
5529   SmallVector<unsigned, 4> InsertIndices;
5530   SmallVector<int, 8> Mask(NumElems, -1);
5531
5532   for (unsigned i = 0; i != NumElems; ++i) {
5533     unsigned Opc = Op.getOperand(i).getOpcode();
5534
5535     if (Opc == ISD::UNDEF)
5536       continue;
5537
5538     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5539       // Quit if more than 1 elements need inserting.
5540       if (InsertIndices.size() > 1)
5541         return SDValue();
5542
5543       InsertIndices.push_back(i);
5544       continue;
5545     }
5546
5547     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5548     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5549     // Quit if non-constant index.
5550     if (!isa<ConstantSDNode>(ExtIdx))
5551       return SDValue();
5552     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5553
5554     // Quit if extracted from vector of different type.
5555     if (ExtractedFromVec.getValueType() != VT)
5556       return SDValue();
5557
5558     if (!VecIn1.getNode())
5559       VecIn1 = ExtractedFromVec;
5560     else if (VecIn1 != ExtractedFromVec) {
5561       if (!VecIn2.getNode())
5562         VecIn2 = ExtractedFromVec;
5563       else if (VecIn2 != ExtractedFromVec)
5564         // Quit if more than 2 vectors to shuffle
5565         return SDValue();
5566     }
5567
5568     if (ExtractedFromVec == VecIn1)
5569       Mask[i] = Idx;
5570     else if (ExtractedFromVec == VecIn2)
5571       Mask[i] = Idx + NumElems;
5572   }
5573
5574   if (!VecIn1.getNode())
5575     return SDValue();
5576
5577   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5578   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5579   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5580     unsigned Idx = InsertIndices[i];
5581     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5582                      DAG.getIntPtrConstant(Idx, DL));
5583   }
5584
5585   return NV;
5586 }
5587
5588 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5589   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5590          Op.getScalarValueSizeInBits() == 1 &&
5591          "Can not convert non-constant vector");
5592   uint64_t Immediate = 0;
5593   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5594     SDValue In = Op.getOperand(idx);
5595     if (In.getOpcode() != ISD::UNDEF)
5596       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5597   }
5598   SDLoc dl(Op);
5599   MVT VT =
5600    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5601   return DAG.getConstant(Immediate, dl, VT);
5602 }
5603 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5604 SDValue
5605 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5606
5607   MVT VT = Op.getSimpleValueType();
5608   assert((VT.getVectorElementType() == MVT::i1) &&
5609          "Unexpected type in LowerBUILD_VECTORvXi1!");
5610
5611   SDLoc dl(Op);
5612   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5613     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5614     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5615     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5616   }
5617
5618   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5619     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5620     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5621     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5622   }
5623
5624   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5625     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5626     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5627       return DAG.getBitcast(VT, Imm);
5628     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5629     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5630                         DAG.getIntPtrConstant(0, dl));
5631   }
5632
5633   // Vector has one or more non-const elements
5634   uint64_t Immediate = 0;
5635   SmallVector<unsigned, 16> NonConstIdx;
5636   bool IsSplat = true;
5637   bool HasConstElts = false;
5638   int SplatIdx = -1;
5639   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5640     SDValue In = Op.getOperand(idx);
5641     if (In.getOpcode() == ISD::UNDEF)
5642       continue;
5643     if (!isa<ConstantSDNode>(In))
5644       NonConstIdx.push_back(idx);
5645     else {
5646       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5647       HasConstElts = true;
5648     }
5649     if (SplatIdx == -1)
5650       SplatIdx = idx;
5651     else if (In != Op.getOperand(SplatIdx))
5652       IsSplat = false;
5653   }
5654
5655   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5656   if (IsSplat)
5657     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5658                        DAG.getConstant(1, dl, VT),
5659                        DAG.getConstant(0, dl, VT));
5660
5661   // insert elements one by one
5662   SDValue DstVec;
5663   SDValue Imm;
5664   if (Immediate) {
5665     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5666     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5667   }
5668   else if (HasConstElts)
5669     Imm = DAG.getConstant(0, dl, VT);
5670   else
5671     Imm = DAG.getUNDEF(VT);
5672   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5673     DstVec = DAG.getBitcast(VT, Imm);
5674   else {
5675     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5676     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5677                          DAG.getIntPtrConstant(0, dl));
5678   }
5679
5680   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5681     unsigned InsertIdx = NonConstIdx[i];
5682     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5683                          Op.getOperand(InsertIdx),
5684                          DAG.getIntPtrConstant(InsertIdx, dl));
5685   }
5686   return DstVec;
5687 }
5688
5689 /// \brief Return true if \p N implements a horizontal binop and return the
5690 /// operands for the horizontal binop into V0 and V1.
5691 ///
5692 /// This is a helper function of LowerToHorizontalOp().
5693 /// This function checks that the build_vector \p N in input implements a
5694 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5695 /// operation to match.
5696 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5697 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5698 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5699 /// arithmetic sub.
5700 ///
5701 /// This function only analyzes elements of \p N whose indices are
5702 /// in range [BaseIdx, LastIdx).
5703 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5704                               SelectionDAG &DAG,
5705                               unsigned BaseIdx, unsigned LastIdx,
5706                               SDValue &V0, SDValue &V1) {
5707   EVT VT = N->getValueType(0);
5708
5709   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5710   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5711          "Invalid Vector in input!");
5712
5713   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5714   bool CanFold = true;
5715   unsigned ExpectedVExtractIdx = BaseIdx;
5716   unsigned NumElts = LastIdx - BaseIdx;
5717   V0 = DAG.getUNDEF(VT);
5718   V1 = DAG.getUNDEF(VT);
5719
5720   // Check if N implements a horizontal binop.
5721   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5722     SDValue Op = N->getOperand(i + BaseIdx);
5723
5724     // Skip UNDEFs.
5725     if (Op->getOpcode() == ISD::UNDEF) {
5726       // Update the expected vector extract index.
5727       if (i * 2 == NumElts)
5728         ExpectedVExtractIdx = BaseIdx;
5729       ExpectedVExtractIdx += 2;
5730       continue;
5731     }
5732
5733     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5734
5735     if (!CanFold)
5736       break;
5737
5738     SDValue Op0 = Op.getOperand(0);
5739     SDValue Op1 = Op.getOperand(1);
5740
5741     // Try to match the following pattern:
5742     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5743     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5744         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5745         Op0.getOperand(0) == Op1.getOperand(0) &&
5746         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5747         isa<ConstantSDNode>(Op1.getOperand(1)));
5748     if (!CanFold)
5749       break;
5750
5751     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5752     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5753
5754     if (i * 2 < NumElts) {
5755       if (V0.getOpcode() == ISD::UNDEF) {
5756         V0 = Op0.getOperand(0);
5757         if (V0.getValueType() != VT)
5758           return false;
5759       }
5760     } else {
5761       if (V1.getOpcode() == ISD::UNDEF) {
5762         V1 = Op0.getOperand(0);
5763         if (V1.getValueType() != VT)
5764           return false;
5765       }
5766       if (i * 2 == NumElts)
5767         ExpectedVExtractIdx = BaseIdx;
5768     }
5769
5770     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5771     if (I0 == ExpectedVExtractIdx)
5772       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5773     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5774       // Try to match the following dag sequence:
5775       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5776       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5777     } else
5778       CanFold = false;
5779
5780     ExpectedVExtractIdx += 2;
5781   }
5782
5783   return CanFold;
5784 }
5785
5786 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5787 /// a concat_vector.
5788 ///
5789 /// This is a helper function of LowerToHorizontalOp().
5790 /// This function expects two 256-bit vectors called V0 and V1.
5791 /// At first, each vector is split into two separate 128-bit vectors.
5792 /// Then, the resulting 128-bit vectors are used to implement two
5793 /// horizontal binary operations.
5794 ///
5795 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5796 ///
5797 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5798 /// the two new horizontal binop.
5799 /// When Mode is set, the first horizontal binop dag node would take as input
5800 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5801 /// horizontal binop dag node would take as input the lower 128-bit of V1
5802 /// and the upper 128-bit of V1.
5803 ///   Example:
5804 ///     HADD V0_LO, V0_HI
5805 ///     HADD V1_LO, V1_HI
5806 ///
5807 /// Otherwise, the first horizontal binop dag node takes as input the lower
5808 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5809 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5810 ///   Example:
5811 ///     HADD V0_LO, V1_LO
5812 ///     HADD V0_HI, V1_HI
5813 ///
5814 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5815 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5816 /// the upper 128-bits of the result.
5817 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5818                                      SDLoc DL, SelectionDAG &DAG,
5819                                      unsigned X86Opcode, bool Mode,
5820                                      bool isUndefLO, bool isUndefHI) {
5821   EVT VT = V0.getValueType();
5822   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5823          "Invalid nodes in input!");
5824
5825   unsigned NumElts = VT.getVectorNumElements();
5826   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5827   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5828   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5829   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5830   EVT NewVT = V0_LO.getValueType();
5831
5832   SDValue LO = DAG.getUNDEF(NewVT);
5833   SDValue HI = DAG.getUNDEF(NewVT);
5834
5835   if (Mode) {
5836     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5837     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5838       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5839     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5840       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5841   } else {
5842     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5843     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5844                        V1_LO->getOpcode() != ISD::UNDEF))
5845       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5846
5847     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5848                        V1_HI->getOpcode() != ISD::UNDEF))
5849       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5850   }
5851
5852   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5853 }
5854
5855 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5856 /// node.
5857 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5858                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5859   EVT VT = BV->getValueType(0);
5860   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5861       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5862     return SDValue();
5863
5864   SDLoc DL(BV);
5865   unsigned NumElts = VT.getVectorNumElements();
5866   SDValue InVec0 = DAG.getUNDEF(VT);
5867   SDValue InVec1 = DAG.getUNDEF(VT);
5868
5869   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5870           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5871
5872   // Odd-numbered elements in the input build vector are obtained from
5873   // adding two integer/float elements.
5874   // Even-numbered elements in the input build vector are obtained from
5875   // subtracting two integer/float elements.
5876   unsigned ExpectedOpcode = ISD::FSUB;
5877   unsigned NextExpectedOpcode = ISD::FADD;
5878   bool AddFound = false;
5879   bool SubFound = false;
5880
5881   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5882     SDValue Op = BV->getOperand(i);
5883
5884     // Skip 'undef' values.
5885     unsigned Opcode = Op.getOpcode();
5886     if (Opcode == ISD::UNDEF) {
5887       std::swap(ExpectedOpcode, NextExpectedOpcode);
5888       continue;
5889     }
5890
5891     // Early exit if we found an unexpected opcode.
5892     if (Opcode != ExpectedOpcode)
5893       return SDValue();
5894
5895     SDValue Op0 = Op.getOperand(0);
5896     SDValue Op1 = Op.getOperand(1);
5897
5898     // Try to match the following pattern:
5899     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5900     // Early exit if we cannot match that sequence.
5901     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5902         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5903         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5904         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5905         Op0.getOperand(1) != Op1.getOperand(1))
5906       return SDValue();
5907
5908     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5909     if (I0 != i)
5910       return SDValue();
5911
5912     // We found a valid add/sub node. Update the information accordingly.
5913     if (i & 1)
5914       AddFound = true;
5915     else
5916       SubFound = true;
5917
5918     // Update InVec0 and InVec1.
5919     if (InVec0.getOpcode() == ISD::UNDEF) {
5920       InVec0 = Op0.getOperand(0);
5921       if (InVec0.getValueType() != VT)
5922         return SDValue();
5923     }
5924     if (InVec1.getOpcode() == ISD::UNDEF) {
5925       InVec1 = Op1.getOperand(0);
5926       if (InVec1.getValueType() != VT)
5927         return SDValue();
5928     }
5929
5930     // Make sure that operands in input to each add/sub node always
5931     // come from a same pair of vectors.
5932     if (InVec0 != Op0.getOperand(0)) {
5933       if (ExpectedOpcode == ISD::FSUB)
5934         return SDValue();
5935
5936       // FADD is commutable. Try to commute the operands
5937       // and then test again.
5938       std::swap(Op0, Op1);
5939       if (InVec0 != Op0.getOperand(0))
5940         return SDValue();
5941     }
5942
5943     if (InVec1 != Op1.getOperand(0))
5944       return SDValue();
5945
5946     // Update the pair of expected opcodes.
5947     std::swap(ExpectedOpcode, NextExpectedOpcode);
5948   }
5949
5950   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5951   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5952       InVec1.getOpcode() != ISD::UNDEF)
5953     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5954
5955   return SDValue();
5956 }
5957
5958 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5959 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5960                                    const X86Subtarget *Subtarget,
5961                                    SelectionDAG &DAG) {
5962   EVT VT = BV->getValueType(0);
5963   unsigned NumElts = VT.getVectorNumElements();
5964   unsigned NumUndefsLO = 0;
5965   unsigned NumUndefsHI = 0;
5966   unsigned Half = NumElts/2;
5967
5968   // Count the number of UNDEF operands in the build_vector in input.
5969   for (unsigned i = 0, e = Half; i != e; ++i)
5970     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5971       NumUndefsLO++;
5972
5973   for (unsigned i = Half, e = NumElts; i != e; ++i)
5974     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5975       NumUndefsHI++;
5976
5977   // Early exit if this is either a build_vector of all UNDEFs or all the
5978   // operands but one are UNDEF.
5979   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5980     return SDValue();
5981
5982   SDLoc DL(BV);
5983   SDValue InVec0, InVec1;
5984   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5985     // Try to match an SSE3 float HADD/HSUB.
5986     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5987       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5988
5989     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5990       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5991   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5992     // Try to match an SSSE3 integer HADD/HSUB.
5993     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5994       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5995
5996     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5997       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5998   }
5999
6000   if (!Subtarget->hasAVX())
6001     return SDValue();
6002
6003   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6004     // Try to match an AVX horizontal add/sub of packed single/double
6005     // precision floating point values from 256-bit vectors.
6006     SDValue InVec2, InVec3;
6007     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6008         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6009         ((InVec0.getOpcode() == ISD::UNDEF ||
6010           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6011         ((InVec1.getOpcode() == ISD::UNDEF ||
6012           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6013       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6014
6015     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6016         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6017         ((InVec0.getOpcode() == ISD::UNDEF ||
6018           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6019         ((InVec1.getOpcode() == ISD::UNDEF ||
6020           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6021       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6022   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6023     // Try to match an AVX2 horizontal add/sub of signed integers.
6024     SDValue InVec2, InVec3;
6025     unsigned X86Opcode;
6026     bool CanFold = true;
6027
6028     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6029         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6030         ((InVec0.getOpcode() == ISD::UNDEF ||
6031           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6032         ((InVec1.getOpcode() == ISD::UNDEF ||
6033           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6034       X86Opcode = X86ISD::HADD;
6035     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6036         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6037         ((InVec0.getOpcode() == ISD::UNDEF ||
6038           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6039         ((InVec1.getOpcode() == ISD::UNDEF ||
6040           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6041       X86Opcode = X86ISD::HSUB;
6042     else
6043       CanFold = false;
6044
6045     if (CanFold) {
6046       // Fold this build_vector into a single horizontal add/sub.
6047       // Do this only if the target has AVX2.
6048       if (Subtarget->hasAVX2())
6049         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6050
6051       // Do not try to expand this build_vector into a pair of horizontal
6052       // add/sub if we can emit a pair of scalar add/sub.
6053       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6054         return SDValue();
6055
6056       // Convert this build_vector into a pair of horizontal binop followed by
6057       // a concat vector.
6058       bool isUndefLO = NumUndefsLO == Half;
6059       bool isUndefHI = NumUndefsHI == Half;
6060       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6061                                    isUndefLO, isUndefHI);
6062     }
6063   }
6064
6065   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6066        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6067     unsigned X86Opcode;
6068     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6069       X86Opcode = X86ISD::HADD;
6070     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6071       X86Opcode = X86ISD::HSUB;
6072     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6073       X86Opcode = X86ISD::FHADD;
6074     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6075       X86Opcode = X86ISD::FHSUB;
6076     else
6077       return SDValue();
6078
6079     // Don't try to expand this build_vector into a pair of horizontal add/sub
6080     // if we can simply emit a pair of scalar add/sub.
6081     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6082       return SDValue();
6083
6084     // Convert this build_vector into two horizontal add/sub followed by
6085     // a concat vector.
6086     bool isUndefLO = NumUndefsLO == Half;
6087     bool isUndefHI = NumUndefsHI == Half;
6088     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6089                                  isUndefLO, isUndefHI);
6090   }
6091
6092   return SDValue();
6093 }
6094
6095 SDValue
6096 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6097   SDLoc dl(Op);
6098
6099   MVT VT = Op.getSimpleValueType();
6100   MVT ExtVT = VT.getVectorElementType();
6101   unsigned NumElems = Op.getNumOperands();
6102
6103   // Generate vectors for predicate vectors.
6104   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6105     return LowerBUILD_VECTORvXi1(Op, DAG);
6106
6107   // Vectors containing all zeros can be matched by pxor and xorps later
6108   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6109     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6110     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6111     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6112       return Op;
6113
6114     return getZeroVector(VT, Subtarget, DAG, dl);
6115   }
6116
6117   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6118   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6119   // vpcmpeqd on 256-bit vectors.
6120   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6121     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6122       return Op;
6123
6124     if (!VT.is512BitVector())
6125       return getOnesVector(VT, Subtarget, DAG, dl);
6126   }
6127
6128   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6129   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6130     return AddSub;
6131   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6132     return HorizontalOp;
6133   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6134     return Broadcast;
6135
6136   unsigned EVTBits = ExtVT.getSizeInBits();
6137
6138   unsigned NumZero  = 0;
6139   unsigned NumNonZero = 0;
6140   unsigned NonZeros = 0;
6141   bool IsAllConstants = true;
6142   SmallSet<SDValue, 8> Values;
6143   for (unsigned i = 0; i < NumElems; ++i) {
6144     SDValue Elt = Op.getOperand(i);
6145     if (Elt.getOpcode() == ISD::UNDEF)
6146       continue;
6147     Values.insert(Elt);
6148     if (Elt.getOpcode() != ISD::Constant &&
6149         Elt.getOpcode() != ISD::ConstantFP)
6150       IsAllConstants = false;
6151     if (X86::isZeroNode(Elt))
6152       NumZero++;
6153     else {
6154       NonZeros |= (1 << i);
6155       NumNonZero++;
6156     }
6157   }
6158
6159   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6160   if (NumNonZero == 0)
6161     return DAG.getUNDEF(VT);
6162
6163   // Special case for single non-zero, non-undef, element.
6164   if (NumNonZero == 1) {
6165     unsigned Idx = countTrailingZeros(NonZeros);
6166     SDValue Item = Op.getOperand(Idx);
6167
6168     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6169     // the value are obviously zero, truncate the value to i32 and do the
6170     // insertion that way.  Only do this if the value is non-constant or if the
6171     // value is a constant being inserted into element 0.  It is cheaper to do
6172     // a constant pool load than it is to do a movd + shuffle.
6173     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6174         (!IsAllConstants || Idx == 0)) {
6175       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6176         // Handle SSE only.
6177         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6178         EVT VecVT = MVT::v4i32;
6179
6180         // Truncate the value (which may itself be a constant) to i32, and
6181         // convert it to a vector with movd (S2V+shuffle to zero extend).
6182         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6183         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6184         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6185                                       Item, Idx * 2, true, Subtarget, DAG));
6186       }
6187     }
6188
6189     // If we have a constant or non-constant insertion into the low element of
6190     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6191     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6192     // depending on what the source datatype is.
6193     if (Idx == 0) {
6194       if (NumZero == 0)
6195         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6196
6197       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6198           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6199         if (VT.is512BitVector()) {
6200           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6201           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6202                              Item, DAG.getIntPtrConstant(0, dl));
6203         }
6204         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6205                "Expected an SSE value type!");
6206         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6207         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6208         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6209       }
6210
6211       // We can't directly insert an i8 or i16 into a vector, so zero extend
6212       // it to i32 first.
6213       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6214         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6215         if (VT.is256BitVector()) {
6216           if (Subtarget->hasAVX()) {
6217             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6218             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6219           } else {
6220             // Without AVX, we need to extend to a 128-bit vector and then
6221             // insert into the 256-bit vector.
6222             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6223             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6224             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6225           }
6226         } else {
6227           assert(VT.is128BitVector() && "Expected an SSE value type!");
6228           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6229           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6230         }
6231         return DAG.getBitcast(VT, Item);
6232       }
6233     }
6234
6235     // Is it a vector logical left shift?
6236     if (NumElems == 2 && Idx == 1 &&
6237         X86::isZeroNode(Op.getOperand(0)) &&
6238         !X86::isZeroNode(Op.getOperand(1))) {
6239       unsigned NumBits = VT.getSizeInBits();
6240       return getVShift(true, VT,
6241                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6242                                    VT, Op.getOperand(1)),
6243                        NumBits/2, DAG, *this, dl);
6244     }
6245
6246     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6247       return SDValue();
6248
6249     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6250     // is a non-constant being inserted into an element other than the low one,
6251     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6252     // movd/movss) to move this into the low element, then shuffle it into
6253     // place.
6254     if (EVTBits == 32) {
6255       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6256       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6257     }
6258   }
6259
6260   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6261   if (Values.size() == 1) {
6262     if (EVTBits == 32) {
6263       // Instead of a shuffle like this:
6264       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6265       // Check if it's possible to issue this instead.
6266       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6267       unsigned Idx = countTrailingZeros(NonZeros);
6268       SDValue Item = Op.getOperand(Idx);
6269       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6270         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6271     }
6272     return SDValue();
6273   }
6274
6275   // A vector full of immediates; various special cases are already
6276   // handled, so this is best done with a single constant-pool load.
6277   if (IsAllConstants)
6278     return SDValue();
6279
6280   // For AVX-length vectors, see if we can use a vector load to get all of the
6281   // elements, otherwise build the individual 128-bit pieces and use
6282   // shuffles to put them in place.
6283   if (VT.is256BitVector() || VT.is512BitVector()) {
6284     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6285
6286     // Check for a build vector of consecutive loads.
6287     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6288       return LD;
6289
6290     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6291
6292     // Build both the lower and upper subvector.
6293     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6294                                 makeArrayRef(&V[0], NumElems/2));
6295     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6296                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6297
6298     // Recreate the wider vector with the lower and upper part.
6299     if (VT.is256BitVector())
6300       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6301     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6302   }
6303
6304   // Let legalizer expand 2-wide build_vectors.
6305   if (EVTBits == 64) {
6306     if (NumNonZero == 1) {
6307       // One half is zero or undef.
6308       unsigned Idx = countTrailingZeros(NonZeros);
6309       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6310                                  Op.getOperand(Idx));
6311       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6312     }
6313     return SDValue();
6314   }
6315
6316   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6317   if (EVTBits == 8 && NumElems == 16)
6318     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6319                                         Subtarget, *this))
6320       return V;
6321
6322   if (EVTBits == 16 && NumElems == 8)
6323     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6324                                       Subtarget, *this))
6325       return V;
6326
6327   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6328   if (EVTBits == 32 && NumElems == 4)
6329     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6330       return V;
6331
6332   // If element VT is == 32 bits, turn it into a number of shuffles.
6333   SmallVector<SDValue, 8> V(NumElems);
6334   if (NumElems == 4 && NumZero > 0) {
6335     for (unsigned i = 0; i < 4; ++i) {
6336       bool isZero = !(NonZeros & (1 << i));
6337       if (isZero)
6338         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6339       else
6340         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6341     }
6342
6343     for (unsigned i = 0; i < 2; ++i) {
6344       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6345         default: break;
6346         case 0:
6347           V[i] = V[i*2];  // Must be a zero vector.
6348           break;
6349         case 1:
6350           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6351           break;
6352         case 2:
6353           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6354           break;
6355         case 3:
6356           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6357           break;
6358       }
6359     }
6360
6361     bool Reverse1 = (NonZeros & 0x3) == 2;
6362     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6363     int MaskVec[] = {
6364       Reverse1 ? 1 : 0,
6365       Reverse1 ? 0 : 1,
6366       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6367       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6368     };
6369     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6370   }
6371
6372   if (Values.size() > 1 && VT.is128BitVector()) {
6373     // Check for a build vector of consecutive loads.
6374     for (unsigned i = 0; i < NumElems; ++i)
6375       V[i] = Op.getOperand(i);
6376
6377     // Check for elements which are consecutive loads.
6378     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6379       return LD;
6380
6381     // Check for a build vector from mostly shuffle plus few inserting.
6382     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6383       return Sh;
6384
6385     // For SSE 4.1, use insertps to put the high elements into the low element.
6386     if (Subtarget->hasSSE41()) {
6387       SDValue Result;
6388       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6389         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6390       else
6391         Result = DAG.getUNDEF(VT);
6392
6393       for (unsigned i = 1; i < NumElems; ++i) {
6394         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6395         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6396                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6397       }
6398       return Result;
6399     }
6400
6401     // Otherwise, expand into a number of unpckl*, start by extending each of
6402     // our (non-undef) elements to the full vector width with the element in the
6403     // bottom slot of the vector (which generates no code for SSE).
6404     for (unsigned i = 0; i < NumElems; ++i) {
6405       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6406         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6407       else
6408         V[i] = DAG.getUNDEF(VT);
6409     }
6410
6411     // Next, we iteratively mix elements, e.g. for v4f32:
6412     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6413     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6414     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6415     unsigned EltStride = NumElems >> 1;
6416     while (EltStride != 0) {
6417       for (unsigned i = 0; i < EltStride; ++i) {
6418         // If V[i+EltStride] is undef and this is the first round of mixing,
6419         // then it is safe to just drop this shuffle: V[i] is already in the
6420         // right place, the one element (since it's the first round) being
6421         // inserted as undef can be dropped.  This isn't safe for successive
6422         // rounds because they will permute elements within both vectors.
6423         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6424             EltStride == NumElems/2)
6425           continue;
6426
6427         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6428       }
6429       EltStride >>= 1;
6430     }
6431     return V[0];
6432   }
6433   return SDValue();
6434 }
6435
6436 // 256-bit AVX can use the vinsertf128 instruction
6437 // to create 256-bit vectors from two other 128-bit ones.
6438 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6439   SDLoc dl(Op);
6440   MVT ResVT = Op.getSimpleValueType();
6441
6442   assert((ResVT.is256BitVector() ||
6443           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6444
6445   SDValue V1 = Op.getOperand(0);
6446   SDValue V2 = Op.getOperand(1);
6447   unsigned NumElems = ResVT.getVectorNumElements();
6448   if (ResVT.is256BitVector())
6449     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6450
6451   if (Op.getNumOperands() == 4) {
6452     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6453                                 ResVT.getVectorNumElements()/2);
6454     SDValue V3 = Op.getOperand(2);
6455     SDValue V4 = Op.getOperand(3);
6456     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6457       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6458   }
6459   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6460 }
6461
6462 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6463                                        const X86Subtarget *Subtarget,
6464                                        SelectionDAG & DAG) {
6465   SDLoc dl(Op);
6466   MVT ResVT = Op.getSimpleValueType();
6467   unsigned NumOfOperands = Op.getNumOperands();
6468
6469   assert(isPowerOf2_32(NumOfOperands) &&
6470          "Unexpected number of operands in CONCAT_VECTORS");
6471
6472   if (NumOfOperands > 2) {
6473     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6474                                   ResVT.getVectorNumElements()/2);
6475     SmallVector<SDValue, 2> Ops;
6476     for (unsigned i = 0; i < NumOfOperands/2; i++)
6477       Ops.push_back(Op.getOperand(i));
6478     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6479     Ops.clear();
6480     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6481       Ops.push_back(Op.getOperand(i));
6482     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6483     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6484   }
6485
6486   SDValue V1 = Op.getOperand(0);
6487   SDValue V2 = Op.getOperand(1);
6488   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6489   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6490
6491   if (IsZeroV1 && IsZeroV2)
6492     return getZeroVector(ResVT, Subtarget, DAG, dl);
6493
6494   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6495   SDValue Undef = DAG.getUNDEF(ResVT);
6496   unsigned NumElems = ResVT.getVectorNumElements();
6497   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6498
6499   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6500   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6501   if (IsZeroV1)
6502     return V2;
6503
6504   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6505   // Zero the upper bits of V1
6506   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6507   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6508   if (IsZeroV2)
6509     return V1;
6510   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6511 }
6512
6513 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6514                                    const X86Subtarget *Subtarget,
6515                                    SelectionDAG &DAG) {
6516   MVT VT = Op.getSimpleValueType();
6517   if (VT.getVectorElementType() == MVT::i1)
6518     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6519
6520   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6521          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6522           Op.getNumOperands() == 4)));
6523
6524   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6525   // from two other 128-bit ones.
6526
6527   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6528   return LowerAVXCONCAT_VECTORS(Op, DAG);
6529 }
6530
6531 //===----------------------------------------------------------------------===//
6532 // Vector shuffle lowering
6533 //
6534 // This is an experimental code path for lowering vector shuffles on x86. It is
6535 // designed to handle arbitrary vector shuffles and blends, gracefully
6536 // degrading performance as necessary. It works hard to recognize idiomatic
6537 // shuffles and lower them to optimal instruction patterns without leaving
6538 // a framework that allows reasonably efficient handling of all vector shuffle
6539 // patterns.
6540 //===----------------------------------------------------------------------===//
6541
6542 /// \brief Tiny helper function to identify a no-op mask.
6543 ///
6544 /// This is a somewhat boring predicate function. It checks whether the mask
6545 /// array input, which is assumed to be a single-input shuffle mask of the kind
6546 /// used by the X86 shuffle instructions (not a fully general
6547 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6548 /// in-place shuffle are 'no-op's.
6549 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6550   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6551     if (Mask[i] != -1 && Mask[i] != i)
6552       return false;
6553   return true;
6554 }
6555
6556 /// \brief Helper function to classify a mask as a single-input mask.
6557 ///
6558 /// This isn't a generic single-input test because in the vector shuffle
6559 /// lowering we canonicalize single inputs to be the first input operand. This
6560 /// means we can more quickly test for a single input by only checking whether
6561 /// an input from the second operand exists. We also assume that the size of
6562 /// mask corresponds to the size of the input vectors which isn't true in the
6563 /// fully general case.
6564 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6565   for (int M : Mask)
6566     if (M >= (int)Mask.size())
6567       return false;
6568   return true;
6569 }
6570
6571 /// \brief Test whether there are elements crossing 128-bit lanes in this
6572 /// shuffle mask.
6573 ///
6574 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6575 /// and we routinely test for these.
6576 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6577   int LaneSize = 128 / VT.getScalarSizeInBits();
6578   int Size = Mask.size();
6579   for (int i = 0; i < Size; ++i)
6580     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6581       return true;
6582   return false;
6583 }
6584
6585 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6586 ///
6587 /// This checks a shuffle mask to see if it is performing the same
6588 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6589 /// that it is also not lane-crossing. It may however involve a blend from the
6590 /// same lane of a second vector.
6591 ///
6592 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6593 /// non-trivial to compute in the face of undef lanes. The representation is
6594 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6595 /// entries from both V1 and V2 inputs to the wider mask.
6596 static bool
6597 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6598                                 SmallVectorImpl<int> &RepeatedMask) {
6599   int LaneSize = 128 / VT.getScalarSizeInBits();
6600   RepeatedMask.resize(LaneSize, -1);
6601   int Size = Mask.size();
6602   for (int i = 0; i < Size; ++i) {
6603     if (Mask[i] < 0)
6604       continue;
6605     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6606       // This entry crosses lanes, so there is no way to model this shuffle.
6607       return false;
6608
6609     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6610     if (RepeatedMask[i % LaneSize] == -1)
6611       // This is the first non-undef entry in this slot of a 128-bit lane.
6612       RepeatedMask[i % LaneSize] =
6613           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6614     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6615       // Found a mismatch with the repeated mask.
6616       return false;
6617   }
6618   return true;
6619 }
6620
6621 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6622 /// arguments.
6623 ///
6624 /// This is a fast way to test a shuffle mask against a fixed pattern:
6625 ///
6626 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6627 ///
6628 /// It returns true if the mask is exactly as wide as the argument list, and
6629 /// each element of the mask is either -1 (signifying undef) or the value given
6630 /// in the argument.
6631 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6632                                 ArrayRef<int> ExpectedMask) {
6633   if (Mask.size() != ExpectedMask.size())
6634     return false;
6635
6636   int Size = Mask.size();
6637
6638   // If the values are build vectors, we can look through them to find
6639   // equivalent inputs that make the shuffles equivalent.
6640   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6641   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6642
6643   for (int i = 0; i < Size; ++i)
6644     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6645       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6646       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6647       if (!MaskBV || !ExpectedBV ||
6648           MaskBV->getOperand(Mask[i] % Size) !=
6649               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6650         return false;
6651     }
6652
6653   return true;
6654 }
6655
6656 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6657 ///
6658 /// This helper function produces an 8-bit shuffle immediate corresponding to
6659 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6660 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6661 /// example.
6662 ///
6663 /// NB: We rely heavily on "undef" masks preserving the input lane.
6664 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6665                                           SelectionDAG &DAG) {
6666   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6667   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6668   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6669   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6670   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6671
6672   unsigned Imm = 0;
6673   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6674   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6675   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6676   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6677   return DAG.getConstant(Imm, DL, MVT::i8);
6678 }
6679
6680 /// \brief Compute whether each element of a shuffle is zeroable.
6681 ///
6682 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6683 /// Either it is an undef element in the shuffle mask, the element of the input
6684 /// referenced is undef, or the element of the input referenced is known to be
6685 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6686 /// as many lanes with this technique as possible to simplify the remaining
6687 /// shuffle.
6688 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6689                                                      SDValue V1, SDValue V2) {
6690   SmallBitVector Zeroable(Mask.size(), false);
6691
6692   while (V1.getOpcode() == ISD::BITCAST)
6693     V1 = V1->getOperand(0);
6694   while (V2.getOpcode() == ISD::BITCAST)
6695     V2 = V2->getOperand(0);
6696
6697   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6698   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6699
6700   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6701     int M = Mask[i];
6702     // Handle the easy cases.
6703     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6704       Zeroable[i] = true;
6705       continue;
6706     }
6707
6708     // If this is an index into a build_vector node (which has the same number
6709     // of elements), dig out the input value and use it.
6710     SDValue V = M < Size ? V1 : V2;
6711     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6712       continue;
6713
6714     SDValue Input = V.getOperand(M % Size);
6715     // The UNDEF opcode check really should be dead code here, but not quite
6716     // worth asserting on (it isn't invalid, just unexpected).
6717     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6718       Zeroable[i] = true;
6719   }
6720
6721   return Zeroable;
6722 }
6723
6724 // X86 has dedicated unpack instructions that can handle specific blend
6725 // operations: UNPCKH and UNPCKL.
6726 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6727                                            SDValue V1, SDValue V2,
6728                                            SelectionDAG &DAG) {
6729   int NumElts = VT.getVectorNumElements();
6730   bool Unpckl = true;
6731   bool Unpckh = true;
6732   bool UnpcklSwapped = true;
6733   bool UnpckhSwapped = true;
6734   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6735
6736   for (int i = 0; i < NumElts; ++i) {
6737     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6738
6739     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6740     int HiPos = LoPos + NumEltsInLane / 2;
6741     int LoPosSwapped = (LoPos + NumElts) % (NumElts * 2);
6742     int HiPosSwapped = (HiPos + NumElts) % (NumElts * 2);
6743
6744     if (Mask[i] == -1)
6745       continue;
6746     if (Mask[i] != LoPos)
6747       Unpckl = false;
6748     if (Mask[i] != HiPos)
6749       Unpckh = false;
6750     if (Mask[i] != LoPosSwapped)
6751       UnpcklSwapped = false;
6752     if (Mask[i] != HiPosSwapped)
6753       UnpckhSwapped = false;
6754     if (!Unpckl && !Unpckh && !UnpcklSwapped && !UnpckhSwapped)
6755       return SDValue();
6756   }
6757   if (Unpckl)
6758     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6759   if (Unpckh)
6760     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6761   if (UnpcklSwapped)
6762     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6763   if (UnpckhSwapped)
6764     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6765
6766   llvm_unreachable("Unexpected result of UNPCK mask analysis");
6767   return SDValue();
6768 }
6769
6770 /// \brief Try to emit a bitmask instruction for a shuffle.
6771 ///
6772 /// This handles cases where we can model a blend exactly as a bitmask due to
6773 /// one of the inputs being zeroable.
6774 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6775                                            SDValue V2, ArrayRef<int> Mask,
6776                                            SelectionDAG &DAG) {
6777   MVT EltVT = VT.getScalarType();
6778   int NumEltBits = EltVT.getSizeInBits();
6779   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6780   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6781   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6782                                     IntEltVT);
6783   if (EltVT.isFloatingPoint()) {
6784     Zero = DAG.getBitcast(EltVT, Zero);
6785     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6786   }
6787   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6788   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6789   SDValue V;
6790   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6791     if (Zeroable[i])
6792       continue;
6793     if (Mask[i] % Size != i)
6794       return SDValue(); // Not a blend.
6795     if (!V)
6796       V = Mask[i] < Size ? V1 : V2;
6797     else if (V != (Mask[i] < Size ? V1 : V2))
6798       return SDValue(); // Can only let one input through the mask.
6799
6800     VMaskOps[i] = AllOnes;
6801   }
6802   if (!V)
6803     return SDValue(); // No non-zeroable elements!
6804
6805   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6806   V = DAG.getNode(VT.isFloatingPoint()
6807                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6808                   DL, VT, V, VMask);
6809   return V;
6810 }
6811
6812 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6813 ///
6814 /// This is used as a fallback approach when first class blend instructions are
6815 /// unavailable. Currently it is only suitable for integer vectors, but could
6816 /// be generalized for floating point vectors if desirable.
6817 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6818                                             SDValue V2, ArrayRef<int> Mask,
6819                                             SelectionDAG &DAG) {
6820   assert(VT.isInteger() && "Only supports integer vector types!");
6821   MVT EltVT = VT.getScalarType();
6822   int NumEltBits = EltVT.getSizeInBits();
6823   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6824   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6825                                     EltVT);
6826   SmallVector<SDValue, 16> MaskOps;
6827   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6828     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6829       return SDValue(); // Shuffled input!
6830     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6831   }
6832
6833   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6834   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6835   // We have to cast V2 around.
6836   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6837   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6838                                       DAG.getBitcast(MaskVT, V1Mask),
6839                                       DAG.getBitcast(MaskVT, V2)));
6840   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6841 }
6842
6843 /// \brief Try to emit a blend instruction for a shuffle.
6844 ///
6845 /// This doesn't do any checks for the availability of instructions for blending
6846 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6847 /// be matched in the backend with the type given. What it does check for is
6848 /// that the shuffle mask is in fact a blend.
6849 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6850                                          SDValue V2, ArrayRef<int> Mask,
6851                                          const X86Subtarget *Subtarget,
6852                                          SelectionDAG &DAG) {
6853   unsigned BlendMask = 0;
6854   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6855     if (Mask[i] >= Size) {
6856       if (Mask[i] != i + Size)
6857         return SDValue(); // Shuffled V2 input!
6858       BlendMask |= 1u << i;
6859       continue;
6860     }
6861     if (Mask[i] >= 0 && Mask[i] != i)
6862       return SDValue(); // Shuffled V1 input!
6863   }
6864   switch (VT.SimpleTy) {
6865   case MVT::v2f64:
6866   case MVT::v4f32:
6867   case MVT::v4f64:
6868   case MVT::v8f32:
6869     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6870                        DAG.getConstant(BlendMask, DL, MVT::i8));
6871
6872   case MVT::v4i64:
6873   case MVT::v8i32:
6874     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6875     // FALLTHROUGH
6876   case MVT::v2i64:
6877   case MVT::v4i32:
6878     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6879     // that instruction.
6880     if (Subtarget->hasAVX2()) {
6881       // Scale the blend by the number of 32-bit dwords per element.
6882       int Scale =  VT.getScalarSizeInBits() / 32;
6883       BlendMask = 0;
6884       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6885         if (Mask[i] >= Size)
6886           for (int j = 0; j < Scale; ++j)
6887             BlendMask |= 1u << (i * Scale + j);
6888
6889       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6890       V1 = DAG.getBitcast(BlendVT, V1);
6891       V2 = DAG.getBitcast(BlendVT, V2);
6892       return DAG.getBitcast(
6893           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6894                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6895     }
6896     // FALLTHROUGH
6897   case MVT::v8i16: {
6898     // For integer shuffles we need to expand the mask and cast the inputs to
6899     // v8i16s prior to blending.
6900     int Scale = 8 / VT.getVectorNumElements();
6901     BlendMask = 0;
6902     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6903       if (Mask[i] >= Size)
6904         for (int j = 0; j < Scale; ++j)
6905           BlendMask |= 1u << (i * Scale + j);
6906
6907     V1 = DAG.getBitcast(MVT::v8i16, V1);
6908     V2 = DAG.getBitcast(MVT::v8i16, V2);
6909     return DAG.getBitcast(VT,
6910                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6911                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6912   }
6913
6914   case MVT::v16i16: {
6915     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6916     SmallVector<int, 8> RepeatedMask;
6917     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6918       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6919       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6920       BlendMask = 0;
6921       for (int i = 0; i < 8; ++i)
6922         if (RepeatedMask[i] >= 16)
6923           BlendMask |= 1u << i;
6924       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6925                          DAG.getConstant(BlendMask, DL, MVT::i8));
6926     }
6927   }
6928     // FALLTHROUGH
6929   case MVT::v16i8:
6930   case MVT::v32i8: {
6931     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6932            "256-bit byte-blends require AVX2 support!");
6933
6934     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6935     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6936       return Masked;
6937
6938     // Scale the blend by the number of bytes per element.
6939     int Scale = VT.getScalarSizeInBits() / 8;
6940
6941     // This form of blend is always done on bytes. Compute the byte vector
6942     // type.
6943     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6944
6945     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6946     // mix of LLVM's code generator and the x86 backend. We tell the code
6947     // generator that boolean values in the elements of an x86 vector register
6948     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6949     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6950     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6951     // of the element (the remaining are ignored) and 0 in that high bit would
6952     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6953     // the LLVM model for boolean values in vector elements gets the relevant
6954     // bit set, it is set backwards and over constrained relative to x86's
6955     // actual model.
6956     SmallVector<SDValue, 32> VSELECTMask;
6957     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6958       for (int j = 0; j < Scale; ++j)
6959         VSELECTMask.push_back(
6960             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6961                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6962                                           MVT::i8));
6963
6964     V1 = DAG.getBitcast(BlendVT, V1);
6965     V2 = DAG.getBitcast(BlendVT, V2);
6966     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6967                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6968                                                       BlendVT, VSELECTMask),
6969                                           V1, V2));
6970   }
6971
6972   default:
6973     llvm_unreachable("Not a supported integer vector type!");
6974   }
6975 }
6976
6977 /// \brief Try to lower as a blend of elements from two inputs followed by
6978 /// a single-input permutation.
6979 ///
6980 /// This matches the pattern where we can blend elements from two inputs and
6981 /// then reduce the shuffle to a single-input permutation.
6982 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6983                                                    SDValue V2,
6984                                                    ArrayRef<int> Mask,
6985                                                    SelectionDAG &DAG) {
6986   // We build up the blend mask while checking whether a blend is a viable way
6987   // to reduce the shuffle.
6988   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6989   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6990
6991   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6992     if (Mask[i] < 0)
6993       continue;
6994
6995     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6996
6997     if (BlendMask[Mask[i] % Size] == -1)
6998       BlendMask[Mask[i] % Size] = Mask[i];
6999     else if (BlendMask[Mask[i] % Size] != Mask[i])
7000       return SDValue(); // Can't blend in the needed input!
7001
7002     PermuteMask[i] = Mask[i] % Size;
7003   }
7004
7005   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7006   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7007 }
7008
7009 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7010 /// blends and permutes.
7011 ///
7012 /// This matches the extremely common pattern for handling combined
7013 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7014 /// operations. It will try to pick the best arrangement of shuffles and
7015 /// blends.
7016 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7017                                                           SDValue V1,
7018                                                           SDValue V2,
7019                                                           ArrayRef<int> Mask,
7020                                                           SelectionDAG &DAG) {
7021   // Shuffle the input elements into the desired positions in V1 and V2 and
7022   // blend them together.
7023   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7024   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7025   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7026   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7027     if (Mask[i] >= 0 && Mask[i] < Size) {
7028       V1Mask[i] = Mask[i];
7029       BlendMask[i] = i;
7030     } else if (Mask[i] >= Size) {
7031       V2Mask[i] = Mask[i] - Size;
7032       BlendMask[i] = i + Size;
7033     }
7034
7035   // Try to lower with the simpler initial blend strategy unless one of the
7036   // input shuffles would be a no-op. We prefer to shuffle inputs as the
7037   // shuffle may be able to fold with a load or other benefit. However, when
7038   // we'll have to do 2x as many shuffles in order to achieve this, blending
7039   // first is a better strategy.
7040   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7041     if (SDValue BlendPerm =
7042             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7043       return BlendPerm;
7044
7045   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7046   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7047   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7048 }
7049
7050 /// \brief Try to lower a vector shuffle as a byte rotation.
7051 ///
7052 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7053 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7054 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7055 /// try to generically lower a vector shuffle through such an pattern. It
7056 /// does not check for the profitability of lowering either as PALIGNR or
7057 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7058 /// This matches shuffle vectors that look like:
7059 ///
7060 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7061 ///
7062 /// Essentially it concatenates V1 and V2, shifts right by some number of
7063 /// elements, and takes the low elements as the result. Note that while this is
7064 /// specified as a *right shift* because x86 is little-endian, it is a *left
7065 /// rotate* of the vector lanes.
7066 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7067                                               SDValue V2,
7068                                               ArrayRef<int> Mask,
7069                                               const X86Subtarget *Subtarget,
7070                                               SelectionDAG &DAG) {
7071   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7072
7073   int NumElts = Mask.size();
7074   int NumLanes = VT.getSizeInBits() / 128;
7075   int NumLaneElts = NumElts / NumLanes;
7076
7077   // We need to detect various ways of spelling a rotation:
7078   //   [11, 12, 13, 14, 15,  0,  1,  2]
7079   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7080   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7081   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7082   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7083   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7084   int Rotation = 0;
7085   SDValue Lo, Hi;
7086   for (int l = 0; l < NumElts; l += NumLaneElts) {
7087     for (int i = 0; i < NumLaneElts; ++i) {
7088       if (Mask[l + i] == -1)
7089         continue;
7090       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7091
7092       // Get the mod-Size index and lane correct it.
7093       int LaneIdx = (Mask[l + i] % NumElts) - l;
7094       // Make sure it was in this lane.
7095       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7096         return SDValue();
7097
7098       // Determine where a rotated vector would have started.
7099       int StartIdx = i - LaneIdx;
7100       if (StartIdx == 0)
7101         // The identity rotation isn't interesting, stop.
7102         return SDValue();
7103
7104       // If we found the tail of a vector the rotation must be the missing
7105       // front. If we found the head of a vector, it must be how much of the
7106       // head.
7107       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7108
7109       if (Rotation == 0)
7110         Rotation = CandidateRotation;
7111       else if (Rotation != CandidateRotation)
7112         // The rotations don't match, so we can't match this mask.
7113         return SDValue();
7114
7115       // Compute which value this mask is pointing at.
7116       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7117
7118       // Compute which of the two target values this index should be assigned
7119       // to. This reflects whether the high elements are remaining or the low
7120       // elements are remaining.
7121       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7122
7123       // Either set up this value if we've not encountered it before, or check
7124       // that it remains consistent.
7125       if (!TargetV)
7126         TargetV = MaskV;
7127       else if (TargetV != MaskV)
7128         // This may be a rotation, but it pulls from the inputs in some
7129         // unsupported interleaving.
7130         return SDValue();
7131     }
7132   }
7133
7134   // Check that we successfully analyzed the mask, and normalize the results.
7135   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7136   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7137   if (!Lo)
7138     Lo = Hi;
7139   else if (!Hi)
7140     Hi = Lo;
7141
7142   // The actual rotate instruction rotates bytes, so we need to scale the
7143   // rotation based on how many bytes are in the vector lane.
7144   int Scale = 16 / NumLaneElts;
7145
7146   // SSSE3 targets can use the palignr instruction.
7147   if (Subtarget->hasSSSE3()) {
7148     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7149     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7150     Lo = DAG.getBitcast(AlignVT, Lo);
7151     Hi = DAG.getBitcast(AlignVT, Hi);
7152
7153     return DAG.getBitcast(
7154         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7155                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7156   }
7157
7158   assert(VT.getSizeInBits() == 128 &&
7159          "Rotate-based lowering only supports 128-bit lowering!");
7160   assert(Mask.size() <= 16 &&
7161          "Can shuffle at most 16 bytes in a 128-bit vector!");
7162
7163   // Default SSE2 implementation
7164   int LoByteShift = 16 - Rotation * Scale;
7165   int HiByteShift = Rotation * Scale;
7166
7167   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7168   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7169   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7170
7171   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7172                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7173   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7174                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7175   return DAG.getBitcast(VT,
7176                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7177 }
7178
7179 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7180 ///
7181 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7182 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7183 /// matches elements from one of the input vectors shuffled to the left or
7184 /// right with zeroable elements 'shifted in'. It handles both the strictly
7185 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7186 /// quad word lane.
7187 ///
7188 /// PSHL : (little-endian) left bit shift.
7189 /// [ zz, 0, zz,  2 ]
7190 /// [ -1, 4, zz, -1 ]
7191 /// PSRL : (little-endian) right bit shift.
7192 /// [  1, zz,  3, zz]
7193 /// [ -1, -1,  7, zz]
7194 /// PSLLDQ : (little-endian) left byte shift
7195 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7196 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7197 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7198 /// PSRLDQ : (little-endian) right byte shift
7199 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7200 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7201 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7202 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7203                                          SDValue V2, ArrayRef<int> Mask,
7204                                          SelectionDAG &DAG) {
7205   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7206
7207   int Size = Mask.size();
7208   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7209
7210   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7211     for (int i = 0; i < Size; i += Scale)
7212       for (int j = 0; j < Shift; ++j)
7213         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7214           return false;
7215
7216     return true;
7217   };
7218
7219   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7220     for (int i = 0; i != Size; i += Scale) {
7221       unsigned Pos = Left ? i + Shift : i;
7222       unsigned Low = Left ? i : i + Shift;
7223       unsigned Len = Scale - Shift;
7224       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7225                                       Low + (V == V1 ? 0 : Size)))
7226         return SDValue();
7227     }
7228
7229     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7230     bool ByteShift = ShiftEltBits > 64;
7231     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7232                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7233     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7234
7235     // Normalize the scale for byte shifts to still produce an i64 element
7236     // type.
7237     Scale = ByteShift ? Scale / 2 : Scale;
7238
7239     // We need to round trip through the appropriate type for the shift.
7240     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7241     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7242     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7243            "Illegal integer vector type");
7244     V = DAG.getBitcast(ShiftVT, V);
7245
7246     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7247                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7248     return DAG.getBitcast(VT, V);
7249   };
7250
7251   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7252   // keep doubling the size of the integer elements up to that. We can
7253   // then shift the elements of the integer vector by whole multiples of
7254   // their width within the elements of the larger integer vector. Test each
7255   // multiple to see if we can find a match with the moved element indices
7256   // and that the shifted in elements are all zeroable.
7257   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7258     for (int Shift = 1; Shift != Scale; ++Shift)
7259       for (bool Left : {true, false})
7260         if (CheckZeros(Shift, Scale, Left))
7261           for (SDValue V : {V1, V2})
7262             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7263               return Match;
7264
7265   // no match
7266   return SDValue();
7267 }
7268
7269 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7270 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7271                                            SDValue V2, ArrayRef<int> Mask,
7272                                            SelectionDAG &DAG) {
7273   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7274   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7275
7276   int Size = Mask.size();
7277   int HalfSize = Size / 2;
7278   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7279
7280   // Upper half must be undefined.
7281   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7282     return SDValue();
7283
7284   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7285   // Remainder of lower half result is zero and upper half is all undef.
7286   auto LowerAsEXTRQ = [&]() {
7287     // Determine the extraction length from the part of the
7288     // lower half that isn't zeroable.
7289     int Len = HalfSize;
7290     for (; Len >= 0; --Len)
7291       if (!Zeroable[Len - 1])
7292         break;
7293     assert(Len > 0 && "Zeroable shuffle mask");
7294
7295     // Attempt to match first Len sequential elements from the lower half.
7296     SDValue Src;
7297     int Idx = -1;
7298     for (int i = 0; i != Len; ++i) {
7299       int M = Mask[i];
7300       if (M < 0)
7301         continue;
7302       SDValue &V = (M < Size ? V1 : V2);
7303       M = M % Size;
7304
7305       // All mask elements must be in the lower half.
7306       if (M > HalfSize)
7307         return SDValue();
7308
7309       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7310         Src = V;
7311         Idx = M - i;
7312         continue;
7313       }
7314       return SDValue();
7315     }
7316
7317     if (Idx < 0)
7318       return SDValue();
7319
7320     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7321     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7322     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7323     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7324                        DAG.getConstant(BitLen, DL, MVT::i8),
7325                        DAG.getConstant(BitIdx, DL, MVT::i8));
7326   };
7327
7328   if (SDValue ExtrQ = LowerAsEXTRQ())
7329     return ExtrQ;
7330
7331   // INSERTQ: Extract lowest Len elements from lower half of second source and
7332   // insert over first source, starting at Idx.
7333   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7334   auto LowerAsInsertQ = [&]() {
7335     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7336       SDValue Base;
7337
7338       // Attempt to match first source from mask before insertion point.
7339       if (isUndefInRange(Mask, 0, Idx)) {
7340         /* EMPTY */
7341       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7342         Base = V1;
7343       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7344         Base = V2;
7345       } else {
7346         continue;
7347       }
7348
7349       // Extend the extraction length looking to match both the insertion of
7350       // the second source and the remaining elements of the first.
7351       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7352         SDValue Insert;
7353         int Len = Hi - Idx;
7354
7355         // Match insertion.
7356         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7357           Insert = V1;
7358         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7359           Insert = V2;
7360         } else {
7361           continue;
7362         }
7363
7364         // Match the remaining elements of the lower half.
7365         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7366           /* EMPTY */
7367         } else if ((!Base || (Base == V1)) &&
7368                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7369           Base = V1;
7370         } else if ((!Base || (Base == V2)) &&
7371                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7372                                               Size + Hi)) {
7373           Base = V2;
7374         } else {
7375           continue;
7376         }
7377
7378         // We may not have a base (first source) - this can safely be undefined.
7379         if (!Base)
7380           Base = DAG.getUNDEF(VT);
7381
7382         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7383         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7384         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7385                            DAG.getConstant(BitLen, DL, MVT::i8),
7386                            DAG.getConstant(BitIdx, DL, MVT::i8));
7387       }
7388     }
7389
7390     return SDValue();
7391   };
7392
7393   if (SDValue InsertQ = LowerAsInsertQ())
7394     return InsertQ;
7395
7396   return SDValue();
7397 }
7398
7399 /// \brief Lower a vector shuffle as a zero or any extension.
7400 ///
7401 /// Given a specific number of elements, element bit width, and extension
7402 /// stride, produce either a zero or any extension based on the available
7403 /// features of the subtarget. The extended elements are consecutive and
7404 /// begin and can start from an offseted element index in the input; to
7405 /// avoid excess shuffling the offset must either being in the bottom lane
7406 /// or at the start of a higher lane. All extended elements must be from
7407 /// the same lane.
7408 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7409     SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7410     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7411   assert(Scale > 1 && "Need a scale to extend.");
7412   int EltBits = VT.getScalarSizeInBits();
7413   int NumElements = VT.getVectorNumElements();
7414   int NumEltsPerLane = 128 / EltBits;
7415   int OffsetLane = Offset / NumEltsPerLane;
7416   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7417          "Only 8, 16, and 32 bit elements can be extended.");
7418   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7419   assert(0 <= Offset && "Extension offset must be positive.");
7420   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7421          "Extension offset must be in the first lane or start an upper lane.");
7422
7423   // Check that an index is in same lane as the base offset.
7424   auto SafeOffset = [&](int Idx) {
7425     return OffsetLane == (Idx / NumEltsPerLane);
7426   };
7427
7428   // Shift along an input so that the offset base moves to the first element.
7429   auto ShuffleOffset = [&](SDValue V) {
7430     if (!Offset)
7431       return V;
7432
7433     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7434     for (int i = 0; i * Scale < NumElements; ++i) {
7435       int SrcIdx = i + Offset;
7436       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7437     }
7438     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7439   };
7440
7441   // Found a valid zext mask! Try various lowering strategies based on the
7442   // input type and available ISA extensions.
7443   if (Subtarget->hasSSE41()) {
7444     // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7445     // PUNPCK will catch this in a later shuffle match.
7446     if (Offset && Scale == 2 && VT.getSizeInBits() == 128)
7447       return SDValue();
7448     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7449                                  NumElements / Scale);
7450     InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7451     return DAG.getBitcast(VT, InputV);
7452   }
7453
7454   assert(VT.getSizeInBits() == 128 && "Only 128-bit vectors can be extended.");
7455
7456   // For any extends we can cheat for larger element sizes and use shuffle
7457   // instructions that can fold with a load and/or copy.
7458   if (AnyExt && EltBits == 32) {
7459     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7460                          -1};
7461     return DAG.getBitcast(
7462         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7463                         DAG.getBitcast(MVT::v4i32, InputV),
7464                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7465   }
7466   if (AnyExt && EltBits == 16 && Scale > 2) {
7467     int PSHUFDMask[4] = {Offset / 2, -1,
7468                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7469     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7470                          DAG.getBitcast(MVT::v4i32, InputV),
7471                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7472     int PSHUFWMask[4] = {1, -1, -1, -1};
7473     unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7474     return DAG.getBitcast(
7475         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7476                         DAG.getBitcast(MVT::v8i16, InputV),
7477                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7478   }
7479
7480   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7481   // to 64-bits.
7482   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7483     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7484     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7485
7486     int LoIdx = Offset * EltBits;
7487     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7488                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7489                                          DAG.getConstant(EltBits, DL, MVT::i8),
7490                                          DAG.getConstant(LoIdx, DL, MVT::i8)));
7491
7492     if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7493         !SafeOffset(Offset + 1))
7494       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7495
7496     int HiIdx = (Offset + 1) * EltBits;
7497     SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7498                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7499                                          DAG.getConstant(EltBits, DL, MVT::i8),
7500                                          DAG.getConstant(HiIdx, DL, MVT::i8)));
7501     return DAG.getNode(ISD::BITCAST, DL, VT,
7502                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7503   }
7504
7505   // If this would require more than 2 unpack instructions to expand, use
7506   // pshufb when available. We can only use more than 2 unpack instructions
7507   // when zero extending i8 elements which also makes it easier to use pshufb.
7508   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7509     assert(NumElements == 16 && "Unexpected byte vector width!");
7510     SDValue PSHUFBMask[16];
7511     for (int i = 0; i < 16; ++i) {
7512       int Idx = Offset + (i / Scale);
7513       PSHUFBMask[i] = DAG.getConstant(
7514           (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7515     }
7516     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7517     return DAG.getBitcast(VT,
7518                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7519                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7520                                                   MVT::v16i8, PSHUFBMask)));
7521   }
7522
7523   // If we are extending from an offset, ensure we start on a boundary that
7524   // we can unpack from.
7525   int AlignToUnpack = Offset % (NumElements / Scale);
7526   if (AlignToUnpack) {
7527     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7528     for (int i = AlignToUnpack; i < NumElements; ++i)
7529       ShMask[i - AlignToUnpack] = i;
7530     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7531     Offset -= AlignToUnpack;
7532   }
7533
7534   // Otherwise emit a sequence of unpacks.
7535   do {
7536     unsigned UnpackLoHi = X86ISD::UNPCKL;
7537     if (Offset >= (NumElements / 2)) {
7538       UnpackLoHi = X86ISD::UNPCKH;
7539       Offset -= (NumElements / 2);
7540     }
7541
7542     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7543     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7544                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7545     InputV = DAG.getBitcast(InputVT, InputV);
7546     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7547     Scale /= 2;
7548     EltBits *= 2;
7549     NumElements /= 2;
7550   } while (Scale > 1);
7551   return DAG.getBitcast(VT, InputV);
7552 }
7553
7554 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7555 ///
7556 /// This routine will try to do everything in its power to cleverly lower
7557 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7558 /// check for the profitability of this lowering,  it tries to aggressively
7559 /// match this pattern. It will use all of the micro-architectural details it
7560 /// can to emit an efficient lowering. It handles both blends with all-zero
7561 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7562 /// masking out later).
7563 ///
7564 /// The reason we have dedicated lowering for zext-style shuffles is that they
7565 /// are both incredibly common and often quite performance sensitive.
7566 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7567     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7568     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7569   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7570
7571   int Bits = VT.getSizeInBits();
7572   int NumLanes = Bits / 128;
7573   int NumElements = VT.getVectorNumElements();
7574   int NumEltsPerLane = NumElements / NumLanes;
7575   assert(VT.getScalarSizeInBits() <= 32 &&
7576          "Exceeds 32-bit integer zero extension limit");
7577   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7578
7579   // Define a helper function to check a particular ext-scale and lower to it if
7580   // valid.
7581   auto Lower = [&](int Scale) -> SDValue {
7582     SDValue InputV;
7583     bool AnyExt = true;
7584     int Offset = 0;
7585     int Matches = 0;
7586     for (int i = 0; i < NumElements; ++i) {
7587       int M = Mask[i];
7588       if (M == -1)
7589         continue; // Valid anywhere but doesn't tell us anything.
7590       if (i % Scale != 0) {
7591         // Each of the extended elements need to be zeroable.
7592         if (!Zeroable[i])
7593           return SDValue();
7594
7595         // We no longer are in the anyext case.
7596         AnyExt = false;
7597         continue;
7598       }
7599
7600       // Each of the base elements needs to be consecutive indices into the
7601       // same input vector.
7602       SDValue V = M < NumElements ? V1 : V2;
7603       M = M % NumElements;
7604       if (!InputV) {
7605         InputV = V;
7606         Offset = M - (i / Scale);
7607       } else if (InputV != V)
7608         return SDValue(); // Flip-flopping inputs.
7609
7610       // Offset must start in the lowest 128-bit lane or at the start of an
7611       // upper lane.
7612       // FIXME: Is it ever worth allowing a negative base offset?
7613       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7614             (Offset % NumEltsPerLane) == 0))
7615         return SDValue();
7616
7617       // If we are offsetting, all referenced entries must come from the same
7618       // lane.
7619       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7620         return SDValue();
7621
7622       if ((M % NumElements) != (Offset + (i / Scale)))
7623         return SDValue(); // Non-consecutive strided elements.
7624       Matches++;
7625     }
7626
7627     // If we fail to find an input, we have a zero-shuffle which should always
7628     // have already been handled.
7629     // FIXME: Maybe handle this here in case during blending we end up with one?
7630     if (!InputV)
7631       return SDValue();
7632
7633     // If we are offsetting, don't extend if we only match a single input, we
7634     // can always do better by using a basic PSHUF or PUNPCK.
7635     if (Offset != 0 && Matches < 2)
7636       return SDValue();
7637
7638     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7639         DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7640   };
7641
7642   // The widest scale possible for extending is to a 64-bit integer.
7643   assert(Bits % 64 == 0 &&
7644          "The number of bits in a vector must be divisible by 64 on x86!");
7645   int NumExtElements = Bits / 64;
7646
7647   // Each iteration, try extending the elements half as much, but into twice as
7648   // many elements.
7649   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7650     assert(NumElements % NumExtElements == 0 &&
7651            "The input vector size must be divisible by the extended size.");
7652     if (SDValue V = Lower(NumElements / NumExtElements))
7653       return V;
7654   }
7655
7656   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7657   if (Bits != 128)
7658     return SDValue();
7659
7660   // Returns one of the source operands if the shuffle can be reduced to a
7661   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7662   auto CanZExtLowHalf = [&]() {
7663     for (int i = NumElements / 2; i != NumElements; ++i)
7664       if (!Zeroable[i])
7665         return SDValue();
7666     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7667       return V1;
7668     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7669       return V2;
7670     return SDValue();
7671   };
7672
7673   if (SDValue V = CanZExtLowHalf()) {
7674     V = DAG.getBitcast(MVT::v2i64, V);
7675     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7676     return DAG.getBitcast(VT, V);
7677   }
7678
7679   // No viable ext lowering found.
7680   return SDValue();
7681 }
7682
7683 /// \brief Try to get a scalar value for a specific element of a vector.
7684 ///
7685 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7686 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7687                                               SelectionDAG &DAG) {
7688   MVT VT = V.getSimpleValueType();
7689   MVT EltVT = VT.getVectorElementType();
7690   while (V.getOpcode() == ISD::BITCAST)
7691     V = V.getOperand(0);
7692   // If the bitcasts shift the element size, we can't extract an equivalent
7693   // element from it.
7694   MVT NewVT = V.getSimpleValueType();
7695   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7696     return SDValue();
7697
7698   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7699       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7700     // Ensure the scalar operand is the same size as the destination.
7701     // FIXME: Add support for scalar truncation where possible.
7702     SDValue S = V.getOperand(Idx);
7703     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7704       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7705   }
7706
7707   return SDValue();
7708 }
7709
7710 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7711 ///
7712 /// This is particularly important because the set of instructions varies
7713 /// significantly based on whether the operand is a load or not.
7714 static bool isShuffleFoldableLoad(SDValue V) {
7715   while (V.getOpcode() == ISD::BITCAST)
7716     V = V.getOperand(0);
7717
7718   return ISD::isNON_EXTLoad(V.getNode());
7719 }
7720
7721 /// \brief Try to lower insertion of a single element into a zero vector.
7722 ///
7723 /// This is a common pattern that we have especially efficient patterns to lower
7724 /// across all subtarget feature sets.
7725 static SDValue lowerVectorShuffleAsElementInsertion(
7726     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7727     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7728   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7729   MVT ExtVT = VT;
7730   MVT EltVT = VT.getVectorElementType();
7731
7732   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7733                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7734                 Mask.begin();
7735   bool IsV1Zeroable = true;
7736   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7737     if (i != V2Index && !Zeroable[i]) {
7738       IsV1Zeroable = false;
7739       break;
7740     }
7741
7742   // Check for a single input from a SCALAR_TO_VECTOR node.
7743   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7744   // all the smarts here sunk into that routine. However, the current
7745   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7746   // vector shuffle lowering is dead.
7747   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7748                                                DAG);
7749   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7750     // We need to zext the scalar if it is smaller than an i32.
7751     V2S = DAG.getBitcast(EltVT, V2S);
7752     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7753       // Using zext to expand a narrow element won't work for non-zero
7754       // insertions.
7755       if (!IsV1Zeroable)
7756         return SDValue();
7757
7758       // Zero-extend directly to i32.
7759       ExtVT = MVT::v4i32;
7760       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7761     }
7762     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7763   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7764              EltVT == MVT::i16) {
7765     // Either not inserting from the low element of the input or the input
7766     // element size is too small to use VZEXT_MOVL to clear the high bits.
7767     return SDValue();
7768   }
7769
7770   if (!IsV1Zeroable) {
7771     // If V1 can't be treated as a zero vector we have fewer options to lower
7772     // this. We can't support integer vectors or non-zero targets cheaply, and
7773     // the V1 elements can't be permuted in any way.
7774     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7775     if (!VT.isFloatingPoint() || V2Index != 0)
7776       return SDValue();
7777     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7778     V1Mask[V2Index] = -1;
7779     if (!isNoopShuffleMask(V1Mask))
7780       return SDValue();
7781     // This is essentially a special case blend operation, but if we have
7782     // general purpose blend operations, they are always faster. Bail and let
7783     // the rest of the lowering handle these as blends.
7784     if (Subtarget->hasSSE41())
7785       return SDValue();
7786
7787     // Otherwise, use MOVSD or MOVSS.
7788     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7789            "Only two types of floating point element types to handle!");
7790     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7791                        ExtVT, V1, V2);
7792   }
7793
7794   // This lowering only works for the low element with floating point vectors.
7795   if (VT.isFloatingPoint() && V2Index != 0)
7796     return SDValue();
7797
7798   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7799   if (ExtVT != VT)
7800     V2 = DAG.getBitcast(VT, V2);
7801
7802   if (V2Index != 0) {
7803     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7804     // the desired position. Otherwise it is more efficient to do a vector
7805     // shift left. We know that we can do a vector shift left because all
7806     // the inputs are zero.
7807     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7808       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7809       V2Shuffle[V2Index] = 0;
7810       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7811     } else {
7812       V2 = DAG.getBitcast(MVT::v2i64, V2);
7813       V2 = DAG.getNode(
7814           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7815           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7816                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7817                               DAG.getDataLayout(), VT)));
7818       V2 = DAG.getBitcast(VT, V2);
7819     }
7820   }
7821   return V2;
7822 }
7823
7824 /// \brief Try to lower broadcast of a single element.
7825 ///
7826 /// For convenience, this code also bundles all of the subtarget feature set
7827 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7828 /// a convenient way to factor it out.
7829 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7830                                              ArrayRef<int> Mask,
7831                                              const X86Subtarget *Subtarget,
7832                                              SelectionDAG &DAG) {
7833   if (!Subtarget->hasAVX())
7834     return SDValue();
7835   if (VT.isInteger() && !Subtarget->hasAVX2())
7836     return SDValue();
7837
7838   // Check that the mask is a broadcast.
7839   int BroadcastIdx = -1;
7840   for (int M : Mask)
7841     if (M >= 0 && BroadcastIdx == -1)
7842       BroadcastIdx = M;
7843     else if (M >= 0 && M != BroadcastIdx)
7844       return SDValue();
7845
7846   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7847                                             "a sorted mask where the broadcast "
7848                                             "comes from V1.");
7849
7850   // Go up the chain of (vector) values to find a scalar load that we can
7851   // combine with the broadcast.
7852   for (;;) {
7853     switch (V.getOpcode()) {
7854     case ISD::CONCAT_VECTORS: {
7855       int OperandSize = Mask.size() / V.getNumOperands();
7856       V = V.getOperand(BroadcastIdx / OperandSize);
7857       BroadcastIdx %= OperandSize;
7858       continue;
7859     }
7860
7861     case ISD::INSERT_SUBVECTOR: {
7862       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7863       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7864       if (!ConstantIdx)
7865         break;
7866
7867       int BeginIdx = (int)ConstantIdx->getZExtValue();
7868       int EndIdx =
7869           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7870       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7871         BroadcastIdx -= BeginIdx;
7872         V = VInner;
7873       } else {
7874         V = VOuter;
7875       }
7876       continue;
7877     }
7878     }
7879     break;
7880   }
7881
7882   // Check if this is a broadcast of a scalar. We special case lowering
7883   // for scalars so that we can more effectively fold with loads.
7884   // First, look through bitcast: if the original value has a larger element
7885   // type than the shuffle, the broadcast element is in essence truncated.
7886   // Make that explicit to ease folding.
7887   if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7888     EVT EltVT = VT.getVectorElementType();
7889     SDValue V0 = V.getOperand(0);
7890     EVT V0VT = V0.getValueType();
7891
7892     if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7893         ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7894          (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7895       V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7896       BroadcastIdx = 0;
7897     }
7898   }
7899
7900   // Also check the simpler case, where we can directly reuse the scalar.
7901   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7902       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7903     V = V.getOperand(BroadcastIdx);
7904
7905     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7906     // Only AVX2 has register broadcasts.
7907     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7908       return SDValue();
7909   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7910     // We can't broadcast from a vector register without AVX2, and we can only
7911     // broadcast from the zero-element of a vector register.
7912     return SDValue();
7913   }
7914
7915   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7916 }
7917
7918 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7919 // INSERTPS when the V1 elements are already in the correct locations
7920 // because otherwise we can just always use two SHUFPS instructions which
7921 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7922 // perform INSERTPS if a single V1 element is out of place and all V2
7923 // elements are zeroable.
7924 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7925                                             ArrayRef<int> Mask,
7926                                             SelectionDAG &DAG) {
7927   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7928   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7929   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7930   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7931
7932   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7933
7934   unsigned ZMask = 0;
7935   int V1DstIndex = -1;
7936   int V2DstIndex = -1;
7937   bool V1UsedInPlace = false;
7938
7939   for (int i = 0; i < 4; ++i) {
7940     // Synthesize a zero mask from the zeroable elements (includes undefs).
7941     if (Zeroable[i]) {
7942       ZMask |= 1 << i;
7943       continue;
7944     }
7945
7946     // Flag if we use any V1 inputs in place.
7947     if (i == Mask[i]) {
7948       V1UsedInPlace = true;
7949       continue;
7950     }
7951
7952     // We can only insert a single non-zeroable element.
7953     if (V1DstIndex != -1 || V2DstIndex != -1)
7954       return SDValue();
7955
7956     if (Mask[i] < 4) {
7957       // V1 input out of place for insertion.
7958       V1DstIndex = i;
7959     } else {
7960       // V2 input for insertion.
7961       V2DstIndex = i;
7962     }
7963   }
7964
7965   // Don't bother if we have no (non-zeroable) element for insertion.
7966   if (V1DstIndex == -1 && V2DstIndex == -1)
7967     return SDValue();
7968
7969   // Determine element insertion src/dst indices. The src index is from the
7970   // start of the inserted vector, not the start of the concatenated vector.
7971   unsigned V2SrcIndex = 0;
7972   if (V1DstIndex != -1) {
7973     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7974     // and don't use the original V2 at all.
7975     V2SrcIndex = Mask[V1DstIndex];
7976     V2DstIndex = V1DstIndex;
7977     V2 = V1;
7978   } else {
7979     V2SrcIndex = Mask[V2DstIndex] - 4;
7980   }
7981
7982   // If no V1 inputs are used in place, then the result is created only from
7983   // the zero mask and the V2 insertion - so remove V1 dependency.
7984   if (!V1UsedInPlace)
7985     V1 = DAG.getUNDEF(MVT::v4f32);
7986
7987   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7988   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7989
7990   // Insert the V2 element into the desired position.
7991   SDLoc DL(Op);
7992   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7993                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7994 }
7995
7996 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7997 /// UNPCK instruction.
7998 ///
7999 /// This specifically targets cases where we end up with alternating between
8000 /// the two inputs, and so can permute them into something that feeds a single
8001 /// UNPCK instruction. Note that this routine only targets integer vectors
8002 /// because for floating point vectors we have a generalized SHUFPS lowering
8003 /// strategy that handles everything that doesn't *exactly* match an unpack,
8004 /// making this clever lowering unnecessary.
8005 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8006                                                     SDValue V1, SDValue V2,
8007                                                     ArrayRef<int> Mask,
8008                                                     SelectionDAG &DAG) {
8009   assert(!VT.isFloatingPoint() &&
8010          "This routine only supports integer vectors.");
8011   assert(!isSingleInputShuffleMask(Mask) &&
8012          "This routine should only be used when blending two inputs.");
8013   assert(Mask.size() >= 2 && "Single element masks are invalid.");
8014
8015   int Size = Mask.size();
8016
8017   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8018     return M >= 0 && M % Size < Size / 2;
8019   });
8020   int NumHiInputs = std::count_if(
8021       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8022
8023   bool UnpackLo = NumLoInputs >= NumHiInputs;
8024
8025   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8026     SmallVector<int, 32> V1Mask(Mask.size(), -1);
8027     SmallVector<int, 32> V2Mask(Mask.size(), -1);
8028
8029     for (int i = 0; i < Size; ++i) {
8030       if (Mask[i] < 0)
8031         continue;
8032
8033       // Each element of the unpack contains Scale elements from this mask.
8034       int UnpackIdx = i / Scale;
8035
8036       // We only handle the case where V1 feeds the first slots of the unpack.
8037       // We rely on canonicalization to ensure this is the case.
8038       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8039         return SDValue();
8040
8041       // Setup the mask for this input. The indexing is tricky as we have to
8042       // handle the unpack stride.
8043       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8044       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8045           Mask[i] % Size;
8046     }
8047
8048     // If we will have to shuffle both inputs to use the unpack, check whether
8049     // we can just unpack first and shuffle the result. If so, skip this unpack.
8050     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8051         !isNoopShuffleMask(V2Mask))
8052       return SDValue();
8053
8054     // Shuffle the inputs into place.
8055     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8056     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8057
8058     // Cast the inputs to the type we will use to unpack them.
8059     V1 = DAG.getBitcast(UnpackVT, V1);
8060     V2 = DAG.getBitcast(UnpackVT, V2);
8061
8062     // Unpack the inputs and cast the result back to the desired type.
8063     return DAG.getBitcast(
8064         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8065                         UnpackVT, V1, V2));
8066   };
8067
8068   // We try each unpack from the largest to the smallest to try and find one
8069   // that fits this mask.
8070   int OrigNumElements = VT.getVectorNumElements();
8071   int OrigScalarSize = VT.getScalarSizeInBits();
8072   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8073     int Scale = ScalarSize / OrigScalarSize;
8074     int NumElements = OrigNumElements / Scale;
8075     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8076     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8077       return Unpack;
8078   }
8079
8080   // If none of the unpack-rooted lowerings worked (or were profitable) try an
8081   // initial unpack.
8082   if (NumLoInputs == 0 || NumHiInputs == 0) {
8083     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8084            "We have to have *some* inputs!");
8085     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8086
8087     // FIXME: We could consider the total complexity of the permute of each
8088     // possible unpacking. Or at the least we should consider how many
8089     // half-crossings are created.
8090     // FIXME: We could consider commuting the unpacks.
8091
8092     SmallVector<int, 32> PermMask;
8093     PermMask.assign(Size, -1);
8094     for (int i = 0; i < Size; ++i) {
8095       if (Mask[i] < 0)
8096         continue;
8097
8098       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8099
8100       PermMask[i] =
8101           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8102     }
8103     return DAG.getVectorShuffle(
8104         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8105                             DL, VT, V1, V2),
8106         DAG.getUNDEF(VT), PermMask);
8107   }
8108
8109   return SDValue();
8110 }
8111
8112 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8113 ///
8114 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8115 /// support for floating point shuffles but not integer shuffles. These
8116 /// instructions will incur a domain crossing penalty on some chips though so
8117 /// it is better to avoid lowering through this for integer vectors where
8118 /// possible.
8119 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8120                                        const X86Subtarget *Subtarget,
8121                                        SelectionDAG &DAG) {
8122   SDLoc DL(Op);
8123   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8124   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8125   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8126   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8127   ArrayRef<int> Mask = SVOp->getMask();
8128   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8129
8130   if (isSingleInputShuffleMask(Mask)) {
8131     // Use low duplicate instructions for masks that match their pattern.
8132     if (Subtarget->hasSSE3())
8133       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8134         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8135
8136     // Straight shuffle of a single input vector. Simulate this by using the
8137     // single input as both of the "inputs" to this instruction..
8138     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8139
8140     if (Subtarget->hasAVX()) {
8141       // If we have AVX, we can use VPERMILPS which will allow folding a load
8142       // into the shuffle.
8143       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8144                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8145     }
8146
8147     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8148                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8149   }
8150   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8151   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8152
8153   // If we have a single input, insert that into V1 if we can do so cheaply.
8154   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8155     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8156             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8157       return Insertion;
8158     // Try inverting the insertion since for v2 masks it is easy to do and we
8159     // can't reliably sort the mask one way or the other.
8160     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8161                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8162     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8163             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8164       return Insertion;
8165   }
8166
8167   // Try to use one of the special instruction patterns to handle two common
8168   // blend patterns if a zero-blend above didn't work.
8169   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8170       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8171     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8172       // We can either use a special instruction to load over the low double or
8173       // to move just the low double.
8174       return DAG.getNode(
8175           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8176           DL, MVT::v2f64, V2,
8177           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8178
8179   if (Subtarget->hasSSE41())
8180     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8181                                                   Subtarget, DAG))
8182       return Blend;
8183
8184   // Use dedicated unpack instructions for masks that match their pattern.
8185   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8186     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
8187   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8188     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
8189
8190   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8191   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8192                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8193 }
8194
8195 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8196 ///
8197 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8198 /// the integer unit to minimize domain crossing penalties. However, for blends
8199 /// it falls back to the floating point shuffle operation with appropriate bit
8200 /// casting.
8201 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8202                                        const X86Subtarget *Subtarget,
8203                                        SelectionDAG &DAG) {
8204   SDLoc DL(Op);
8205   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8206   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8207   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8208   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8209   ArrayRef<int> Mask = SVOp->getMask();
8210   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8211
8212   if (isSingleInputShuffleMask(Mask)) {
8213     // Check for being able to broadcast a single element.
8214     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8215                                                           Mask, Subtarget, DAG))
8216       return Broadcast;
8217
8218     // Straight shuffle of a single input vector. For everything from SSE2
8219     // onward this has a single fast instruction with no scary immediates.
8220     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8221     V1 = DAG.getBitcast(MVT::v4i32, V1);
8222     int WidenedMask[4] = {
8223         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8224         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8225     return DAG.getBitcast(
8226         MVT::v2i64,
8227         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8228                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8229   }
8230   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8231   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8232   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8233   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8234
8235   // If we have a blend of two PACKUS operations an the blend aligns with the
8236   // low and half halves, we can just merge the PACKUS operations. This is
8237   // particularly important as it lets us merge shuffles that this routine itself
8238   // creates.
8239   auto GetPackNode = [](SDValue V) {
8240     while (V.getOpcode() == ISD::BITCAST)
8241       V = V.getOperand(0);
8242
8243     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8244   };
8245   if (SDValue V1Pack = GetPackNode(V1))
8246     if (SDValue V2Pack = GetPackNode(V2))
8247       return DAG.getBitcast(MVT::v2i64,
8248                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8249                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8250                                                      : V1Pack.getOperand(1),
8251                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8252                                                      : V2Pack.getOperand(1)));
8253
8254   // Try to use shift instructions.
8255   if (SDValue Shift =
8256           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8257     return Shift;
8258
8259   // When loading a scalar and then shuffling it into a vector we can often do
8260   // the insertion cheaply.
8261   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8262           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8263     return Insertion;
8264   // Try inverting the insertion since for v2 masks it is easy to do and we
8265   // can't reliably sort the mask one way or the other.
8266   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8267   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8268           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8269     return Insertion;
8270
8271   // We have different paths for blend lowering, but they all must use the
8272   // *exact* same predicate.
8273   bool IsBlendSupported = Subtarget->hasSSE41();
8274   if (IsBlendSupported)
8275     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8276                                                   Subtarget, DAG))
8277       return Blend;
8278
8279   // Use dedicated unpack instructions for masks that match their pattern.
8280   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8281     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8282   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8283     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8284
8285   // Try to use byte rotation instructions.
8286   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8287   if (Subtarget->hasSSSE3())
8288     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8289             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8290       return Rotate;
8291
8292   // If we have direct support for blends, we should lower by decomposing into
8293   // a permute. That will be faster than the domain cross.
8294   if (IsBlendSupported)
8295     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8296                                                       Mask, DAG);
8297
8298   // We implement this with SHUFPD which is pretty lame because it will likely
8299   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8300   // However, all the alternatives are still more cycles and newer chips don't
8301   // have this problem. It would be really nice if x86 had better shuffles here.
8302   V1 = DAG.getBitcast(MVT::v2f64, V1);
8303   V2 = DAG.getBitcast(MVT::v2f64, V2);
8304   return DAG.getBitcast(MVT::v2i64,
8305                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8306 }
8307
8308 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8309 ///
8310 /// This is used to disable more specialized lowerings when the shufps lowering
8311 /// will happen to be efficient.
8312 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8313   // This routine only handles 128-bit shufps.
8314   assert(Mask.size() == 4 && "Unsupported mask size!");
8315
8316   // To lower with a single SHUFPS we need to have the low half and high half
8317   // each requiring a single input.
8318   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8319     return false;
8320   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8321     return false;
8322
8323   return true;
8324 }
8325
8326 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8327 ///
8328 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8329 /// It makes no assumptions about whether this is the *best* lowering, it simply
8330 /// uses it.
8331 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8332                                             ArrayRef<int> Mask, SDValue V1,
8333                                             SDValue V2, SelectionDAG &DAG) {
8334   SDValue LowV = V1, HighV = V2;
8335   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8336
8337   int NumV2Elements =
8338       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8339
8340   if (NumV2Elements == 1) {
8341     int V2Index =
8342         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8343         Mask.begin();
8344
8345     // Compute the index adjacent to V2Index and in the same half by toggling
8346     // the low bit.
8347     int V2AdjIndex = V2Index ^ 1;
8348
8349     if (Mask[V2AdjIndex] == -1) {
8350       // Handles all the cases where we have a single V2 element and an undef.
8351       // This will only ever happen in the high lanes because we commute the
8352       // vector otherwise.
8353       if (V2Index < 2)
8354         std::swap(LowV, HighV);
8355       NewMask[V2Index] -= 4;
8356     } else {
8357       // Handle the case where the V2 element ends up adjacent to a V1 element.
8358       // To make this work, blend them together as the first step.
8359       int V1Index = V2AdjIndex;
8360       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8361       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8362                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8363
8364       // Now proceed to reconstruct the final blend as we have the necessary
8365       // high or low half formed.
8366       if (V2Index < 2) {
8367         LowV = V2;
8368         HighV = V1;
8369       } else {
8370         HighV = V2;
8371       }
8372       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8373       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8374     }
8375   } else if (NumV2Elements == 2) {
8376     if (Mask[0] < 4 && Mask[1] < 4) {
8377       // Handle the easy case where we have V1 in the low lanes and V2 in the
8378       // high lanes.
8379       NewMask[2] -= 4;
8380       NewMask[3] -= 4;
8381     } else if (Mask[2] < 4 && Mask[3] < 4) {
8382       // We also handle the reversed case because this utility may get called
8383       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8384       // arrange things in the right direction.
8385       NewMask[0] -= 4;
8386       NewMask[1] -= 4;
8387       HighV = V1;
8388       LowV = V2;
8389     } else {
8390       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8391       // trying to place elements directly, just blend them and set up the final
8392       // shuffle to place them.
8393
8394       // The first two blend mask elements are for V1, the second two are for
8395       // V2.
8396       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8397                           Mask[2] < 4 ? Mask[2] : Mask[3],
8398                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8399                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8400       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8401                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8402
8403       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8404       // a blend.
8405       LowV = HighV = V1;
8406       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8407       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8408       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8409       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8410     }
8411   }
8412   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8413                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8414 }
8415
8416 /// \brief Lower 4-lane 32-bit floating point shuffles.
8417 ///
8418 /// Uses instructions exclusively from the floating point unit to minimize
8419 /// domain crossing penalties, as these are sufficient to implement all v4f32
8420 /// shuffles.
8421 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8422                                        const X86Subtarget *Subtarget,
8423                                        SelectionDAG &DAG) {
8424   SDLoc DL(Op);
8425   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8426   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8427   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8428   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8429   ArrayRef<int> Mask = SVOp->getMask();
8430   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8431
8432   int NumV2Elements =
8433       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8434
8435   if (NumV2Elements == 0) {
8436     // Check for being able to broadcast a single element.
8437     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8438                                                           Mask, Subtarget, DAG))
8439       return Broadcast;
8440
8441     // Use even/odd duplicate instructions for masks that match their pattern.
8442     if (Subtarget->hasSSE3()) {
8443       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8444         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8445       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8446         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8447     }
8448
8449     if (Subtarget->hasAVX()) {
8450       // If we have AVX, we can use VPERMILPS which will allow folding a load
8451       // into the shuffle.
8452       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8453                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8454     }
8455
8456     // Otherwise, use a straight shuffle of a single input vector. We pass the
8457     // input vector to both operands to simulate this with a SHUFPS.
8458     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8459                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8460   }
8461
8462   // There are special ways we can lower some single-element blends. However, we
8463   // have custom ways we can lower more complex single-element blends below that
8464   // we defer to if both this and BLENDPS fail to match, so restrict this to
8465   // when the V2 input is targeting element 0 of the mask -- that is the fast
8466   // case here.
8467   if (NumV2Elements == 1 && Mask[0] >= 4)
8468     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8469                                                          Mask, Subtarget, DAG))
8470       return V;
8471
8472   if (Subtarget->hasSSE41()) {
8473     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8474                                                   Subtarget, DAG))
8475       return Blend;
8476
8477     // Use INSERTPS if we can complete the shuffle efficiently.
8478     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8479       return V;
8480
8481     if (!isSingleSHUFPSMask(Mask))
8482       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8483               DL, MVT::v4f32, V1, V2, Mask, DAG))
8484         return BlendPerm;
8485   }
8486
8487   // Use dedicated unpack instructions for masks that match their pattern.
8488   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8489     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8490   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8491     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8492   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8493     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8494   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8495     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8496
8497   // Otherwise fall back to a SHUFPS lowering strategy.
8498   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8499 }
8500
8501 /// \brief Lower 4-lane i32 vector shuffles.
8502 ///
8503 /// We try to handle these with integer-domain shuffles where we can, but for
8504 /// blends we use the floating point domain blend instructions.
8505 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8506                                        const X86Subtarget *Subtarget,
8507                                        SelectionDAG &DAG) {
8508   SDLoc DL(Op);
8509   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8510   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8511   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8512   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8513   ArrayRef<int> Mask = SVOp->getMask();
8514   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8515
8516   // Whenever we can lower this as a zext, that instruction is strictly faster
8517   // than any alternative. It also allows us to fold memory operands into the
8518   // shuffle in many cases.
8519   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8520                                                          Mask, Subtarget, DAG))
8521     return ZExt;
8522
8523   int NumV2Elements =
8524       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8525
8526   if (NumV2Elements == 0) {
8527     // Check for being able to broadcast a single element.
8528     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8529                                                           Mask, Subtarget, DAG))
8530       return Broadcast;
8531
8532     // Straight shuffle of a single input vector. For everything from SSE2
8533     // onward this has a single fast instruction with no scary immediates.
8534     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8535     // but we aren't actually going to use the UNPCK instruction because doing
8536     // so prevents folding a load into this instruction or making a copy.
8537     const int UnpackLoMask[] = {0, 0, 1, 1};
8538     const int UnpackHiMask[] = {2, 2, 3, 3};
8539     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8540       Mask = UnpackLoMask;
8541     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8542       Mask = UnpackHiMask;
8543
8544     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8545                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8546   }
8547
8548   // Try to use shift instructions.
8549   if (SDValue Shift =
8550           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8551     return Shift;
8552
8553   // There are special ways we can lower some single-element blends.
8554   if (NumV2Elements == 1)
8555     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8556                                                          Mask, Subtarget, DAG))
8557       return V;
8558
8559   // We have different paths for blend lowering, but they all must use the
8560   // *exact* same predicate.
8561   bool IsBlendSupported = Subtarget->hasSSE41();
8562   if (IsBlendSupported)
8563     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8564                                                   Subtarget, DAG))
8565       return Blend;
8566
8567   if (SDValue Masked =
8568           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8569     return Masked;
8570
8571   // Use dedicated unpack instructions for masks that match their pattern.
8572   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8573     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8574   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8575     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8576   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8577     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8578   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8579     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8580
8581   // Try to use byte rotation instructions.
8582   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8583   if (Subtarget->hasSSSE3())
8584     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8585             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8586       return Rotate;
8587
8588   // If we have direct support for blends, we should lower by decomposing into
8589   // a permute. That will be faster than the domain cross.
8590   if (IsBlendSupported)
8591     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8592                                                       Mask, DAG);
8593
8594   // Try to lower by permuting the inputs into an unpack instruction.
8595   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8596                                                             V2, Mask, DAG))
8597     return Unpack;
8598
8599   // We implement this with SHUFPS because it can blend from two vectors.
8600   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8601   // up the inputs, bypassing domain shift penalties that we would encur if we
8602   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8603   // relevant.
8604   return DAG.getBitcast(
8605       MVT::v4i32,
8606       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8607                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8608 }
8609
8610 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8611 /// shuffle lowering, and the most complex part.
8612 ///
8613 /// The lowering strategy is to try to form pairs of input lanes which are
8614 /// targeted at the same half of the final vector, and then use a dword shuffle
8615 /// to place them onto the right half, and finally unpack the paired lanes into
8616 /// their final position.
8617 ///
8618 /// The exact breakdown of how to form these dword pairs and align them on the
8619 /// correct sides is really tricky. See the comments within the function for
8620 /// more of the details.
8621 ///
8622 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8623 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8624 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8625 /// vector, form the analogous 128-bit 8-element Mask.
8626 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8627     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8628     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8629   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8630   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8631
8632   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8633   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8634   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8635
8636   SmallVector<int, 4> LoInputs;
8637   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8638                [](int M) { return M >= 0; });
8639   std::sort(LoInputs.begin(), LoInputs.end());
8640   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8641   SmallVector<int, 4> HiInputs;
8642   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8643                [](int M) { return M >= 0; });
8644   std::sort(HiInputs.begin(), HiInputs.end());
8645   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8646   int NumLToL =
8647       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8648   int NumHToL = LoInputs.size() - NumLToL;
8649   int NumLToH =
8650       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8651   int NumHToH = HiInputs.size() - NumLToH;
8652   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8653   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8654   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8655   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8656
8657   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8658   // such inputs we can swap two of the dwords across the half mark and end up
8659   // with <=2 inputs to each half in each half. Once there, we can fall through
8660   // to the generic code below. For example:
8661   //
8662   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8663   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8664   //
8665   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8666   // and an existing 2-into-2 on the other half. In this case we may have to
8667   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8668   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8669   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8670   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8671   // half than the one we target for fixing) will be fixed when we re-enter this
8672   // path. We will also combine away any sequence of PSHUFD instructions that
8673   // result into a single instruction. Here is an example of the tricky case:
8674   //
8675   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8676   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8677   //
8678   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8679   //
8680   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8681   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8682   //
8683   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8684   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8685   //
8686   // The result is fine to be handled by the generic logic.
8687   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8688                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8689                           int AOffset, int BOffset) {
8690     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8691            "Must call this with A having 3 or 1 inputs from the A half.");
8692     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8693            "Must call this with B having 1 or 3 inputs from the B half.");
8694     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8695            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8696
8697     bool ThreeAInputs = AToAInputs.size() == 3;
8698
8699     // Compute the index of dword with only one word among the three inputs in
8700     // a half by taking the sum of the half with three inputs and subtracting
8701     // the sum of the actual three inputs. The difference is the remaining
8702     // slot.
8703     int ADWord, BDWord;
8704     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8705     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8706     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8707     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8708     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8709     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8710     int TripleNonInputIdx =
8711         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8712     TripleDWord = TripleNonInputIdx / 2;
8713
8714     // We use xor with one to compute the adjacent DWord to whichever one the
8715     // OneInput is in.
8716     OneInputDWord = (OneInput / 2) ^ 1;
8717
8718     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8719     // and BToA inputs. If there is also such a problem with the BToB and AToB
8720     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8721     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8722     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8723     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8724       // Compute how many inputs will be flipped by swapping these DWords. We
8725       // need
8726       // to balance this to ensure we don't form a 3-1 shuffle in the other
8727       // half.
8728       int NumFlippedAToBInputs =
8729           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8730           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8731       int NumFlippedBToBInputs =
8732           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8733           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8734       if ((NumFlippedAToBInputs == 1 &&
8735            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8736           (NumFlippedBToBInputs == 1 &&
8737            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8738         // We choose whether to fix the A half or B half based on whether that
8739         // half has zero flipped inputs. At zero, we may not be able to fix it
8740         // with that half. We also bias towards fixing the B half because that
8741         // will more commonly be the high half, and we have to bias one way.
8742         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8743                                                        ArrayRef<int> Inputs) {
8744           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8745           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8746                                          PinnedIdx ^ 1) != Inputs.end();
8747           // Determine whether the free index is in the flipped dword or the
8748           // unflipped dword based on where the pinned index is. We use this bit
8749           // in an xor to conditionally select the adjacent dword.
8750           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8751           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8752                                              FixFreeIdx) != Inputs.end();
8753           if (IsFixIdxInput == IsFixFreeIdxInput)
8754             FixFreeIdx += 1;
8755           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8756                                         FixFreeIdx) != Inputs.end();
8757           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8758                  "We need to be changing the number of flipped inputs!");
8759           int PSHUFHalfMask[] = {0, 1, 2, 3};
8760           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8761           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8762                           MVT::v8i16, V,
8763                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8764
8765           for (int &M : Mask)
8766             if (M != -1 && M == FixIdx)
8767               M = FixFreeIdx;
8768             else if (M != -1 && M == FixFreeIdx)
8769               M = FixIdx;
8770         };
8771         if (NumFlippedBToBInputs != 0) {
8772           int BPinnedIdx =
8773               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8774           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8775         } else {
8776           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8777           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8778           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8779         }
8780       }
8781     }
8782
8783     int PSHUFDMask[] = {0, 1, 2, 3};
8784     PSHUFDMask[ADWord] = BDWord;
8785     PSHUFDMask[BDWord] = ADWord;
8786     V = DAG.getBitcast(
8787         VT,
8788         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8789                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8790
8791     // Adjust the mask to match the new locations of A and B.
8792     for (int &M : Mask)
8793       if (M != -1 && M/2 == ADWord)
8794         M = 2 * BDWord + M % 2;
8795       else if (M != -1 && M/2 == BDWord)
8796         M = 2 * ADWord + M % 2;
8797
8798     // Recurse back into this routine to re-compute state now that this isn't
8799     // a 3 and 1 problem.
8800     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8801                                                      DAG);
8802   };
8803   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8804     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8805   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8806     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8807
8808   // At this point there are at most two inputs to the low and high halves from
8809   // each half. That means the inputs can always be grouped into dwords and
8810   // those dwords can then be moved to the correct half with a dword shuffle.
8811   // We use at most one low and one high word shuffle to collect these paired
8812   // inputs into dwords, and finally a dword shuffle to place them.
8813   int PSHUFLMask[4] = {-1, -1, -1, -1};
8814   int PSHUFHMask[4] = {-1, -1, -1, -1};
8815   int PSHUFDMask[4] = {-1, -1, -1, -1};
8816
8817   // First fix the masks for all the inputs that are staying in their
8818   // original halves. This will then dictate the targets of the cross-half
8819   // shuffles.
8820   auto fixInPlaceInputs =
8821       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8822                     MutableArrayRef<int> SourceHalfMask,
8823                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8824     if (InPlaceInputs.empty())
8825       return;
8826     if (InPlaceInputs.size() == 1) {
8827       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8828           InPlaceInputs[0] - HalfOffset;
8829       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8830       return;
8831     }
8832     if (IncomingInputs.empty()) {
8833       // Just fix all of the in place inputs.
8834       for (int Input : InPlaceInputs) {
8835         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8836         PSHUFDMask[Input / 2] = Input / 2;
8837       }
8838       return;
8839     }
8840
8841     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8842     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8843         InPlaceInputs[0] - HalfOffset;
8844     // Put the second input next to the first so that they are packed into
8845     // a dword. We find the adjacent index by toggling the low bit.
8846     int AdjIndex = InPlaceInputs[0] ^ 1;
8847     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8848     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8849     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8850   };
8851   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8852   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8853
8854   // Now gather the cross-half inputs and place them into a free dword of
8855   // their target half.
8856   // FIXME: This operation could almost certainly be simplified dramatically to
8857   // look more like the 3-1 fixing operation.
8858   auto moveInputsToRightHalf = [&PSHUFDMask](
8859       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8860       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8861       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8862       int DestOffset) {
8863     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8864       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8865     };
8866     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8867                                                int Word) {
8868       int LowWord = Word & ~1;
8869       int HighWord = Word | 1;
8870       return isWordClobbered(SourceHalfMask, LowWord) ||
8871              isWordClobbered(SourceHalfMask, HighWord);
8872     };
8873
8874     if (IncomingInputs.empty())
8875       return;
8876
8877     if (ExistingInputs.empty()) {
8878       // Map any dwords with inputs from them into the right half.
8879       for (int Input : IncomingInputs) {
8880         // If the source half mask maps over the inputs, turn those into
8881         // swaps and use the swapped lane.
8882         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8883           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8884             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8885                 Input - SourceOffset;
8886             // We have to swap the uses in our half mask in one sweep.
8887             for (int &M : HalfMask)
8888               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8889                 M = Input;
8890               else if (M == Input)
8891                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8892           } else {
8893             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8894                        Input - SourceOffset &&
8895                    "Previous placement doesn't match!");
8896           }
8897           // Note that this correctly re-maps both when we do a swap and when
8898           // we observe the other side of the swap above. We rely on that to
8899           // avoid swapping the members of the input list directly.
8900           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8901         }
8902
8903         // Map the input's dword into the correct half.
8904         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8905           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8906         else
8907           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8908                      Input / 2 &&
8909                  "Previous placement doesn't match!");
8910       }
8911
8912       // And just directly shift any other-half mask elements to be same-half
8913       // as we will have mirrored the dword containing the element into the
8914       // same position within that half.
8915       for (int &M : HalfMask)
8916         if (M >= SourceOffset && M < SourceOffset + 4) {
8917           M = M - SourceOffset + DestOffset;
8918           assert(M >= 0 && "This should never wrap below zero!");
8919         }
8920       return;
8921     }
8922
8923     // Ensure we have the input in a viable dword of its current half. This
8924     // is particularly tricky because the original position may be clobbered
8925     // by inputs being moved and *staying* in that half.
8926     if (IncomingInputs.size() == 1) {
8927       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8928         int InputFixed = std::find(std::begin(SourceHalfMask),
8929                                    std::end(SourceHalfMask), -1) -
8930                          std::begin(SourceHalfMask) + SourceOffset;
8931         SourceHalfMask[InputFixed - SourceOffset] =
8932             IncomingInputs[0] - SourceOffset;
8933         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8934                      InputFixed);
8935         IncomingInputs[0] = InputFixed;
8936       }
8937     } else if (IncomingInputs.size() == 2) {
8938       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8939           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8940         // We have two non-adjacent or clobbered inputs we need to extract from
8941         // the source half. To do this, we need to map them into some adjacent
8942         // dword slot in the source mask.
8943         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8944                               IncomingInputs[1] - SourceOffset};
8945
8946         // If there is a free slot in the source half mask adjacent to one of
8947         // the inputs, place the other input in it. We use (Index XOR 1) to
8948         // compute an adjacent index.
8949         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8950             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8951           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8952           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8953           InputsFixed[1] = InputsFixed[0] ^ 1;
8954         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8955                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8956           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8957           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8958           InputsFixed[0] = InputsFixed[1] ^ 1;
8959         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8960                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8961           // The two inputs are in the same DWord but it is clobbered and the
8962           // adjacent DWord isn't used at all. Move both inputs to the free
8963           // slot.
8964           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8965           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8966           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8967           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8968         } else {
8969           // The only way we hit this point is if there is no clobbering
8970           // (because there are no off-half inputs to this half) and there is no
8971           // free slot adjacent to one of the inputs. In this case, we have to
8972           // swap an input with a non-input.
8973           for (int i = 0; i < 4; ++i)
8974             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8975                    "We can't handle any clobbers here!");
8976           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8977                  "Cannot have adjacent inputs here!");
8978
8979           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8980           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8981
8982           // We also have to update the final source mask in this case because
8983           // it may need to undo the above swap.
8984           for (int &M : FinalSourceHalfMask)
8985             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8986               M = InputsFixed[1] + SourceOffset;
8987             else if (M == InputsFixed[1] + SourceOffset)
8988               M = (InputsFixed[0] ^ 1) + SourceOffset;
8989
8990           InputsFixed[1] = InputsFixed[0] ^ 1;
8991         }
8992
8993         // Point everything at the fixed inputs.
8994         for (int &M : HalfMask)
8995           if (M == IncomingInputs[0])
8996             M = InputsFixed[0] + SourceOffset;
8997           else if (M == IncomingInputs[1])
8998             M = InputsFixed[1] + SourceOffset;
8999
9000         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9001         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9002       }
9003     } else {
9004       llvm_unreachable("Unhandled input size!");
9005     }
9006
9007     // Now hoist the DWord down to the right half.
9008     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9009     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9010     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9011     for (int &M : HalfMask)
9012       for (int Input : IncomingInputs)
9013         if (M == Input)
9014           M = FreeDWord * 2 + Input % 2;
9015   };
9016   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9017                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
9018   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9019                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
9020
9021   // Now enact all the shuffles we've computed to move the inputs into their
9022   // target half.
9023   if (!isNoopShuffleMask(PSHUFLMask))
9024     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9025                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9026   if (!isNoopShuffleMask(PSHUFHMask))
9027     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9028                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9029   if (!isNoopShuffleMask(PSHUFDMask))
9030     V = DAG.getBitcast(
9031         VT,
9032         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9033                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9034
9035   // At this point, each half should contain all its inputs, and we can then
9036   // just shuffle them into their final position.
9037   assert(std::count_if(LoMask.begin(), LoMask.end(),
9038                        [](int M) { return M >= 4; }) == 0 &&
9039          "Failed to lift all the high half inputs to the low mask!");
9040   assert(std::count_if(HiMask.begin(), HiMask.end(),
9041                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9042          "Failed to lift all the low half inputs to the high mask!");
9043
9044   // Do a half shuffle for the low mask.
9045   if (!isNoopShuffleMask(LoMask))
9046     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9047                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9048
9049   // Do a half shuffle with the high mask after shifting its values down.
9050   for (int &M : HiMask)
9051     if (M >= 0)
9052       M -= 4;
9053   if (!isNoopShuffleMask(HiMask))
9054     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9055                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9056
9057   return V;
9058 }
9059
9060 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9061 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9062                                           SDValue V2, ArrayRef<int> Mask,
9063                                           SelectionDAG &DAG, bool &V1InUse,
9064                                           bool &V2InUse) {
9065   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9066   SDValue V1Mask[16];
9067   SDValue V2Mask[16];
9068   V1InUse = false;
9069   V2InUse = false;
9070
9071   int Size = Mask.size();
9072   int Scale = 16 / Size;
9073   for (int i = 0; i < 16; ++i) {
9074     if (Mask[i / Scale] == -1) {
9075       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9076     } else {
9077       const int ZeroMask = 0x80;
9078       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9079                                           : ZeroMask;
9080       int V2Idx = Mask[i / Scale] < Size
9081                       ? ZeroMask
9082                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
9083       if (Zeroable[i / Scale])
9084         V1Idx = V2Idx = ZeroMask;
9085       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9086       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9087       V1InUse |= (ZeroMask != V1Idx);
9088       V2InUse |= (ZeroMask != V2Idx);
9089     }
9090   }
9091
9092   if (V1InUse)
9093     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9094                      DAG.getBitcast(MVT::v16i8, V1),
9095                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9096   if (V2InUse)
9097     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9098                      DAG.getBitcast(MVT::v16i8, V2),
9099                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9100
9101   // If we need shuffled inputs from both, blend the two.
9102   SDValue V;
9103   if (V1InUse && V2InUse)
9104     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9105   else
9106     V = V1InUse ? V1 : V2;
9107
9108   // Cast the result back to the correct type.
9109   return DAG.getBitcast(VT, V);
9110 }
9111
9112 /// \brief Generic lowering of 8-lane i16 shuffles.
9113 ///
9114 /// This handles both single-input shuffles and combined shuffle/blends with
9115 /// two inputs. The single input shuffles are immediately delegated to
9116 /// a dedicated lowering routine.
9117 ///
9118 /// The blends are lowered in one of three fundamental ways. If there are few
9119 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9120 /// of the input is significantly cheaper when lowered as an interleaving of
9121 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9122 /// halves of the inputs separately (making them have relatively few inputs)
9123 /// and then concatenate them.
9124 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9125                                        const X86Subtarget *Subtarget,
9126                                        SelectionDAG &DAG) {
9127   SDLoc DL(Op);
9128   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9129   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9130   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9131   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9132   ArrayRef<int> OrigMask = SVOp->getMask();
9133   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9134                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9135   MutableArrayRef<int> Mask(MaskStorage);
9136
9137   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9138
9139   // Whenever we can lower this as a zext, that instruction is strictly faster
9140   // than any alternative.
9141   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9142           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9143     return ZExt;
9144
9145   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9146   (void)isV1;
9147   auto isV2 = [](int M) { return M >= 8; };
9148
9149   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9150
9151   if (NumV2Inputs == 0) {
9152     // Check for being able to broadcast a single element.
9153     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9154                                                           Mask, Subtarget, DAG))
9155       return Broadcast;
9156
9157     // Try to use shift instructions.
9158     if (SDValue Shift =
9159             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9160       return Shift;
9161
9162     // Use dedicated unpack instructions for masks that match their pattern.
9163     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
9164       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
9165     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
9166       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
9167
9168     // Try to use byte rotation instructions.
9169     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9170                                                         Mask, Subtarget, DAG))
9171       return Rotate;
9172
9173     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9174                                                      Subtarget, DAG);
9175   }
9176
9177   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9178          "All single-input shuffles should be canonicalized to be V1-input "
9179          "shuffles.");
9180
9181   // Try to use shift instructions.
9182   if (SDValue Shift =
9183           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9184     return Shift;
9185
9186   // See if we can use SSE4A Extraction / Insertion.
9187   if (Subtarget->hasSSE4A())
9188     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9189       return V;
9190
9191   // There are special ways we can lower some single-element blends.
9192   if (NumV2Inputs == 1)
9193     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9194                                                          Mask, Subtarget, DAG))
9195       return V;
9196
9197   // We have different paths for blend lowering, but they all must use the
9198   // *exact* same predicate.
9199   bool IsBlendSupported = Subtarget->hasSSE41();
9200   if (IsBlendSupported)
9201     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9202                                                   Subtarget, DAG))
9203       return Blend;
9204
9205   if (SDValue Masked =
9206           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9207     return Masked;
9208
9209   // Use dedicated unpack instructions for masks that match their pattern.
9210   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
9211     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9212   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
9213     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9214
9215   // Try to use byte rotation instructions.
9216   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9217           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9218     return Rotate;
9219
9220   if (SDValue BitBlend =
9221           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9222     return BitBlend;
9223
9224   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9225                                                             V2, Mask, DAG))
9226     return Unpack;
9227
9228   // If we can't directly blend but can use PSHUFB, that will be better as it
9229   // can both shuffle and set up the inefficient blend.
9230   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9231     bool V1InUse, V2InUse;
9232     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9233                                       V1InUse, V2InUse);
9234   }
9235
9236   // We can always bit-blend if we have to so the fallback strategy is to
9237   // decompose into single-input permutes and blends.
9238   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9239                                                       Mask, DAG);
9240 }
9241
9242 /// \brief Check whether a compaction lowering can be done by dropping even
9243 /// elements and compute how many times even elements must be dropped.
9244 ///
9245 /// This handles shuffles which take every Nth element where N is a power of
9246 /// two. Example shuffle masks:
9247 ///
9248 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9249 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9250 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9251 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9252 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9253 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9254 ///
9255 /// Any of these lanes can of course be undef.
9256 ///
9257 /// This routine only supports N <= 3.
9258 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9259 /// for larger N.
9260 ///
9261 /// \returns N above, or the number of times even elements must be dropped if
9262 /// there is such a number. Otherwise returns zero.
9263 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9264   // Figure out whether we're looping over two inputs or just one.
9265   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9266
9267   // The modulus for the shuffle vector entries is based on whether this is
9268   // a single input or not.
9269   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9270   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9271          "We should only be called with masks with a power-of-2 size!");
9272
9273   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9274
9275   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9276   // and 2^3 simultaneously. This is because we may have ambiguity with
9277   // partially undef inputs.
9278   bool ViableForN[3] = {true, true, true};
9279
9280   for (int i = 0, e = Mask.size(); i < e; ++i) {
9281     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9282     // want.
9283     if (Mask[i] == -1)
9284       continue;
9285
9286     bool IsAnyViable = false;
9287     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9288       if (ViableForN[j]) {
9289         uint64_t N = j + 1;
9290
9291         // The shuffle mask must be equal to (i * 2^N) % M.
9292         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9293           IsAnyViable = true;
9294         else
9295           ViableForN[j] = false;
9296       }
9297     // Early exit if we exhaust the possible powers of two.
9298     if (!IsAnyViable)
9299       break;
9300   }
9301
9302   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9303     if (ViableForN[j])
9304       return j + 1;
9305
9306   // Return 0 as there is no viable power of two.
9307   return 0;
9308 }
9309
9310 /// \brief Generic lowering of v16i8 shuffles.
9311 ///
9312 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9313 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9314 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9315 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9316 /// back together.
9317 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9318                                        const X86Subtarget *Subtarget,
9319                                        SelectionDAG &DAG) {
9320   SDLoc DL(Op);
9321   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9322   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9323   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9324   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9325   ArrayRef<int> Mask = SVOp->getMask();
9326   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9327
9328   // Try to use shift instructions.
9329   if (SDValue Shift =
9330           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9331     return Shift;
9332
9333   // Try to use byte rotation instructions.
9334   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9335           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9336     return Rotate;
9337
9338   // Try to use a zext lowering.
9339   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9340           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9341     return ZExt;
9342
9343   // See if we can use SSE4A Extraction / Insertion.
9344   if (Subtarget->hasSSE4A())
9345     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9346       return V;
9347
9348   int NumV2Elements =
9349       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9350
9351   // For single-input shuffles, there are some nicer lowering tricks we can use.
9352   if (NumV2Elements == 0) {
9353     // Check for being able to broadcast a single element.
9354     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9355                                                           Mask, Subtarget, DAG))
9356       return Broadcast;
9357
9358     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9359     // Notably, this handles splat and partial-splat shuffles more efficiently.
9360     // However, it only makes sense if the pre-duplication shuffle simplifies
9361     // things significantly. Currently, this means we need to be able to
9362     // express the pre-duplication shuffle as an i16 shuffle.
9363     //
9364     // FIXME: We should check for other patterns which can be widened into an
9365     // i16 shuffle as well.
9366     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9367       for (int i = 0; i < 16; i += 2)
9368         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9369           return false;
9370
9371       return true;
9372     };
9373     auto tryToWidenViaDuplication = [&]() -> SDValue {
9374       if (!canWidenViaDuplication(Mask))
9375         return SDValue();
9376       SmallVector<int, 4> LoInputs;
9377       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9378                    [](int M) { return M >= 0 && M < 8; });
9379       std::sort(LoInputs.begin(), LoInputs.end());
9380       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9381                      LoInputs.end());
9382       SmallVector<int, 4> HiInputs;
9383       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9384                    [](int M) { return M >= 8; });
9385       std::sort(HiInputs.begin(), HiInputs.end());
9386       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9387                      HiInputs.end());
9388
9389       bool TargetLo = LoInputs.size() >= HiInputs.size();
9390       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9391       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9392
9393       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9394       SmallDenseMap<int, int, 8> LaneMap;
9395       for (int I : InPlaceInputs) {
9396         PreDupI16Shuffle[I/2] = I/2;
9397         LaneMap[I] = I;
9398       }
9399       int j = TargetLo ? 0 : 4, je = j + 4;
9400       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9401         // Check if j is already a shuffle of this input. This happens when
9402         // there are two adjacent bytes after we move the low one.
9403         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9404           // If we haven't yet mapped the input, search for a slot into which
9405           // we can map it.
9406           while (j < je && PreDupI16Shuffle[j] != -1)
9407             ++j;
9408
9409           if (j == je)
9410             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9411             return SDValue();
9412
9413           // Map this input with the i16 shuffle.
9414           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9415         }
9416
9417         // Update the lane map based on the mapping we ended up with.
9418         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9419       }
9420       V1 = DAG.getBitcast(
9421           MVT::v16i8,
9422           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9423                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9424
9425       // Unpack the bytes to form the i16s that will be shuffled into place.
9426       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9427                        MVT::v16i8, V1, V1);
9428
9429       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9430       for (int i = 0; i < 16; ++i)
9431         if (Mask[i] != -1) {
9432           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9433           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9434           if (PostDupI16Shuffle[i / 2] == -1)
9435             PostDupI16Shuffle[i / 2] = MappedMask;
9436           else
9437             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9438                    "Conflicting entrties in the original shuffle!");
9439         }
9440       return DAG.getBitcast(
9441           MVT::v16i8,
9442           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9443                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9444     };
9445     if (SDValue V = tryToWidenViaDuplication())
9446       return V;
9447   }
9448
9449   if (SDValue Masked =
9450           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9451     return Masked;
9452
9453   // Use dedicated unpack instructions for masks that match their pattern.
9454   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9455                                          0, 16, 1, 17, 2, 18, 3, 19,
9456                                          // High half.
9457                                          4, 20, 5, 21, 6, 22, 7, 23}))
9458     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9459   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9460                                          8, 24, 9, 25, 10, 26, 11, 27,
9461                                          // High half.
9462                                          12, 28, 13, 29, 14, 30, 15, 31}))
9463     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9464
9465   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9466   // with PSHUFB. It is important to do this before we attempt to generate any
9467   // blends but after all of the single-input lowerings. If the single input
9468   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9469   // want to preserve that and we can DAG combine any longer sequences into
9470   // a PSHUFB in the end. But once we start blending from multiple inputs,
9471   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9472   // and there are *very* few patterns that would actually be faster than the
9473   // PSHUFB approach because of its ability to zero lanes.
9474   //
9475   // FIXME: The only exceptions to the above are blends which are exact
9476   // interleavings with direct instructions supporting them. We currently don't
9477   // handle those well here.
9478   if (Subtarget->hasSSSE3()) {
9479     bool V1InUse = false;
9480     bool V2InUse = false;
9481
9482     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9483                                                 DAG, V1InUse, V2InUse);
9484
9485     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9486     // do so. This avoids using them to handle blends-with-zero which is
9487     // important as a single pshufb is significantly faster for that.
9488     if (V1InUse && V2InUse) {
9489       if (Subtarget->hasSSE41())
9490         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9491                                                       Mask, Subtarget, DAG))
9492           return Blend;
9493
9494       // We can use an unpack to do the blending rather than an or in some
9495       // cases. Even though the or may be (very minorly) more efficient, we
9496       // preference this lowering because there are common cases where part of
9497       // the complexity of the shuffles goes away when we do the final blend as
9498       // an unpack.
9499       // FIXME: It might be worth trying to detect if the unpack-feeding
9500       // shuffles will both be pshufb, in which case we shouldn't bother with
9501       // this.
9502       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9503               DL, MVT::v16i8, V1, V2, Mask, DAG))
9504         return Unpack;
9505     }
9506
9507     return PSHUFB;
9508   }
9509
9510   // There are special ways we can lower some single-element blends.
9511   if (NumV2Elements == 1)
9512     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9513                                                          Mask, Subtarget, DAG))
9514       return V;
9515
9516   if (SDValue BitBlend =
9517           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9518     return BitBlend;
9519
9520   // Check whether a compaction lowering can be done. This handles shuffles
9521   // which take every Nth element for some even N. See the helper function for
9522   // details.
9523   //
9524   // We special case these as they can be particularly efficiently handled with
9525   // the PACKUSB instruction on x86 and they show up in common patterns of
9526   // rearranging bytes to truncate wide elements.
9527   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9528     // NumEvenDrops is the power of two stride of the elements. Another way of
9529     // thinking about it is that we need to drop the even elements this many
9530     // times to get the original input.
9531     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9532
9533     // First we need to zero all the dropped bytes.
9534     assert(NumEvenDrops <= 3 &&
9535            "No support for dropping even elements more than 3 times.");
9536     // We use the mask type to pick which bytes are preserved based on how many
9537     // elements are dropped.
9538     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9539     SDValue ByteClearMask = DAG.getBitcast(
9540         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9541     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9542     if (!IsSingleInput)
9543       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9544
9545     // Now pack things back together.
9546     V1 = DAG.getBitcast(MVT::v8i16, V1);
9547     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9548     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9549     for (int i = 1; i < NumEvenDrops; ++i) {
9550       Result = DAG.getBitcast(MVT::v8i16, Result);
9551       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9552     }
9553
9554     return Result;
9555   }
9556
9557   // Handle multi-input cases by blending single-input shuffles.
9558   if (NumV2Elements > 0)
9559     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9560                                                       Mask, DAG);
9561
9562   // The fallback path for single-input shuffles widens this into two v8i16
9563   // vectors with unpacks, shuffles those, and then pulls them back together
9564   // with a pack.
9565   SDValue V = V1;
9566
9567   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9568   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9569   for (int i = 0; i < 16; ++i)
9570     if (Mask[i] >= 0)
9571       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9572
9573   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9574
9575   SDValue VLoHalf, VHiHalf;
9576   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9577   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9578   // i16s.
9579   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9580                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9581       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9582                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9583     // Use a mask to drop the high bytes.
9584     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9585     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9586                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9587
9588     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9589     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9590
9591     // Squash the masks to point directly into VLoHalf.
9592     for (int &M : LoBlendMask)
9593       if (M >= 0)
9594         M /= 2;
9595     for (int &M : HiBlendMask)
9596       if (M >= 0)
9597         M /= 2;
9598   } else {
9599     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9600     // VHiHalf so that we can blend them as i16s.
9601     VLoHalf = DAG.getBitcast(
9602         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9603     VHiHalf = DAG.getBitcast(
9604         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9605   }
9606
9607   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9608   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9609
9610   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9611 }
9612
9613 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9614 ///
9615 /// This routine breaks down the specific type of 128-bit shuffle and
9616 /// dispatches to the lowering routines accordingly.
9617 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9618                                         MVT VT, const X86Subtarget *Subtarget,
9619                                         SelectionDAG &DAG) {
9620   switch (VT.SimpleTy) {
9621   case MVT::v2i64:
9622     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9623   case MVT::v2f64:
9624     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9625   case MVT::v4i32:
9626     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9627   case MVT::v4f32:
9628     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9629   case MVT::v8i16:
9630     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9631   case MVT::v16i8:
9632     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9633
9634   default:
9635     llvm_unreachable("Unimplemented!");
9636   }
9637 }
9638
9639 /// \brief Helper function to test whether a shuffle mask could be
9640 /// simplified by widening the elements being shuffled.
9641 ///
9642 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9643 /// leaves it in an unspecified state.
9644 ///
9645 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9646 /// shuffle masks. The latter have the special property of a '-2' representing
9647 /// a zero-ed lane of a vector.
9648 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9649                                     SmallVectorImpl<int> &WidenedMask) {
9650   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9651     // If both elements are undef, its trivial.
9652     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9653       WidenedMask.push_back(SM_SentinelUndef);
9654       continue;
9655     }
9656
9657     // Check for an undef mask and a mask value properly aligned to fit with
9658     // a pair of values. If we find such a case, use the non-undef mask's value.
9659     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9660       WidenedMask.push_back(Mask[i + 1] / 2);
9661       continue;
9662     }
9663     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9664       WidenedMask.push_back(Mask[i] / 2);
9665       continue;
9666     }
9667
9668     // When zeroing, we need to spread the zeroing across both lanes to widen.
9669     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9670       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9671           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9672         WidenedMask.push_back(SM_SentinelZero);
9673         continue;
9674       }
9675       return false;
9676     }
9677
9678     // Finally check if the two mask values are adjacent and aligned with
9679     // a pair.
9680     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9681       WidenedMask.push_back(Mask[i] / 2);
9682       continue;
9683     }
9684
9685     // Otherwise we can't safely widen the elements used in this shuffle.
9686     return false;
9687   }
9688   assert(WidenedMask.size() == Mask.size() / 2 &&
9689          "Incorrect size of mask after widening the elements!");
9690
9691   return true;
9692 }
9693
9694 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9695 ///
9696 /// This routine just extracts two subvectors, shuffles them independently, and
9697 /// then concatenates them back together. This should work effectively with all
9698 /// AVX vector shuffle types.
9699 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9700                                           SDValue V2, ArrayRef<int> Mask,
9701                                           SelectionDAG &DAG) {
9702   assert(VT.getSizeInBits() >= 256 &&
9703          "Only for 256-bit or wider vector shuffles!");
9704   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9705   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9706
9707   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9708   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9709
9710   int NumElements = VT.getVectorNumElements();
9711   int SplitNumElements = NumElements / 2;
9712   MVT ScalarVT = VT.getScalarType();
9713   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9714
9715   // Rather than splitting build-vectors, just build two narrower build
9716   // vectors. This helps shuffling with splats and zeros.
9717   auto SplitVector = [&](SDValue V) {
9718     while (V.getOpcode() == ISD::BITCAST)
9719       V = V->getOperand(0);
9720
9721     MVT OrigVT = V.getSimpleValueType();
9722     int OrigNumElements = OrigVT.getVectorNumElements();
9723     int OrigSplitNumElements = OrigNumElements / 2;
9724     MVT OrigScalarVT = OrigVT.getScalarType();
9725     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9726
9727     SDValue LoV, HiV;
9728
9729     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9730     if (!BV) {
9731       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9732                         DAG.getIntPtrConstant(0, DL));
9733       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9734                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9735     } else {
9736
9737       SmallVector<SDValue, 16> LoOps, HiOps;
9738       for (int i = 0; i < OrigSplitNumElements; ++i) {
9739         LoOps.push_back(BV->getOperand(i));
9740         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9741       }
9742       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9743       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9744     }
9745     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9746                           DAG.getBitcast(SplitVT, HiV));
9747   };
9748
9749   SDValue LoV1, HiV1, LoV2, HiV2;
9750   std::tie(LoV1, HiV1) = SplitVector(V1);
9751   std::tie(LoV2, HiV2) = SplitVector(V2);
9752
9753   // Now create two 4-way blends of these half-width vectors.
9754   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9755     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9756     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9757     for (int i = 0; i < SplitNumElements; ++i) {
9758       int M = HalfMask[i];
9759       if (M >= NumElements) {
9760         if (M >= NumElements + SplitNumElements)
9761           UseHiV2 = true;
9762         else
9763           UseLoV2 = true;
9764         V2BlendMask.push_back(M - NumElements);
9765         V1BlendMask.push_back(-1);
9766         BlendMask.push_back(SplitNumElements + i);
9767       } else if (M >= 0) {
9768         if (M >= SplitNumElements)
9769           UseHiV1 = true;
9770         else
9771           UseLoV1 = true;
9772         V2BlendMask.push_back(-1);
9773         V1BlendMask.push_back(M);
9774         BlendMask.push_back(i);
9775       } else {
9776         V2BlendMask.push_back(-1);
9777         V1BlendMask.push_back(-1);
9778         BlendMask.push_back(-1);
9779       }
9780     }
9781
9782     // Because the lowering happens after all combining takes place, we need to
9783     // manually combine these blend masks as much as possible so that we create
9784     // a minimal number of high-level vector shuffle nodes.
9785
9786     // First try just blending the halves of V1 or V2.
9787     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9788       return DAG.getUNDEF(SplitVT);
9789     if (!UseLoV2 && !UseHiV2)
9790       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9791     if (!UseLoV1 && !UseHiV1)
9792       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9793
9794     SDValue V1Blend, V2Blend;
9795     if (UseLoV1 && UseHiV1) {
9796       V1Blend =
9797         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9798     } else {
9799       // We only use half of V1 so map the usage down into the final blend mask.
9800       V1Blend = UseLoV1 ? LoV1 : HiV1;
9801       for (int i = 0; i < SplitNumElements; ++i)
9802         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9803           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9804     }
9805     if (UseLoV2 && UseHiV2) {
9806       V2Blend =
9807         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9808     } else {
9809       // We only use half of V2 so map the usage down into the final blend mask.
9810       V2Blend = UseLoV2 ? LoV2 : HiV2;
9811       for (int i = 0; i < SplitNumElements; ++i)
9812         if (BlendMask[i] >= SplitNumElements)
9813           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9814     }
9815     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9816   };
9817   SDValue Lo = HalfBlend(LoMask);
9818   SDValue Hi = HalfBlend(HiMask);
9819   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9820 }
9821
9822 /// \brief Either split a vector in halves or decompose the shuffles and the
9823 /// blend.
9824 ///
9825 /// This is provided as a good fallback for many lowerings of non-single-input
9826 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9827 /// between splitting the shuffle into 128-bit components and stitching those
9828 /// back together vs. extracting the single-input shuffles and blending those
9829 /// results.
9830 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9831                                                 SDValue V2, ArrayRef<int> Mask,
9832                                                 SelectionDAG &DAG) {
9833   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9834                                             "lower single-input shuffles as it "
9835                                             "could then recurse on itself.");
9836   int Size = Mask.size();
9837
9838   // If this can be modeled as a broadcast of two elements followed by a blend,
9839   // prefer that lowering. This is especially important because broadcasts can
9840   // often fold with memory operands.
9841   auto DoBothBroadcast = [&] {
9842     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9843     for (int M : Mask)
9844       if (M >= Size) {
9845         if (V2BroadcastIdx == -1)
9846           V2BroadcastIdx = M - Size;
9847         else if (M - Size != V2BroadcastIdx)
9848           return false;
9849       } else if (M >= 0) {
9850         if (V1BroadcastIdx == -1)
9851           V1BroadcastIdx = M;
9852         else if (M != V1BroadcastIdx)
9853           return false;
9854       }
9855     return true;
9856   };
9857   if (DoBothBroadcast())
9858     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9859                                                       DAG);
9860
9861   // If the inputs all stem from a single 128-bit lane of each input, then we
9862   // split them rather than blending because the split will decompose to
9863   // unusually few instructions.
9864   int LaneCount = VT.getSizeInBits() / 128;
9865   int LaneSize = Size / LaneCount;
9866   SmallBitVector LaneInputs[2];
9867   LaneInputs[0].resize(LaneCount, false);
9868   LaneInputs[1].resize(LaneCount, false);
9869   for (int i = 0; i < Size; ++i)
9870     if (Mask[i] >= 0)
9871       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9872   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9873     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9874
9875   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9876   // that the decomposed single-input shuffles don't end up here.
9877   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9878 }
9879
9880 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9881 /// a permutation and blend of those lanes.
9882 ///
9883 /// This essentially blends the out-of-lane inputs to each lane into the lane
9884 /// from a permuted copy of the vector. This lowering strategy results in four
9885 /// instructions in the worst case for a single-input cross lane shuffle which
9886 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9887 /// of. Special cases for each particular shuffle pattern should be handled
9888 /// prior to trying this lowering.
9889 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9890                                                        SDValue V1, SDValue V2,
9891                                                        ArrayRef<int> Mask,
9892                                                        SelectionDAG &DAG) {
9893   // FIXME: This should probably be generalized for 512-bit vectors as well.
9894   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9895   int LaneSize = Mask.size() / 2;
9896
9897   // If there are only inputs from one 128-bit lane, splitting will in fact be
9898   // less expensive. The flags track whether the given lane contains an element
9899   // that crosses to another lane.
9900   bool LaneCrossing[2] = {false, false};
9901   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9902     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9903       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9904   if (!LaneCrossing[0] || !LaneCrossing[1])
9905     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9906
9907   if (isSingleInputShuffleMask(Mask)) {
9908     SmallVector<int, 32> FlippedBlendMask;
9909     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9910       FlippedBlendMask.push_back(
9911           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9912                                   ? Mask[i]
9913                                   : Mask[i] % LaneSize +
9914                                         (i / LaneSize) * LaneSize + Size));
9915
9916     // Flip the vector, and blend the results which should now be in-lane. The
9917     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9918     // 5 for the high source. The value 3 selects the high half of source 2 and
9919     // the value 2 selects the low half of source 2. We only use source 2 to
9920     // allow folding it into a memory operand.
9921     unsigned PERMMask = 3 | 2 << 4;
9922     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9923                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9924     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9925   }
9926
9927   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9928   // will be handled by the above logic and a blend of the results, much like
9929   // other patterns in AVX.
9930   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9931 }
9932
9933 /// \brief Handle lowering 2-lane 128-bit shuffles.
9934 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9935                                         SDValue V2, ArrayRef<int> Mask,
9936                                         const X86Subtarget *Subtarget,
9937                                         SelectionDAG &DAG) {
9938   // TODO: If minimizing size and one of the inputs is a zero vector and the
9939   // the zero vector has only one use, we could use a VPERM2X128 to save the
9940   // instruction bytes needed to explicitly generate the zero vector.
9941
9942   // Blends are faster and handle all the non-lane-crossing cases.
9943   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9944                                                 Subtarget, DAG))
9945     return Blend;
9946
9947   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9948   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9949
9950   // If either input operand is a zero vector, use VPERM2X128 because its mask
9951   // allows us to replace the zero input with an implicit zero.
9952   if (!IsV1Zero && !IsV2Zero) {
9953     // Check for patterns which can be matched with a single insert of a 128-bit
9954     // subvector.
9955     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9956     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9957       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9958                                    VT.getVectorNumElements() / 2);
9959       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9960                                 DAG.getIntPtrConstant(0, DL));
9961       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9962                                 OnlyUsesV1 ? V1 : V2,
9963                                 DAG.getIntPtrConstant(0, DL));
9964       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9965     }
9966   }
9967
9968   // Otherwise form a 128-bit permutation. After accounting for undefs,
9969   // convert the 64-bit shuffle mask selection values into 128-bit
9970   // selection bits by dividing the indexes by 2 and shifting into positions
9971   // defined by a vperm2*128 instruction's immediate control byte.
9972
9973   // The immediate permute control byte looks like this:
9974   //    [1:0] - select 128 bits from sources for low half of destination
9975   //    [2]   - ignore
9976   //    [3]   - zero low half of destination
9977   //    [5:4] - select 128 bits from sources for high half of destination
9978   //    [6]   - ignore
9979   //    [7]   - zero high half of destination
9980
9981   int MaskLO = Mask[0];
9982   if (MaskLO == SM_SentinelUndef)
9983     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9984
9985   int MaskHI = Mask[2];
9986   if (MaskHI == SM_SentinelUndef)
9987     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9988
9989   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9990
9991   // If either input is a zero vector, replace it with an undef input.
9992   // Shuffle mask values <  4 are selecting elements of V1.
9993   // Shuffle mask values >= 4 are selecting elements of V2.
9994   // Adjust each half of the permute mask by clearing the half that was
9995   // selecting the zero vector and setting the zero mask bit.
9996   if (IsV1Zero) {
9997     V1 = DAG.getUNDEF(VT);
9998     if (MaskLO < 4)
9999       PermMask = (PermMask & 0xf0) | 0x08;
10000     if (MaskHI < 4)
10001       PermMask = (PermMask & 0x0f) | 0x80;
10002   }
10003   if (IsV2Zero) {
10004     V2 = DAG.getUNDEF(VT);
10005     if (MaskLO >= 4)
10006       PermMask = (PermMask & 0xf0) | 0x08;
10007     if (MaskHI >= 4)
10008       PermMask = (PermMask & 0x0f) | 0x80;
10009   }
10010
10011   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10012                      DAG.getConstant(PermMask, DL, MVT::i8));
10013 }
10014
10015 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10016 /// shuffling each lane.
10017 ///
10018 /// This will only succeed when the result of fixing the 128-bit lanes results
10019 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10020 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10021 /// the lane crosses early and then use simpler shuffles within each lane.
10022 ///
10023 /// FIXME: It might be worthwhile at some point to support this without
10024 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10025 /// in x86 only floating point has interesting non-repeating shuffles, and even
10026 /// those are still *marginally* more expensive.
10027 static SDValue lowerVectorShuffleByMerging128BitLanes(
10028     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10029     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10030   assert(!isSingleInputShuffleMask(Mask) &&
10031          "This is only useful with multiple inputs.");
10032
10033   int Size = Mask.size();
10034   int LaneSize = 128 / VT.getScalarSizeInBits();
10035   int NumLanes = Size / LaneSize;
10036   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10037
10038   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10039   // check whether the in-128-bit lane shuffles share a repeating pattern.
10040   SmallVector<int, 4> Lanes;
10041   Lanes.resize(NumLanes, -1);
10042   SmallVector<int, 4> InLaneMask;
10043   InLaneMask.resize(LaneSize, -1);
10044   for (int i = 0; i < Size; ++i) {
10045     if (Mask[i] < 0)
10046       continue;
10047
10048     int j = i / LaneSize;
10049
10050     if (Lanes[j] < 0) {
10051       // First entry we've seen for this lane.
10052       Lanes[j] = Mask[i] / LaneSize;
10053     } else if (Lanes[j] != Mask[i] / LaneSize) {
10054       // This doesn't match the lane selected previously!
10055       return SDValue();
10056     }
10057
10058     // Check that within each lane we have a consistent shuffle mask.
10059     int k = i % LaneSize;
10060     if (InLaneMask[k] < 0) {
10061       InLaneMask[k] = Mask[i] % LaneSize;
10062     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10063       // This doesn't fit a repeating in-lane mask.
10064       return SDValue();
10065     }
10066   }
10067
10068   // First shuffle the lanes into place.
10069   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10070                                 VT.getSizeInBits() / 64);
10071   SmallVector<int, 8> LaneMask;
10072   LaneMask.resize(NumLanes * 2, -1);
10073   for (int i = 0; i < NumLanes; ++i)
10074     if (Lanes[i] >= 0) {
10075       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10076       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10077     }
10078
10079   V1 = DAG.getBitcast(LaneVT, V1);
10080   V2 = DAG.getBitcast(LaneVT, V2);
10081   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10082
10083   // Cast it back to the type we actually want.
10084   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10085
10086   // Now do a simple shuffle that isn't lane crossing.
10087   SmallVector<int, 8> NewMask;
10088   NewMask.resize(Size, -1);
10089   for (int i = 0; i < Size; ++i)
10090     if (Mask[i] >= 0)
10091       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10092   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10093          "Must not introduce lane crosses at this point!");
10094
10095   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10096 }
10097
10098 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10099 /// given mask.
10100 ///
10101 /// This returns true if the elements from a particular input are already in the
10102 /// slot required by the given mask and require no permutation.
10103 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10104   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10105   int Size = Mask.size();
10106   for (int i = 0; i < Size; ++i)
10107     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10108       return false;
10109
10110   return true;
10111 }
10112
10113 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10114                                             ArrayRef<int> Mask, SDValue V1,
10115                                             SDValue V2, SelectionDAG &DAG) {
10116
10117   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
10118   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
10119   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10120   int NumElts = VT.getVectorNumElements();
10121   bool ShufpdMask = true;
10122   bool CommutableMask = true;
10123   unsigned Immediate = 0;
10124   for (int i = 0; i < NumElts; ++i) {
10125     if (Mask[i] < 0)
10126       continue;
10127     int Val = (i & 6) + NumElts * (i & 1);
10128     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10129     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10130       ShufpdMask = false;
10131     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10132       CommutableMask = false;
10133     Immediate |= (Mask[i] % 2) << i;
10134   }
10135   if (ShufpdMask)
10136     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10137                        DAG.getConstant(Immediate, DL, MVT::i8));
10138   if (CommutableMask)
10139     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10140                        DAG.getConstant(Immediate, DL, MVT::i8));
10141   return SDValue();
10142 }
10143
10144 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10145 ///
10146 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10147 /// isn't available.
10148 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10149                                        const X86Subtarget *Subtarget,
10150                                        SelectionDAG &DAG) {
10151   SDLoc DL(Op);
10152   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10153   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10154   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10155   ArrayRef<int> Mask = SVOp->getMask();
10156   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10157
10158   SmallVector<int, 4> WidenedMask;
10159   if (canWidenShuffleElements(Mask, WidenedMask))
10160     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10161                                     DAG);
10162
10163   if (isSingleInputShuffleMask(Mask)) {
10164     // Check for being able to broadcast a single element.
10165     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10166                                                           Mask, Subtarget, DAG))
10167       return Broadcast;
10168
10169     // Use low duplicate instructions for masks that match their pattern.
10170     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10171       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10172
10173     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10174       // Non-half-crossing single input shuffles can be lowerid with an
10175       // interleaved permutation.
10176       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10177                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10178       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10179                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10180     }
10181
10182     // With AVX2 we have direct support for this permutation.
10183     if (Subtarget->hasAVX2())
10184       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10185                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10186
10187     // Otherwise, fall back.
10188     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10189                                                    DAG);
10190   }
10191
10192   // X86 has dedicated unpack instructions that can handle specific blend
10193   // operations: UNPCKH and UNPCKL.
10194   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10195     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
10196   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10197     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
10198   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10199     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
10200   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10201     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
10202
10203   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10204                                                 Subtarget, DAG))
10205     return Blend;
10206
10207   // Check if the blend happens to exactly fit that of SHUFPD.
10208   if (SDValue Op =
10209       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10210     return Op;
10211
10212   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10213   // shuffle. However, if we have AVX2 and either inputs are already in place,
10214   // we will be able to shuffle even across lanes the other input in a single
10215   // instruction so skip this pattern.
10216   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10217                                  isShuffleMaskInputInPlace(1, Mask))))
10218     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10219             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10220       return Result;
10221
10222   // If we have AVX2 then we always want to lower with a blend because an v4 we
10223   // can fully permute the elements.
10224   if (Subtarget->hasAVX2())
10225     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10226                                                       Mask, DAG);
10227
10228   // Otherwise fall back on generic lowering.
10229   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10230 }
10231
10232 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10233 ///
10234 /// This routine is only called when we have AVX2 and thus a reasonable
10235 /// instruction set for v4i64 shuffling..
10236 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10237                                        const X86Subtarget *Subtarget,
10238                                        SelectionDAG &DAG) {
10239   SDLoc DL(Op);
10240   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10241   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10242   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10243   ArrayRef<int> Mask = SVOp->getMask();
10244   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10245   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10246
10247   SmallVector<int, 4> WidenedMask;
10248   if (canWidenShuffleElements(Mask, WidenedMask))
10249     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10250                                     DAG);
10251
10252   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10253                                                 Subtarget, DAG))
10254     return Blend;
10255
10256   // Check for being able to broadcast a single element.
10257   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10258                                                         Mask, Subtarget, DAG))
10259     return Broadcast;
10260
10261   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10262   // use lower latency instructions that will operate on both 128-bit lanes.
10263   SmallVector<int, 2> RepeatedMask;
10264   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10265     if (isSingleInputShuffleMask(Mask)) {
10266       int PSHUFDMask[] = {-1, -1, -1, -1};
10267       for (int i = 0; i < 2; ++i)
10268         if (RepeatedMask[i] >= 0) {
10269           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10270           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10271         }
10272       return DAG.getBitcast(
10273           MVT::v4i64,
10274           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10275                       DAG.getBitcast(MVT::v8i32, V1),
10276                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10277     }
10278   }
10279
10280   // AVX2 provides a direct instruction for permuting a single input across
10281   // lanes.
10282   if (isSingleInputShuffleMask(Mask))
10283     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10284                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10285
10286   // Try to use shift instructions.
10287   if (SDValue Shift =
10288           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10289     return Shift;
10290
10291   // Use dedicated unpack instructions for masks that match their pattern.
10292   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10293     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
10294   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10295     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
10296   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10297     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
10298   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10299     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
10300
10301   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10302   // shuffle. However, if we have AVX2 and either inputs are already in place,
10303   // we will be able to shuffle even across lanes the other input in a single
10304   // instruction so skip this pattern.
10305   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10306                                  isShuffleMaskInputInPlace(1, Mask))))
10307     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10308             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10309       return Result;
10310
10311   // Otherwise fall back on generic blend lowering.
10312   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10313                                                     Mask, DAG);
10314 }
10315
10316 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10317 ///
10318 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10319 /// isn't available.
10320 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10321                                        const X86Subtarget *Subtarget,
10322                                        SelectionDAG &DAG) {
10323   SDLoc DL(Op);
10324   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10325   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10326   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10327   ArrayRef<int> Mask = SVOp->getMask();
10328   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10329
10330   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10331                                                 Subtarget, DAG))
10332     return Blend;
10333
10334   // Check for being able to broadcast a single element.
10335   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10336                                                         Mask, Subtarget, DAG))
10337     return Broadcast;
10338
10339   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10340   // options to efficiently lower the shuffle.
10341   SmallVector<int, 4> RepeatedMask;
10342   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10343     assert(RepeatedMask.size() == 4 &&
10344            "Repeated masks must be half the mask width!");
10345
10346     // Use even/odd duplicate instructions for masks that match their pattern.
10347     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10348       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10349     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10350       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10351
10352     if (isSingleInputShuffleMask(Mask))
10353       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10354                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10355
10356     // Use dedicated unpack instructions for masks that match their pattern.
10357     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10358       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10359     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10360       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10361     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10362       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10363     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10364       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10365
10366     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10367     // have already handled any direct blends. We also need to squash the
10368     // repeated mask into a simulated v4f32 mask.
10369     for (int i = 0; i < 4; ++i)
10370       if (RepeatedMask[i] >= 8)
10371         RepeatedMask[i] -= 4;
10372     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10373   }
10374
10375   // If we have a single input shuffle with different shuffle patterns in the
10376   // two 128-bit lanes use the variable mask to VPERMILPS.
10377   if (isSingleInputShuffleMask(Mask)) {
10378     SDValue VPermMask[8];
10379     for (int i = 0; i < 8; ++i)
10380       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10381                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10382     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10383       return DAG.getNode(
10384           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10385           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10386
10387     if (Subtarget->hasAVX2())
10388       return DAG.getNode(
10389           X86ISD::VPERMV, DL, MVT::v8f32,
10390           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10391                                                  MVT::v8i32, VPermMask)),
10392           V1);
10393
10394     // Otherwise, fall back.
10395     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10396                                                    DAG);
10397   }
10398
10399   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10400   // shuffle.
10401   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10402           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10403     return Result;
10404
10405   // If we have AVX2 then we always want to lower with a blend because at v8 we
10406   // can fully permute the elements.
10407   if (Subtarget->hasAVX2())
10408     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10409                                                       Mask, DAG);
10410
10411   // Otherwise fall back on generic lowering.
10412   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10413 }
10414
10415 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10416 ///
10417 /// This routine is only called when we have AVX2 and thus a reasonable
10418 /// instruction set for v8i32 shuffling..
10419 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10420                                        const X86Subtarget *Subtarget,
10421                                        SelectionDAG &DAG) {
10422   SDLoc DL(Op);
10423   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10424   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10425   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10426   ArrayRef<int> Mask = SVOp->getMask();
10427   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10428   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10429
10430   // Whenever we can lower this as a zext, that instruction is strictly faster
10431   // than any alternative. It also allows us to fold memory operands into the
10432   // shuffle in many cases.
10433   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10434                                                          Mask, Subtarget, DAG))
10435     return ZExt;
10436
10437   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10438                                                 Subtarget, DAG))
10439     return Blend;
10440
10441   // Check for being able to broadcast a single element.
10442   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10443                                                         Mask, Subtarget, DAG))
10444     return Broadcast;
10445
10446   // If the shuffle mask is repeated in each 128-bit lane we can use more
10447   // efficient instructions that mirror the shuffles across the two 128-bit
10448   // lanes.
10449   SmallVector<int, 4> RepeatedMask;
10450   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10451     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10452     if (isSingleInputShuffleMask(Mask))
10453       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10454                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10455
10456     // Use dedicated unpack instructions for masks that match their pattern.
10457     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10458       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10459     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10460       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10461     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10462       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10463     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10464       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10465   }
10466
10467   // Try to use shift instructions.
10468   if (SDValue Shift =
10469           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10470     return Shift;
10471
10472   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10473           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10474     return Rotate;
10475
10476   // If the shuffle patterns aren't repeated but it is a single input, directly
10477   // generate a cross-lane VPERMD instruction.
10478   if (isSingleInputShuffleMask(Mask)) {
10479     SDValue VPermMask[8];
10480     for (int i = 0; i < 8; ++i)
10481       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10482                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10483     return DAG.getNode(
10484         X86ISD::VPERMV, DL, MVT::v8i32,
10485         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10486   }
10487
10488   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10489   // shuffle.
10490   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10491           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10492     return Result;
10493
10494   // Otherwise fall back on generic blend lowering.
10495   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10496                                                     Mask, DAG);
10497 }
10498
10499 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10500 ///
10501 /// This routine is only called when we have AVX2 and thus a reasonable
10502 /// instruction set for v16i16 shuffling..
10503 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10504                                         const X86Subtarget *Subtarget,
10505                                         SelectionDAG &DAG) {
10506   SDLoc DL(Op);
10507   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10508   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10509   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10510   ArrayRef<int> Mask = SVOp->getMask();
10511   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10512   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10513
10514   // Whenever we can lower this as a zext, that instruction is strictly faster
10515   // than any alternative. It also allows us to fold memory operands into the
10516   // shuffle in many cases.
10517   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10518                                                          Mask, Subtarget, DAG))
10519     return ZExt;
10520
10521   // Check for being able to broadcast a single element.
10522   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10523                                                         Mask, Subtarget, DAG))
10524     return Broadcast;
10525
10526   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10527                                                 Subtarget, DAG))
10528     return Blend;
10529
10530   // Use dedicated unpack instructions for masks that match their pattern.
10531   if (isShuffleEquivalent(V1, V2, Mask,
10532                           {// First 128-bit lane:
10533                            0, 16, 1, 17, 2, 18, 3, 19,
10534                            // Second 128-bit lane:
10535                            8, 24, 9, 25, 10, 26, 11, 27}))
10536     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10537   if (isShuffleEquivalent(V1, V2, Mask,
10538                           {// First 128-bit lane:
10539                            4, 20, 5, 21, 6, 22, 7, 23,
10540                            // Second 128-bit lane:
10541                            12, 28, 13, 29, 14, 30, 15, 31}))
10542     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10543
10544   // Try to use shift instructions.
10545   if (SDValue Shift =
10546           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10547     return Shift;
10548
10549   // Try to use byte rotation instructions.
10550   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10551           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10552     return Rotate;
10553
10554   if (isSingleInputShuffleMask(Mask)) {
10555     // There are no generalized cross-lane shuffle operations available on i16
10556     // element types.
10557     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10558       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10559                                                      Mask, DAG);
10560
10561     SmallVector<int, 8> RepeatedMask;
10562     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10563       // As this is a single-input shuffle, the repeated mask should be
10564       // a strictly valid v8i16 mask that we can pass through to the v8i16
10565       // lowering to handle even the v16 case.
10566       return lowerV8I16GeneralSingleInputVectorShuffle(
10567           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10568     }
10569
10570     SDValue PSHUFBMask[32];
10571     for (int i = 0; i < 16; ++i) {
10572       if (Mask[i] == -1) {
10573         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10574         continue;
10575       }
10576
10577       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10578       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10579       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10580       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10581     }
10582     return DAG.getBitcast(MVT::v16i16,
10583                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10584                                       DAG.getBitcast(MVT::v32i8, V1),
10585                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10586                                                   MVT::v32i8, PSHUFBMask)));
10587   }
10588
10589   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10590   // shuffle.
10591   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10592           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10593     return Result;
10594
10595   // Otherwise fall back on generic lowering.
10596   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10597 }
10598
10599 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10600 ///
10601 /// This routine is only called when we have AVX2 and thus a reasonable
10602 /// instruction set for v32i8 shuffling..
10603 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10604                                        const X86Subtarget *Subtarget,
10605                                        SelectionDAG &DAG) {
10606   SDLoc DL(Op);
10607   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10608   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10609   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10610   ArrayRef<int> Mask = SVOp->getMask();
10611   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10612   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10613
10614   // Whenever we can lower this as a zext, that instruction is strictly faster
10615   // than any alternative. It also allows us to fold memory operands into the
10616   // shuffle in many cases.
10617   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10618                                                          Mask, Subtarget, DAG))
10619     return ZExt;
10620
10621   // Check for being able to broadcast a single element.
10622   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10623                                                         Mask, Subtarget, DAG))
10624     return Broadcast;
10625
10626   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10627                                                 Subtarget, DAG))
10628     return Blend;
10629
10630   // Use dedicated unpack instructions for masks that match their pattern.
10631   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10632   // 256-bit lanes.
10633   if (isShuffleEquivalent(
10634           V1, V2, Mask,
10635           {// First 128-bit lane:
10636            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10637            // Second 128-bit lane:
10638            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10639     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10640   if (isShuffleEquivalent(
10641           V1, V2, Mask,
10642           {// First 128-bit lane:
10643            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10644            // Second 128-bit lane:
10645            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10646     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10647
10648   // Try to use shift instructions.
10649   if (SDValue Shift =
10650           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10651     return Shift;
10652
10653   // Try to use byte rotation instructions.
10654   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10655           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10656     return Rotate;
10657
10658   if (isSingleInputShuffleMask(Mask)) {
10659     // There are no generalized cross-lane shuffle operations available on i8
10660     // element types.
10661     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10662       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10663                                                      Mask, DAG);
10664
10665     SDValue PSHUFBMask[32];
10666     for (int i = 0; i < 32; ++i)
10667       PSHUFBMask[i] =
10668           Mask[i] < 0
10669               ? DAG.getUNDEF(MVT::i8)
10670               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10671                                 MVT::i8);
10672
10673     return DAG.getNode(
10674         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10675         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10676   }
10677
10678   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10679   // shuffle.
10680   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10681           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10682     return Result;
10683
10684   // Otherwise fall back on generic lowering.
10685   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10686 }
10687
10688 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10689 ///
10690 /// This routine either breaks down the specific type of a 256-bit x86 vector
10691 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10692 /// together based on the available instructions.
10693 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10694                                         MVT VT, const X86Subtarget *Subtarget,
10695                                         SelectionDAG &DAG) {
10696   SDLoc DL(Op);
10697   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10698   ArrayRef<int> Mask = SVOp->getMask();
10699
10700   // If we have a single input to the zero element, insert that into V1 if we
10701   // can do so cheaply.
10702   int NumElts = VT.getVectorNumElements();
10703   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10704     return M >= NumElts;
10705   });
10706
10707   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10708     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10709                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10710       return Insertion;
10711
10712   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
10713   // can check for those subtargets here and avoid much of the subtarget
10714   // querying in the per-vector-type lowering routines. With AVX1 we have
10715   // essentially *zero* ability to manipulate a 256-bit vector with integer
10716   // types. Since we'll use floating point types there eventually, just
10717   // immediately cast everything to a float and operate entirely in that domain.
10718   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10719     int ElementBits = VT.getScalarSizeInBits();
10720     if (ElementBits < 32)
10721       // No floating point type available, decompose into 128-bit vectors.
10722       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10723
10724     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10725                                 VT.getVectorNumElements());
10726     V1 = DAG.getBitcast(FpVT, V1);
10727     V2 = DAG.getBitcast(FpVT, V2);
10728     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10729   }
10730
10731   switch (VT.SimpleTy) {
10732   case MVT::v4f64:
10733     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10734   case MVT::v4i64:
10735     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10736   case MVT::v8f32:
10737     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10738   case MVT::v8i32:
10739     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10740   case MVT::v16i16:
10741     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10742   case MVT::v32i8:
10743     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10744
10745   default:
10746     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10747   }
10748 }
10749
10750 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
10751 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
10752                                              ArrayRef<int> Mask,
10753                                              SDValue V1, SDValue V2,
10754                                              SelectionDAG &DAG) {
10755   assert(VT.getScalarSizeInBits() == 64 &&
10756          "Unexpected element type size for 128bit shuffle.");
10757
10758   // To handle 256 bit vector requires VLX and most probably
10759   // function lowerV2X128VectorShuffle() is better solution.
10760   assert(VT.getSizeInBits() == 512 &&
10761          "Unexpected vector size for 128bit shuffle.");
10762
10763   SmallVector<int, 4> WidenedMask;
10764   if (!canWidenShuffleElements(Mask, WidenedMask))
10765     return SDValue();
10766
10767   // Form a 128-bit permutation.
10768   // Convert the 64-bit shuffle mask selection values into 128-bit selection
10769   // bits defined by a vshuf64x2 instruction's immediate control byte.
10770   unsigned PermMask = 0, Imm = 0;
10771   unsigned ControlBitsNum = WidenedMask.size() / 2;
10772
10773   for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
10774     if (WidenedMask[i] == SM_SentinelZero)
10775       return SDValue();
10776
10777     // Use first element in place of undef mask.
10778     Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
10779     PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
10780   }
10781
10782   return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
10783                      DAG.getConstant(PermMask, DL, MVT::i8));
10784 }
10785
10786 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10787                                            ArrayRef<int> Mask, SDValue V1,
10788                                            SDValue V2, SelectionDAG &DAG) {
10789
10790   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10791
10792   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10793   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10794
10795   SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
10796   if (isSingleInputShuffleMask(Mask))
10797     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10798
10799   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10800 }
10801
10802 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10803 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10804                                        const X86Subtarget *Subtarget,
10805                                        SelectionDAG &DAG) {
10806   SDLoc DL(Op);
10807   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10808   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10809   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10810   ArrayRef<int> Mask = SVOp->getMask();
10811   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10812
10813   if (SDValue Shuf128 =
10814           lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
10815     return Shuf128;
10816
10817   if (SDValue Unpck =
10818           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
10819     return Unpck;
10820
10821   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10822 }
10823
10824 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10825 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10826                                        const X86Subtarget *Subtarget,
10827                                        SelectionDAG &DAG) {
10828   SDLoc DL(Op);
10829   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10830   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10831   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10832   ArrayRef<int> Mask = SVOp->getMask();
10833   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10834
10835   if (SDValue Unpck =
10836           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
10837     return Unpck;
10838
10839   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
10840 }
10841
10842 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10843 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10844                                        const X86Subtarget *Subtarget,
10845                                        SelectionDAG &DAG) {
10846   SDLoc DL(Op);
10847   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10848   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10849   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10850   ArrayRef<int> Mask = SVOp->getMask();
10851   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10852
10853   if (SDValue Shuf128 =
10854           lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
10855     return Shuf128;
10856
10857   if (SDValue Unpck =
10858           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
10859     return Unpck;
10860
10861   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
10862 }
10863
10864 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10865 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10866                                        const X86Subtarget *Subtarget,
10867                                        SelectionDAG &DAG) {
10868   SDLoc DL(Op);
10869   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10870   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10871   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10872   ArrayRef<int> Mask = SVOp->getMask();
10873   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10874
10875   if (SDValue Unpck =
10876           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
10877     return Unpck;
10878
10879   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
10880 }
10881
10882 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10883 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10884                                         const X86Subtarget *Subtarget,
10885                                         SelectionDAG &DAG) {
10886   SDLoc DL(Op);
10887   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10888   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10889   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10890   ArrayRef<int> Mask = SVOp->getMask();
10891   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10892   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10893
10894   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
10895 }
10896
10897 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10898 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10899                                        const X86Subtarget *Subtarget,
10900                                        SelectionDAG &DAG) {
10901   SDLoc DL(Op);
10902   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10903   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10904   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10905   ArrayRef<int> Mask = SVOp->getMask();
10906   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10907   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10908
10909   // FIXME: Implement direct support for this type!
10910   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10911 }
10912
10913 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10914 ///
10915 /// This routine either breaks down the specific type of a 512-bit x86 vector
10916 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10917 /// together based on the available instructions.
10918 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10919                                         MVT VT, const X86Subtarget *Subtarget,
10920                                         SelectionDAG &DAG) {
10921   SDLoc DL(Op);
10922   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10923   ArrayRef<int> Mask = SVOp->getMask();
10924   assert(Subtarget->hasAVX512() &&
10925          "Cannot lower 512-bit vectors w/ basic ISA!");
10926
10927   // Check for being able to broadcast a single element.
10928   if (SDValue Broadcast =
10929           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10930     return Broadcast;
10931
10932   // Dispatch to each element type for lowering. If we don't have supprot for
10933   // specific element type shuffles at 512 bits, immediately split them and
10934   // lower them. Each lowering routine of a given type is allowed to assume that
10935   // the requisite ISA extensions for that element type are available.
10936   switch (VT.SimpleTy) {
10937   case MVT::v8f64:
10938     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10939   case MVT::v16f32:
10940     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10941   case MVT::v8i64:
10942     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10943   case MVT::v16i32:
10944     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10945   case MVT::v32i16:
10946     if (Subtarget->hasBWI())
10947       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10948     break;
10949   case MVT::v64i8:
10950     if (Subtarget->hasBWI())
10951       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10952     break;
10953
10954   default:
10955     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10956   }
10957
10958   // Otherwise fall back on splitting.
10959   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10960 }
10961
10962 // Lower vXi1 vector shuffles.
10963 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
10964 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
10965 // vector, shuffle and then truncate it back.
10966 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10967                                       MVT VT, const X86Subtarget *Subtarget,
10968                                       SelectionDAG &DAG) {
10969   SDLoc DL(Op);
10970   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10971   ArrayRef<int> Mask = SVOp->getMask();
10972   assert(Subtarget->hasAVX512() &&
10973          "Cannot lower 512-bit vectors w/o basic ISA!");
10974   EVT ExtVT;
10975   switch (VT.SimpleTy) {
10976   default:
10977     assert(false && "Expected a vector of i1 elements");
10978     break;
10979   case MVT::v2i1:
10980     ExtVT = MVT::v2i64;
10981     break;
10982   case MVT::v4i1:
10983     ExtVT = MVT::v4i32;
10984     break;
10985   case MVT::v8i1:
10986     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
10987     break;
10988   case MVT::v16i1:
10989     ExtVT = MVT::v16i32;
10990     break;
10991   case MVT::v32i1:
10992     ExtVT = MVT::v32i16;
10993     break;
10994   case MVT::v64i1:
10995     ExtVT = MVT::v64i8;
10996     break;
10997   }
10998
10999   if (ISD::isBuildVectorAllZeros(V1.getNode()))
11000     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11001   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
11002     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11003   else
11004     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
11005
11006   if (V2.isUndef())
11007     V2 = DAG.getUNDEF(ExtVT);
11008   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
11009     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11010   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
11011     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11012   else
11013     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11014   return DAG.getNode(ISD::TRUNCATE, DL, VT,
11015                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11016 }
11017 /// \brief Top-level lowering for x86 vector shuffles.
11018 ///
11019 /// This handles decomposition, canonicalization, and lowering of all x86
11020 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11021 /// above in helper routines. The canonicalization attempts to widen shuffles
11022 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11023 /// s.t. only one of the two inputs needs to be tested, etc.
11024 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11025                                   SelectionDAG &DAG) {
11026   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11027   ArrayRef<int> Mask = SVOp->getMask();
11028   SDValue V1 = Op.getOperand(0);
11029   SDValue V2 = Op.getOperand(1);
11030   MVT VT = Op.getSimpleValueType();
11031   int NumElements = VT.getVectorNumElements();
11032   SDLoc dl(Op);
11033   bool Is1BitVector = (VT.getScalarType() == MVT::i1);
11034
11035   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11036          "Can't lower MMX shuffles");
11037
11038   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11039   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11040   if (V1IsUndef && V2IsUndef)
11041     return DAG.getUNDEF(VT);
11042
11043   // When we create a shuffle node we put the UNDEF node to second operand,
11044   // but in some cases the first operand may be transformed to UNDEF.
11045   // In this case we should just commute the node.
11046   if (V1IsUndef)
11047     return DAG.getCommutedVectorShuffle(*SVOp);
11048
11049   // Check for non-undef masks pointing at an undef vector and make the masks
11050   // undef as well. This makes it easier to match the shuffle based solely on
11051   // the mask.
11052   if (V2IsUndef)
11053     for (int M : Mask)
11054       if (M >= NumElements) {
11055         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11056         for (int &M : NewMask)
11057           if (M >= NumElements)
11058             M = -1;
11059         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11060       }
11061
11062   // We actually see shuffles that are entirely re-arrangements of a set of
11063   // zero inputs. This mostly happens while decomposing complex shuffles into
11064   // simple ones. Directly lower these as a buildvector of zeros.
11065   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11066   if (Zeroable.all())
11067     return getZeroVector(VT, Subtarget, DAG, dl);
11068
11069   // Try to collapse shuffles into using a vector type with fewer elements but
11070   // wider element types. We cap this to not form integers or floating point
11071   // elements wider than 64 bits, but it might be interesting to form i128
11072   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11073   SmallVector<int, 16> WidenedMask;
11074   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11075       canWidenShuffleElements(Mask, WidenedMask)) {
11076     MVT NewEltVT = VT.isFloatingPoint()
11077                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11078                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11079     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11080     // Make sure that the new vector type is legal. For example, v2f64 isn't
11081     // legal on SSE1.
11082     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11083       V1 = DAG.getBitcast(NewVT, V1);
11084       V2 = DAG.getBitcast(NewVT, V2);
11085       return DAG.getBitcast(
11086           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11087     }
11088   }
11089
11090   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11091   for (int M : SVOp->getMask())
11092     if (M < 0)
11093       ++NumUndefElements;
11094     else if (M < NumElements)
11095       ++NumV1Elements;
11096     else
11097       ++NumV2Elements;
11098
11099   // Commute the shuffle as needed such that more elements come from V1 than
11100   // V2. This allows us to match the shuffle pattern strictly on how many
11101   // elements come from V1 without handling the symmetric cases.
11102   if (NumV2Elements > NumV1Elements)
11103     return DAG.getCommutedVectorShuffle(*SVOp);
11104
11105   // When the number of V1 and V2 elements are the same, try to minimize the
11106   // number of uses of V2 in the low half of the vector. When that is tied,
11107   // ensure that the sum of indices for V1 is equal to or lower than the sum
11108   // indices for V2. When those are equal, try to ensure that the number of odd
11109   // indices for V1 is lower than the number of odd indices for V2.
11110   if (NumV1Elements == NumV2Elements) {
11111     int LowV1Elements = 0, LowV2Elements = 0;
11112     for (int M : SVOp->getMask().slice(0, NumElements / 2))
11113       if (M >= NumElements)
11114         ++LowV2Elements;
11115       else if (M >= 0)
11116         ++LowV1Elements;
11117     if (LowV2Elements > LowV1Elements) {
11118       return DAG.getCommutedVectorShuffle(*SVOp);
11119     } else if (LowV2Elements == LowV1Elements) {
11120       int SumV1Indices = 0, SumV2Indices = 0;
11121       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11122         if (SVOp->getMask()[i] >= NumElements)
11123           SumV2Indices += i;
11124         else if (SVOp->getMask()[i] >= 0)
11125           SumV1Indices += i;
11126       if (SumV2Indices < SumV1Indices) {
11127         return DAG.getCommutedVectorShuffle(*SVOp);
11128       } else if (SumV2Indices == SumV1Indices) {
11129         int NumV1OddIndices = 0, NumV2OddIndices = 0;
11130         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11131           if (SVOp->getMask()[i] >= NumElements)
11132             NumV2OddIndices += i % 2;
11133           else if (SVOp->getMask()[i] >= 0)
11134             NumV1OddIndices += i % 2;
11135         if (NumV2OddIndices < NumV1OddIndices)
11136           return DAG.getCommutedVectorShuffle(*SVOp);
11137       }
11138     }
11139   }
11140
11141   // For each vector width, delegate to a specialized lowering routine.
11142   if (VT.getSizeInBits() == 128)
11143     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11144
11145   if (VT.getSizeInBits() == 256)
11146     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11147
11148   if (VT.getSizeInBits() == 512)
11149     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11150
11151   if (Is1BitVector)
11152     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11153   llvm_unreachable("Unimplemented!");
11154 }
11155
11156 // This function assumes its argument is a BUILD_VECTOR of constants or
11157 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11158 // true.
11159 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11160                                     unsigned &MaskValue) {
11161   MaskValue = 0;
11162   unsigned NumElems = BuildVector->getNumOperands();
11163   
11164   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11165   // We don't handle the >2 lanes case right now.
11166   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11167   if (NumLanes > 2)
11168     return false;
11169
11170   unsigned NumElemsInLane = NumElems / NumLanes;
11171
11172   // Blend for v16i16 should be symmetric for the both lanes.
11173   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11174     SDValue EltCond = BuildVector->getOperand(i);
11175     SDValue SndLaneEltCond =
11176         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11177
11178     int Lane1Cond = -1, Lane2Cond = -1;
11179     if (isa<ConstantSDNode>(EltCond))
11180       Lane1Cond = !isZero(EltCond);
11181     if (isa<ConstantSDNode>(SndLaneEltCond))
11182       Lane2Cond = !isZero(SndLaneEltCond);
11183
11184     unsigned LaneMask = 0;
11185     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11186       // Lane1Cond != 0, means we want the first argument.
11187       // Lane1Cond == 0, means we want the second argument.
11188       // The encoding of this argument is 0 for the first argument, 1
11189       // for the second. Therefore, invert the condition.
11190       LaneMask = !Lane1Cond << i;
11191     else if (Lane1Cond < 0)
11192       LaneMask = !Lane2Cond << i;
11193     else
11194       return false;
11195
11196     MaskValue |= LaneMask;
11197     if (NumLanes == 2)
11198       MaskValue |= LaneMask << NumElemsInLane;
11199   }
11200   return true;
11201 }
11202
11203 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11204 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11205                                            const X86Subtarget *Subtarget,
11206                                            SelectionDAG &DAG) {
11207   SDValue Cond = Op.getOperand(0);
11208   SDValue LHS = Op.getOperand(1);
11209   SDValue RHS = Op.getOperand(2);
11210   SDLoc dl(Op);
11211   MVT VT = Op.getSimpleValueType();
11212
11213   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11214     return SDValue();
11215   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11216
11217   // Only non-legal VSELECTs reach this lowering, convert those into generic
11218   // shuffles and re-use the shuffle lowering path for blends.
11219   SmallVector<int, 32> Mask;
11220   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11221     SDValue CondElt = CondBV->getOperand(i);
11222     Mask.push_back(
11223         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
11224   }
11225   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11226 }
11227
11228 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11229   // A vselect where all conditions and data are constants can be optimized into
11230   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11231   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11232       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11233       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11234     return SDValue();
11235
11236   // Try to lower this to a blend-style vector shuffle. This can handle all
11237   // constant condition cases.
11238   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11239     return BlendOp;
11240
11241   // Variable blends are only legal from SSE4.1 onward.
11242   if (!Subtarget->hasSSE41())
11243     return SDValue();
11244
11245   // Only some types will be legal on some subtargets. If we can emit a legal
11246   // VSELECT-matching blend, return Op, and but if we need to expand, return
11247   // a null value.
11248   switch (Op.getSimpleValueType().SimpleTy) {
11249   default:
11250     // Most of the vector types have blends past SSE4.1.
11251     return Op;
11252
11253   case MVT::v32i8:
11254     // The byte blends for AVX vectors were introduced only in AVX2.
11255     if (Subtarget->hasAVX2())
11256       return Op;
11257
11258     return SDValue();
11259
11260   case MVT::v8i16:
11261   case MVT::v16i16:
11262     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11263     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11264       return Op;
11265
11266     // FIXME: We should custom lower this by fixing the condition and using i8
11267     // blends.
11268     return SDValue();
11269   }
11270 }
11271
11272 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11273   MVT VT = Op.getSimpleValueType();
11274   SDLoc dl(Op);
11275
11276   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11277     return SDValue();
11278
11279   if (VT.getSizeInBits() == 8) {
11280     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11281                                   Op.getOperand(0), Op.getOperand(1));
11282     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11283                                   DAG.getValueType(VT));
11284     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11285   }
11286
11287   if (VT.getSizeInBits() == 16) {
11288     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11289     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11290     if (Idx == 0)
11291       return DAG.getNode(
11292           ISD::TRUNCATE, dl, MVT::i16,
11293           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11294                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11295                       Op.getOperand(1)));
11296     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11297                                   Op.getOperand(0), Op.getOperand(1));
11298     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11299                                   DAG.getValueType(VT));
11300     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11301   }
11302
11303   if (VT == MVT::f32) {
11304     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11305     // the result back to FR32 register. It's only worth matching if the
11306     // result has a single use which is a store or a bitcast to i32.  And in
11307     // the case of a store, it's not worth it if the index is a constant 0,
11308     // because a MOVSSmr can be used instead, which is smaller and faster.
11309     if (!Op.hasOneUse())
11310       return SDValue();
11311     SDNode *User = *Op.getNode()->use_begin();
11312     if ((User->getOpcode() != ISD::STORE ||
11313          (isa<ConstantSDNode>(Op.getOperand(1)) &&
11314           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11315         (User->getOpcode() != ISD::BITCAST ||
11316          User->getValueType(0) != MVT::i32))
11317       return SDValue();
11318     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11319                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11320                                   Op.getOperand(1));
11321     return DAG.getBitcast(MVT::f32, Extract);
11322   }
11323
11324   if (VT == MVT::i32 || VT == MVT::i64) {
11325     // ExtractPS/pextrq works with constant index.
11326     if (isa<ConstantSDNode>(Op.getOperand(1)))
11327       return Op;
11328   }
11329   return SDValue();
11330 }
11331
11332 /// Extract one bit from mask vector, like v16i1 or v8i1.
11333 /// AVX-512 feature.
11334 SDValue
11335 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11336   SDValue Vec = Op.getOperand(0);
11337   SDLoc dl(Vec);
11338   MVT VecVT = Vec.getSimpleValueType();
11339   SDValue Idx = Op.getOperand(1);
11340   MVT EltVT = Op.getSimpleValueType();
11341
11342   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11343   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11344          "Unexpected vector type in ExtractBitFromMaskVector");
11345
11346   // variable index can't be handled in mask registers,
11347   // extend vector to VR512
11348   if (!isa<ConstantSDNode>(Idx)) {
11349     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11350     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11351     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11352                               ExtVT.getVectorElementType(), Ext, Idx);
11353     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11354   }
11355
11356   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11357   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11358   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11359     rc = getRegClassFor(MVT::v16i1);
11360   unsigned MaxSift = rc->getSize()*8 - 1;
11361   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11362                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11363   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11364                     DAG.getConstant(MaxSift, dl, MVT::i8));
11365   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11366                        DAG.getIntPtrConstant(0, dl));
11367 }
11368
11369 SDValue
11370 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11371                                            SelectionDAG &DAG) const {
11372   SDLoc dl(Op);
11373   SDValue Vec = Op.getOperand(0);
11374   MVT VecVT = Vec.getSimpleValueType();
11375   SDValue Idx = Op.getOperand(1);
11376
11377   if (Op.getSimpleValueType() == MVT::i1)
11378     return ExtractBitFromMaskVector(Op, DAG);
11379
11380   if (!isa<ConstantSDNode>(Idx)) {
11381     if (VecVT.is512BitVector() ||
11382         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11383          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11384
11385       MVT MaskEltVT =
11386         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11387       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11388                                     MaskEltVT.getSizeInBits());
11389
11390       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11391       auto PtrVT = getPointerTy(DAG.getDataLayout());
11392       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11393                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11394                                  DAG.getConstant(0, dl, PtrVT));
11395       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11396       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11397                          DAG.getConstant(0, dl, PtrVT));
11398     }
11399     return SDValue();
11400   }
11401
11402   // If this is a 256-bit vector result, first extract the 128-bit vector and
11403   // then extract the element from the 128-bit vector.
11404   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11405
11406     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11407     // Get the 128-bit vector.
11408     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11409     MVT EltVT = VecVT.getVectorElementType();
11410
11411     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11412
11413     //if (IdxVal >= NumElems/2)
11414     //  IdxVal -= NumElems/2;
11415     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
11416     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11417                        DAG.getConstant(IdxVal, dl, MVT::i32));
11418   }
11419
11420   assert(VecVT.is128BitVector() && "Unexpected vector length");
11421
11422   if (Subtarget->hasSSE41())
11423     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11424       return Res;
11425
11426   MVT VT = Op.getSimpleValueType();
11427   // TODO: handle v16i8.
11428   if (VT.getSizeInBits() == 16) {
11429     SDValue Vec = Op.getOperand(0);
11430     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11431     if (Idx == 0)
11432       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11433                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11434                                      DAG.getBitcast(MVT::v4i32, Vec),
11435                                      Op.getOperand(1)));
11436     // Transform it so it match pextrw which produces a 32-bit result.
11437     MVT EltVT = MVT::i32;
11438     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11439                                   Op.getOperand(0), Op.getOperand(1));
11440     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11441                                   DAG.getValueType(VT));
11442     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11443   }
11444
11445   if (VT.getSizeInBits() == 32) {
11446     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11447     if (Idx == 0)
11448       return Op;
11449
11450     // SHUFPS the element to the lowest double word, then movss.
11451     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11452     MVT VVT = Op.getOperand(0).getSimpleValueType();
11453     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11454                                        DAG.getUNDEF(VVT), Mask);
11455     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11456                        DAG.getIntPtrConstant(0, dl));
11457   }
11458
11459   if (VT.getSizeInBits() == 64) {
11460     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11461     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11462     //        to match extract_elt for f64.
11463     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11464     if (Idx == 0)
11465       return Op;
11466
11467     // UNPCKHPD the element to the lowest double word, then movsd.
11468     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11469     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11470     int Mask[2] = { 1, -1 };
11471     MVT VVT = Op.getOperand(0).getSimpleValueType();
11472     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11473                                        DAG.getUNDEF(VVT), Mask);
11474     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11475                        DAG.getIntPtrConstant(0, dl));
11476   }
11477
11478   return SDValue();
11479 }
11480
11481 /// Insert one bit to mask vector, like v16i1 or v8i1.
11482 /// AVX-512 feature.
11483 SDValue
11484 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11485   SDLoc dl(Op);
11486   SDValue Vec = Op.getOperand(0);
11487   SDValue Elt = Op.getOperand(1);
11488   SDValue Idx = Op.getOperand(2);
11489   MVT VecVT = Vec.getSimpleValueType();
11490
11491   if (!isa<ConstantSDNode>(Idx)) {
11492     // Non constant index. Extend source and destination,
11493     // insert element and then truncate the result.
11494     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11495     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11496     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11497       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11498       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11499     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11500   }
11501
11502   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11503   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11504   if (IdxVal)
11505     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11506                            DAG.getConstant(IdxVal, dl, MVT::i8));
11507   if (Vec.getOpcode() == ISD::UNDEF)
11508     return EltInVec;
11509   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11510 }
11511
11512 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11513                                                   SelectionDAG &DAG) const {
11514   MVT VT = Op.getSimpleValueType();
11515   MVT EltVT = VT.getVectorElementType();
11516
11517   if (EltVT == MVT::i1)
11518     return InsertBitToMaskVector(Op, DAG);
11519
11520   SDLoc dl(Op);
11521   SDValue N0 = Op.getOperand(0);
11522   SDValue N1 = Op.getOperand(1);
11523   SDValue N2 = Op.getOperand(2);
11524   if (!isa<ConstantSDNode>(N2))
11525     return SDValue();
11526   auto *N2C = cast<ConstantSDNode>(N2);
11527   unsigned IdxVal = N2C->getZExtValue();
11528
11529   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11530   // into that, and then insert the subvector back into the result.
11531   if (VT.is256BitVector() || VT.is512BitVector()) {
11532     // With a 256-bit vector, we can insert into the zero element efficiently
11533     // using a blend if we have AVX or AVX2 and the right data type.
11534     if (VT.is256BitVector() && IdxVal == 0) {
11535       // TODO: It is worthwhile to cast integer to floating point and back
11536       // and incur a domain crossing penalty if that's what we'll end up
11537       // doing anyway after extracting to a 128-bit vector.
11538       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11539           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11540         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11541         N2 = DAG.getIntPtrConstant(1, dl);
11542         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11543       }
11544     }
11545
11546     // Get the desired 128-bit vector chunk.
11547     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11548
11549     // Insert the element into the desired chunk.
11550     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11551     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11552
11553     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11554                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11555
11556     // Insert the changed part back into the bigger vector
11557     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11558   }
11559   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11560
11561   if (Subtarget->hasSSE41()) {
11562     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11563       unsigned Opc;
11564       if (VT == MVT::v8i16) {
11565         Opc = X86ISD::PINSRW;
11566       } else {
11567         assert(VT == MVT::v16i8);
11568         Opc = X86ISD::PINSRB;
11569       }
11570
11571       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11572       // argument.
11573       if (N1.getValueType() != MVT::i32)
11574         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11575       if (N2.getValueType() != MVT::i32)
11576         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11577       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11578     }
11579
11580     if (EltVT == MVT::f32) {
11581       // Bits [7:6] of the constant are the source select. This will always be
11582       //   zero here. The DAG Combiner may combine an extract_elt index into
11583       //   these bits. For example (insert (extract, 3), 2) could be matched by
11584       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11585       // Bits [5:4] of the constant are the destination select. This is the
11586       //   value of the incoming immediate.
11587       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11588       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11589
11590       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11591       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11592         // If this is an insertion of 32-bits into the low 32-bits of
11593         // a vector, we prefer to generate a blend with immediate rather
11594         // than an insertps. Blends are simpler operations in hardware and so
11595         // will always have equal or better performance than insertps.
11596         // But if optimizing for size and there's a load folding opportunity,
11597         // generate insertps because blendps does not have a 32-bit memory
11598         // operand form.
11599         N2 = DAG.getIntPtrConstant(1, dl);
11600         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11601         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11602       }
11603       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11604       // Create this as a scalar to vector..
11605       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11606       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11607     }
11608
11609     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11610       // PINSR* works with constant index.
11611       return Op;
11612     }
11613   }
11614
11615   if (EltVT == MVT::i8)
11616     return SDValue();
11617
11618   if (EltVT.getSizeInBits() == 16) {
11619     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11620     // as its second argument.
11621     if (N1.getValueType() != MVT::i32)
11622       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11623     if (N2.getValueType() != MVT::i32)
11624       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11625     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11626   }
11627   return SDValue();
11628 }
11629
11630 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11631   SDLoc dl(Op);
11632   MVT OpVT = Op.getSimpleValueType();
11633
11634   // If this is a 256-bit vector result, first insert into a 128-bit
11635   // vector and then insert into the 256-bit vector.
11636   if (!OpVT.is128BitVector()) {
11637     // Insert into a 128-bit vector.
11638     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11639     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11640                                  OpVT.getVectorNumElements() / SizeFactor);
11641
11642     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11643
11644     // Insert the 128-bit vector.
11645     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11646   }
11647
11648   if (OpVT == MVT::v1i64 &&
11649       Op.getOperand(0).getValueType() == MVT::i64)
11650     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11651
11652   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11653   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11654   return DAG.getBitcast(
11655       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11656 }
11657
11658 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11659 // a simple subregister reference or explicit instructions to grab
11660 // upper bits of a vector.
11661 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11662                                       SelectionDAG &DAG) {
11663   SDLoc dl(Op);
11664   SDValue In =  Op.getOperand(0);
11665   SDValue Idx = Op.getOperand(1);
11666   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11667   MVT ResVT   = Op.getSimpleValueType();
11668   MVT InVT    = In.getSimpleValueType();
11669
11670   if (Subtarget->hasFp256()) {
11671     if (ResVT.is128BitVector() &&
11672         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11673         isa<ConstantSDNode>(Idx)) {
11674       return Extract128BitVector(In, IdxVal, DAG, dl);
11675     }
11676     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11677         isa<ConstantSDNode>(Idx)) {
11678       return Extract256BitVector(In, IdxVal, DAG, dl);
11679     }
11680   }
11681   return SDValue();
11682 }
11683
11684 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11685 // simple superregister reference or explicit instructions to insert
11686 // the upper bits of a vector.
11687 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11688                                      SelectionDAG &DAG) {
11689   if (!Subtarget->hasAVX())
11690     return SDValue();
11691
11692   SDLoc dl(Op);
11693   SDValue Vec = Op.getOperand(0);
11694   SDValue SubVec = Op.getOperand(1);
11695   SDValue Idx = Op.getOperand(2);
11696
11697   if (!isa<ConstantSDNode>(Idx))
11698     return SDValue();
11699
11700   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11701   MVT OpVT = Op.getSimpleValueType();
11702   MVT SubVecVT = SubVec.getSimpleValueType();
11703
11704   // Fold two 16-byte subvector loads into one 32-byte load:
11705   // (insert_subvector (insert_subvector undef, (load addr), 0),
11706   //                   (load addr + 16), Elts/2)
11707   // --> load32 addr
11708   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11709       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11710       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11711     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11712     if (Idx2 && Idx2->getZExtValue() == 0) {
11713       SDValue SubVec2 = Vec.getOperand(1);
11714       // If needed, look through a bitcast to get to the load.
11715       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11716         SubVec2 = SubVec2.getOperand(0);
11717
11718       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11719         bool Fast;
11720         unsigned Alignment = FirstLd->getAlignment();
11721         unsigned AS = FirstLd->getAddressSpace();
11722         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11723         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11724                                     OpVT, AS, Alignment, &Fast) && Fast) {
11725           SDValue Ops[] = { SubVec2, SubVec };
11726           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11727             return Ld;
11728         }
11729       }
11730     }
11731   }
11732
11733   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11734       SubVecVT.is128BitVector())
11735     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11736
11737   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11738     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11739
11740   if (OpVT.getVectorElementType() == MVT::i1) {
11741     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11742       return Op;
11743     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11744     SDValue Undef = DAG.getUNDEF(OpVT);
11745     unsigned NumElems = OpVT.getVectorNumElements();
11746     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11747
11748     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11749       // Zero upper bits of the Vec
11750       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11751       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11752
11753       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11754                                  SubVec, ZeroIdx);
11755       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11756       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11757     }
11758     if (IdxVal == 0) {
11759       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11760                                  SubVec, ZeroIdx);
11761       // Zero upper bits of the Vec2
11762       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11763       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11764       // Zero lower bits of the Vec
11765       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11766       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11767       // Merge them together
11768       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11769     }
11770   }
11771   return SDValue();
11772 }
11773
11774 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11775 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11776 // one of the above mentioned nodes. It has to be wrapped because otherwise
11777 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11778 // be used to form addressing mode. These wrapped nodes will be selected
11779 // into MOV32ri.
11780 SDValue
11781 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11782   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11783
11784   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11785   // global base reg.
11786   unsigned char OpFlag = 0;
11787   unsigned WrapperKind = X86ISD::Wrapper;
11788   CodeModel::Model M = DAG.getTarget().getCodeModel();
11789
11790   if (Subtarget->isPICStyleRIPRel() &&
11791       (M == CodeModel::Small || M == CodeModel::Kernel))
11792     WrapperKind = X86ISD::WrapperRIP;
11793   else if (Subtarget->isPICStyleGOT())
11794     OpFlag = X86II::MO_GOTOFF;
11795   else if (Subtarget->isPICStyleStubPIC())
11796     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11797
11798   auto PtrVT = getPointerTy(DAG.getDataLayout());
11799   SDValue Result = DAG.getTargetConstantPool(
11800       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11801   SDLoc DL(CP);
11802   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11803   // With PIC, the address is actually $g + Offset.
11804   if (OpFlag) {
11805     Result =
11806         DAG.getNode(ISD::ADD, DL, PtrVT,
11807                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11808   }
11809
11810   return Result;
11811 }
11812
11813 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11814   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11815
11816   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11817   // global base reg.
11818   unsigned char OpFlag = 0;
11819   unsigned WrapperKind = X86ISD::Wrapper;
11820   CodeModel::Model M = DAG.getTarget().getCodeModel();
11821
11822   if (Subtarget->isPICStyleRIPRel() &&
11823       (M == CodeModel::Small || M == CodeModel::Kernel))
11824     WrapperKind = X86ISD::WrapperRIP;
11825   else if (Subtarget->isPICStyleGOT())
11826     OpFlag = X86II::MO_GOTOFF;
11827   else if (Subtarget->isPICStyleStubPIC())
11828     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11829
11830   auto PtrVT = getPointerTy(DAG.getDataLayout());
11831   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11832   SDLoc DL(JT);
11833   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11834
11835   // With PIC, the address is actually $g + Offset.
11836   if (OpFlag)
11837     Result =
11838         DAG.getNode(ISD::ADD, DL, PtrVT,
11839                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11840
11841   return Result;
11842 }
11843
11844 SDValue
11845 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11846   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11847
11848   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11849   // global base reg.
11850   unsigned char OpFlag = 0;
11851   unsigned WrapperKind = X86ISD::Wrapper;
11852   CodeModel::Model M = DAG.getTarget().getCodeModel();
11853
11854   if (Subtarget->isPICStyleRIPRel() &&
11855       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11856     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11857       OpFlag = X86II::MO_GOTPCREL;
11858     WrapperKind = X86ISD::WrapperRIP;
11859   } else if (Subtarget->isPICStyleGOT()) {
11860     OpFlag = X86II::MO_GOT;
11861   } else if (Subtarget->isPICStyleStubPIC()) {
11862     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11863   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11864     OpFlag = X86II::MO_DARWIN_NONLAZY;
11865   }
11866
11867   auto PtrVT = getPointerTy(DAG.getDataLayout());
11868   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11869
11870   SDLoc DL(Op);
11871   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11872
11873   // With PIC, the address is actually $g + Offset.
11874   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11875       !Subtarget->is64Bit()) {
11876     Result =
11877         DAG.getNode(ISD::ADD, DL, PtrVT,
11878                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11879   }
11880
11881   // For symbols that require a load from a stub to get the address, emit the
11882   // load.
11883   if (isGlobalStubReference(OpFlag))
11884     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11885                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11886                          false, false, false, 0);
11887
11888   return Result;
11889 }
11890
11891 SDValue
11892 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11893   // Create the TargetBlockAddressAddress node.
11894   unsigned char OpFlags =
11895     Subtarget->ClassifyBlockAddressReference();
11896   CodeModel::Model M = DAG.getTarget().getCodeModel();
11897   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11898   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11899   SDLoc dl(Op);
11900   auto PtrVT = getPointerTy(DAG.getDataLayout());
11901   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11902
11903   if (Subtarget->isPICStyleRIPRel() &&
11904       (M == CodeModel::Small || M == CodeModel::Kernel))
11905     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11906   else
11907     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11908
11909   // With PIC, the address is actually $g + Offset.
11910   if (isGlobalRelativeToPICBase(OpFlags)) {
11911     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11912                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11913   }
11914
11915   return Result;
11916 }
11917
11918 SDValue
11919 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11920                                       int64_t Offset, SelectionDAG &DAG) const {
11921   // Create the TargetGlobalAddress node, folding in the constant
11922   // offset if it is legal.
11923   unsigned char OpFlags =
11924       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11925   CodeModel::Model M = DAG.getTarget().getCodeModel();
11926   auto PtrVT = getPointerTy(DAG.getDataLayout());
11927   SDValue Result;
11928   if (OpFlags == X86II::MO_NO_FLAG &&
11929       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11930     // A direct static reference to a global.
11931     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11932     Offset = 0;
11933   } else {
11934     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11935   }
11936
11937   if (Subtarget->isPICStyleRIPRel() &&
11938       (M == CodeModel::Small || M == CodeModel::Kernel))
11939     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11940   else
11941     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11942
11943   // With PIC, the address is actually $g + Offset.
11944   if (isGlobalRelativeToPICBase(OpFlags)) {
11945     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11946                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11947   }
11948
11949   // For globals that require a load from a stub to get the address, emit the
11950   // load.
11951   if (isGlobalStubReference(OpFlags))
11952     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11953                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11954                          false, false, false, 0);
11955
11956   // If there was a non-zero offset that we didn't fold, create an explicit
11957   // addition for it.
11958   if (Offset != 0)
11959     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11960                          DAG.getConstant(Offset, dl, PtrVT));
11961
11962   return Result;
11963 }
11964
11965 SDValue
11966 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11967   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11968   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11969   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11970 }
11971
11972 static SDValue
11973 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11974            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11975            unsigned char OperandFlags, bool LocalDynamic = false) {
11976   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11977   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11978   SDLoc dl(GA);
11979   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11980                                            GA->getValueType(0),
11981                                            GA->getOffset(),
11982                                            OperandFlags);
11983
11984   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11985                                            : X86ISD::TLSADDR;
11986
11987   if (InFlag) {
11988     SDValue Ops[] = { Chain,  TGA, *InFlag };
11989     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11990   } else {
11991     SDValue Ops[]  = { Chain, TGA };
11992     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11993   }
11994
11995   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11996   MFI->setAdjustsStack(true);
11997   MFI->setHasCalls(true);
11998
11999   SDValue Flag = Chain.getValue(1);
12000   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12001 }
12002
12003 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12004 static SDValue
12005 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12006                                 const EVT PtrVT) {
12007   SDValue InFlag;
12008   SDLoc dl(GA);  // ? function entry point might be better
12009   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12010                                    DAG.getNode(X86ISD::GlobalBaseReg,
12011                                                SDLoc(), PtrVT), InFlag);
12012   InFlag = Chain.getValue(1);
12013
12014   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12015 }
12016
12017 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12018 static SDValue
12019 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12020                                 const EVT PtrVT) {
12021   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12022                     X86::RAX, X86II::MO_TLSGD);
12023 }
12024
12025 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12026                                            SelectionDAG &DAG,
12027                                            const EVT PtrVT,
12028                                            bool is64Bit) {
12029   SDLoc dl(GA);
12030
12031   // Get the start address of the TLS block for this module.
12032   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12033       .getInfo<X86MachineFunctionInfo>();
12034   MFI->incNumLocalDynamicTLSAccesses();
12035
12036   SDValue Base;
12037   if (is64Bit) {
12038     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12039                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
12040   } else {
12041     SDValue InFlag;
12042     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12043         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12044     InFlag = Chain.getValue(1);
12045     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12046                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12047   }
12048
12049   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12050   // of Base.
12051
12052   // Build x@dtpoff.
12053   unsigned char OperandFlags = X86II::MO_DTPOFF;
12054   unsigned WrapperKind = X86ISD::Wrapper;
12055   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12056                                            GA->getValueType(0),
12057                                            GA->getOffset(), OperandFlags);
12058   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12059
12060   // Add x@dtpoff with the base.
12061   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12062 }
12063
12064 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12065 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12066                                    const EVT PtrVT, TLSModel::Model model,
12067                                    bool is64Bit, bool isPIC) {
12068   SDLoc dl(GA);
12069
12070   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12071   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12072                                                          is64Bit ? 257 : 256));
12073
12074   SDValue ThreadPointer =
12075       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12076                   MachinePointerInfo(Ptr), false, false, false, 0);
12077
12078   unsigned char OperandFlags = 0;
12079   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
12080   // initialexec.
12081   unsigned WrapperKind = X86ISD::Wrapper;
12082   if (model == TLSModel::LocalExec) {
12083     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12084   } else if (model == TLSModel::InitialExec) {
12085     if (is64Bit) {
12086       OperandFlags = X86II::MO_GOTTPOFF;
12087       WrapperKind = X86ISD::WrapperRIP;
12088     } else {
12089       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12090     }
12091   } else {
12092     llvm_unreachable("Unexpected model");
12093   }
12094
12095   // emit "addl x@ntpoff,%eax" (local exec)
12096   // or "addl x@indntpoff,%eax" (initial exec)
12097   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12098   SDValue TGA =
12099       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12100                                  GA->getOffset(), OperandFlags);
12101   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12102
12103   if (model == TLSModel::InitialExec) {
12104     if (isPIC && !is64Bit) {
12105       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12106                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12107                            Offset);
12108     }
12109
12110     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12111                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12112                          false, false, false, 0);
12113   }
12114
12115   // The address of the thread local variable is the add of the thread
12116   // pointer with the offset of the variable.
12117   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12118 }
12119
12120 SDValue
12121 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12122
12123   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12124   const GlobalValue *GV = GA->getGlobal();
12125   auto PtrVT = getPointerTy(DAG.getDataLayout());
12126
12127   if (Subtarget->isTargetELF()) {
12128     if (DAG.getTarget().Options.EmulatedTLS)
12129       return LowerToTLSEmulatedModel(GA, DAG);
12130     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12131     switch (model) {
12132       case TLSModel::GeneralDynamic:
12133         if (Subtarget->is64Bit())
12134           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12135         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12136       case TLSModel::LocalDynamic:
12137         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12138                                            Subtarget->is64Bit());
12139       case TLSModel::InitialExec:
12140       case TLSModel::LocalExec:
12141         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12142                                    DAG.getTarget().getRelocationModel() ==
12143                                        Reloc::PIC_);
12144     }
12145     llvm_unreachable("Unknown TLS model.");
12146   }
12147
12148   if (Subtarget->isTargetDarwin()) {
12149     // Darwin only has one model of TLS.  Lower to that.
12150     unsigned char OpFlag = 0;
12151     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12152                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12153
12154     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12155     // global base reg.
12156     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12157                  !Subtarget->is64Bit();
12158     if (PIC32)
12159       OpFlag = X86II::MO_TLVP_PIC_BASE;
12160     else
12161       OpFlag = X86II::MO_TLVP;
12162     SDLoc DL(Op);
12163     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12164                                                 GA->getValueType(0),
12165                                                 GA->getOffset(), OpFlag);
12166     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12167
12168     // With PIC32, the address is actually $g + Offset.
12169     if (PIC32)
12170       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12171                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12172                            Offset);
12173
12174     // Lowering the machine isd will make sure everything is in the right
12175     // location.
12176     SDValue Chain = DAG.getEntryNode();
12177     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12178     SDValue Args[] = { Chain, Offset };
12179     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12180
12181     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12182     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12183     MFI->setAdjustsStack(true);
12184
12185     // And our return value (tls address) is in the standard call return value
12186     // location.
12187     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12188     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12189   }
12190
12191   if (Subtarget->isTargetKnownWindowsMSVC() ||
12192       Subtarget->isTargetWindowsGNU()) {
12193     // Just use the implicit TLS architecture
12194     // Need to generate someting similar to:
12195     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12196     //                                  ; from TEB
12197     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12198     //   mov     rcx, qword [rdx+rcx*8]
12199     //   mov     eax, .tls$:tlsvar
12200     //   [rax+rcx] contains the address
12201     // Windows 64bit: gs:0x58
12202     // Windows 32bit: fs:__tls_array
12203
12204     SDLoc dl(GA);
12205     SDValue Chain = DAG.getEntryNode();
12206
12207     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12208     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12209     // use its literal value of 0x2C.
12210     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12211                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12212                                                              256)
12213                                         : Type::getInt32PtrTy(*DAG.getContext(),
12214                                                               257));
12215
12216     SDValue TlsArray = Subtarget->is64Bit()
12217                            ? DAG.getIntPtrConstant(0x58, dl)
12218                            : (Subtarget->isTargetWindowsGNU()
12219                                   ? DAG.getIntPtrConstant(0x2C, dl)
12220                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12221
12222     SDValue ThreadPointer =
12223         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12224                     false, false, 0);
12225
12226     SDValue res;
12227     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12228       res = ThreadPointer;
12229     } else {
12230       // Load the _tls_index variable
12231       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12232       if (Subtarget->is64Bit())
12233         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12234                              MachinePointerInfo(), MVT::i32, false, false,
12235                              false, 0);
12236       else
12237         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12238                           false, false, 0);
12239
12240       auto &DL = DAG.getDataLayout();
12241       SDValue Scale =
12242           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12243       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12244
12245       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12246     }
12247
12248     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12249                       false, 0);
12250
12251     // Get the offset of start of .tls section
12252     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12253                                              GA->getValueType(0),
12254                                              GA->getOffset(), X86II::MO_SECREL);
12255     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12256
12257     // The address of the thread local variable is the add of the thread
12258     // pointer with the offset of the variable.
12259     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12260   }
12261
12262   llvm_unreachable("TLS not implemented for this target.");
12263 }
12264
12265 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12266 /// and take a 2 x i32 value to shift plus a shift amount.
12267 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12268   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12269   MVT VT = Op.getSimpleValueType();
12270   unsigned VTBits = VT.getSizeInBits();
12271   SDLoc dl(Op);
12272   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12273   SDValue ShOpLo = Op.getOperand(0);
12274   SDValue ShOpHi = Op.getOperand(1);
12275   SDValue ShAmt  = Op.getOperand(2);
12276   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12277   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12278   // during isel.
12279   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12280                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12281   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12282                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12283                        : DAG.getConstant(0, dl, VT);
12284
12285   SDValue Tmp2, Tmp3;
12286   if (Op.getOpcode() == ISD::SHL_PARTS) {
12287     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12288     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12289   } else {
12290     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12291     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12292   }
12293
12294   // If the shift amount is larger or equal than the width of a part we can't
12295   // rely on the results of shld/shrd. Insert a test and select the appropriate
12296   // values for large shift amounts.
12297   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12298                                 DAG.getConstant(VTBits, dl, MVT::i8));
12299   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12300                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12301
12302   SDValue Hi, Lo;
12303   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12304   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12305   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12306
12307   if (Op.getOpcode() == ISD::SHL_PARTS) {
12308     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12309     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12310   } else {
12311     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12312     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12313   }
12314
12315   SDValue Ops[2] = { Lo, Hi };
12316   return DAG.getMergeValues(Ops, dl);
12317 }
12318
12319 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12320                                            SelectionDAG &DAG) const {
12321   SDValue Src = Op.getOperand(0);
12322   MVT SrcVT = Src.getSimpleValueType();
12323   MVT VT = Op.getSimpleValueType();
12324   SDLoc dl(Op);
12325
12326   if (SrcVT.isVector()) {
12327     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12328       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12329                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12330                          DAG.getUNDEF(SrcVT)));
12331     }
12332     if (SrcVT.getVectorElementType() == MVT::i1) {
12333       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12334       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12335                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12336     }
12337     return SDValue();
12338   }
12339
12340   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12341          "Unknown SINT_TO_FP to lower!");
12342
12343   // These are really Legal; return the operand so the caller accepts it as
12344   // Legal.
12345   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12346     return Op;
12347   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12348       Subtarget->is64Bit()) {
12349     return Op;
12350   }
12351
12352   unsigned Size = SrcVT.getSizeInBits()/8;
12353   MachineFunction &MF = DAG.getMachineFunction();
12354   auto PtrVT = getPointerTy(MF.getDataLayout());
12355   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12356   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12357   SDValue Chain = DAG.getStore(
12358       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12359       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12360       false, 0);
12361   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12362 }
12363
12364 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12365                                      SDValue StackSlot,
12366                                      SelectionDAG &DAG) const {
12367   // Build the FILD
12368   SDLoc DL(Op);
12369   SDVTList Tys;
12370   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12371   if (useSSE)
12372     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12373   else
12374     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12375
12376   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12377
12378   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12379   MachineMemOperand *MMO;
12380   if (FI) {
12381     int SSFI = FI->getIndex();
12382     MMO = DAG.getMachineFunction().getMachineMemOperand(
12383         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12384         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12385   } else {
12386     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12387     StackSlot = StackSlot.getOperand(1);
12388   }
12389   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12390   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12391                                            X86ISD::FILD, DL,
12392                                            Tys, Ops, SrcVT, MMO);
12393
12394   if (useSSE) {
12395     Chain = Result.getValue(1);
12396     SDValue InFlag = Result.getValue(2);
12397
12398     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12399     // shouldn't be necessary except that RFP cannot be live across
12400     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12401     MachineFunction &MF = DAG.getMachineFunction();
12402     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12403     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12404     auto PtrVT = getPointerTy(MF.getDataLayout());
12405     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12406     Tys = DAG.getVTList(MVT::Other);
12407     SDValue Ops[] = {
12408       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12409     };
12410     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12411         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12412         MachineMemOperand::MOStore, SSFISize, SSFISize);
12413
12414     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12415                                     Ops, Op.getValueType(), MMO);
12416     Result = DAG.getLoad(
12417         Op.getValueType(), DL, Chain, StackSlot,
12418         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12419         false, false, false, 0);
12420   }
12421
12422   return Result;
12423 }
12424
12425 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12426 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12427                                                SelectionDAG &DAG) const {
12428   // This algorithm is not obvious. Here it is what we're trying to output:
12429   /*
12430      movq       %rax,  %xmm0
12431      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12432      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12433      #ifdef __SSE3__
12434        haddpd   %xmm0, %xmm0
12435      #else
12436        pshufd   $0x4e, %xmm0, %xmm1
12437        addpd    %xmm1, %xmm0
12438      #endif
12439   */
12440
12441   SDLoc dl(Op);
12442   LLVMContext *Context = DAG.getContext();
12443
12444   // Build some magic constants.
12445   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12446   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12447   auto PtrVT = getPointerTy(DAG.getDataLayout());
12448   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12449
12450   SmallVector<Constant*,2> CV1;
12451   CV1.push_back(
12452     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12453                                       APInt(64, 0x4330000000000000ULL))));
12454   CV1.push_back(
12455     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12456                                       APInt(64, 0x4530000000000000ULL))));
12457   Constant *C1 = ConstantVector::get(CV1);
12458   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12459
12460   // Load the 64-bit value into an XMM register.
12461   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12462                             Op.getOperand(0));
12463   SDValue CLod0 =
12464       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12465                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12466                   false, false, false, 16);
12467   SDValue Unpck1 =
12468       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12469
12470   SDValue CLod1 =
12471       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12472                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12473                   false, false, false, 16);
12474   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12475   // TODO: Are there any fast-math-flags to propagate here?
12476   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12477   SDValue Result;
12478
12479   if (Subtarget->hasSSE3()) {
12480     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12481     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12482   } else {
12483     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12484     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12485                                            S2F, 0x4E, DAG);
12486     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12487                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12488   }
12489
12490   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12491                      DAG.getIntPtrConstant(0, dl));
12492 }
12493
12494 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12495 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12496                                                SelectionDAG &DAG) const {
12497   SDLoc dl(Op);
12498   // FP constant to bias correct the final result.
12499   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12500                                    MVT::f64);
12501
12502   // Load the 32-bit value into an XMM register.
12503   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12504                              Op.getOperand(0));
12505
12506   // Zero out the upper parts of the register.
12507   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12508
12509   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12510                      DAG.getBitcast(MVT::v2f64, Load),
12511                      DAG.getIntPtrConstant(0, dl));
12512
12513   // Or the load with the bias.
12514   SDValue Or = DAG.getNode(
12515       ISD::OR, dl, MVT::v2i64,
12516       DAG.getBitcast(MVT::v2i64,
12517                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12518       DAG.getBitcast(MVT::v2i64,
12519                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12520   Or =
12521       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12522                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12523
12524   // Subtract the bias.
12525   // TODO: Are there any fast-math-flags to propagate here?
12526   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12527
12528   // Handle final rounding.
12529   EVT DestVT = Op.getValueType();
12530
12531   if (DestVT.bitsLT(MVT::f64))
12532     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12533                        DAG.getIntPtrConstant(0, dl));
12534   if (DestVT.bitsGT(MVT::f64))
12535     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12536
12537   // Handle final rounding.
12538   return Sub;
12539 }
12540
12541 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12542                                      const X86Subtarget &Subtarget) {
12543   // The algorithm is the following:
12544   // #ifdef __SSE4_1__
12545   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12546   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12547   //                                 (uint4) 0x53000000, 0xaa);
12548   // #else
12549   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12550   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12551   // #endif
12552   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12553   //     return (float4) lo + fhi;
12554
12555   // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12556   // reassociate the two FADDs, and if we do that, the algorithm fails
12557   // spectacularly (PR24512).
12558   // FIXME: If we ever have some kind of Machine FMF, this should be marked
12559   // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12560   // there's also the MachineCombiner reassociations happening on Machine IR.
12561   if (DAG.getTarget().Options.UnsafeFPMath)
12562     return SDValue();
12563
12564   SDLoc DL(Op);
12565   SDValue V = Op->getOperand(0);
12566   EVT VecIntVT = V.getValueType();
12567   bool Is128 = VecIntVT == MVT::v4i32;
12568   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12569   // If we convert to something else than the supported type, e.g., to v4f64,
12570   // abort early.
12571   if (VecFloatVT != Op->getValueType(0))
12572     return SDValue();
12573
12574   unsigned NumElts = VecIntVT.getVectorNumElements();
12575   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12576          "Unsupported custom type");
12577   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12578
12579   // In the #idef/#else code, we have in common:
12580   // - The vector of constants:
12581   // -- 0x4b000000
12582   // -- 0x53000000
12583   // - A shift:
12584   // -- v >> 16
12585
12586   // Create the splat vector for 0x4b000000.
12587   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12588   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12589                            CstLow, CstLow, CstLow, CstLow};
12590   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12591                                   makeArrayRef(&CstLowArray[0], NumElts));
12592   // Create the splat vector for 0x53000000.
12593   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12594   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12595                             CstHigh, CstHigh, CstHigh, CstHigh};
12596   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12597                                    makeArrayRef(&CstHighArray[0], NumElts));
12598
12599   // Create the right shift.
12600   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12601   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12602                              CstShift, CstShift, CstShift, CstShift};
12603   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12604                                     makeArrayRef(&CstShiftArray[0], NumElts));
12605   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12606
12607   SDValue Low, High;
12608   if (Subtarget.hasSSE41()) {
12609     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12610     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12611     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12612     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12613     // Low will be bitcasted right away, so do not bother bitcasting back to its
12614     // original type.
12615     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12616                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12617     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12618     //                                 (uint4) 0x53000000, 0xaa);
12619     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12620     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12621     // High will be bitcasted right away, so do not bother bitcasting back to
12622     // its original type.
12623     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12624                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12625   } else {
12626     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12627     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12628                                      CstMask, CstMask, CstMask);
12629     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12630     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12631     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12632
12633     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12634     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12635   }
12636
12637   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12638   SDValue CstFAdd = DAG.getConstantFP(
12639       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12640   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12641                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12642   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12643                                    makeArrayRef(&CstFAddArray[0], NumElts));
12644
12645   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12646   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12647   // TODO: Are there any fast-math-flags to propagate here?
12648   SDValue FHigh =
12649       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12650   //     return (float4) lo + fhi;
12651   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12652   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12653 }
12654
12655 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12656                                                SelectionDAG &DAG) const {
12657   SDValue N0 = Op.getOperand(0);
12658   MVT SVT = N0.getSimpleValueType();
12659   SDLoc dl(Op);
12660
12661   switch (SVT.SimpleTy) {
12662   default:
12663     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12664   case MVT::v4i8:
12665   case MVT::v4i16:
12666   case MVT::v8i8:
12667   case MVT::v8i16: {
12668     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12669     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12670                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12671   }
12672   case MVT::v4i32:
12673   case MVT::v8i32:
12674     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12675   case MVT::v16i8:
12676   case MVT::v16i16:
12677     if (Subtarget->hasAVX512())
12678       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12679                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12680   }
12681   llvm_unreachable(nullptr);
12682 }
12683
12684 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12685                                            SelectionDAG &DAG) const {
12686   SDValue N0 = Op.getOperand(0);
12687   SDLoc dl(Op);
12688   auto PtrVT = getPointerTy(DAG.getDataLayout());
12689
12690   if (Op.getValueType().isVector())
12691     return lowerUINT_TO_FP_vec(Op, DAG);
12692
12693   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12694   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12695   // the optimization here.
12696   if (DAG.SignBitIsZero(N0))
12697     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12698
12699   MVT SrcVT = N0.getSimpleValueType();
12700   MVT DstVT = Op.getSimpleValueType();
12701
12702   if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
12703       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
12704     // Conversions from unsigned i32 to f32/f64 are legal,
12705     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
12706     return Op;
12707   }
12708
12709   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12710     return LowerUINT_TO_FP_i64(Op, DAG);
12711   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12712     return LowerUINT_TO_FP_i32(Op, DAG);
12713   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12714     return SDValue();
12715
12716   // Make a 64-bit buffer, and use it to build an FILD.
12717   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12718   if (SrcVT == MVT::i32) {
12719     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12720     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12721     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12722                                   StackSlot, MachinePointerInfo(),
12723                                   false, false, 0);
12724     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12725                                   OffsetSlot, MachinePointerInfo(),
12726                                   false, false, 0);
12727     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12728     return Fild;
12729   }
12730
12731   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12732   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12733                                StackSlot, MachinePointerInfo(),
12734                                false, false, 0);
12735   // For i64 source, we need to add the appropriate power of 2 if the input
12736   // was negative.  This is the same as the optimization in
12737   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12738   // we must be careful to do the computation in x87 extended precision, not
12739   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12740   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12741   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12742       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12743       MachineMemOperand::MOLoad, 8, 8);
12744
12745   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12746   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12747   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12748                                          MVT::i64, MMO);
12749
12750   APInt FF(32, 0x5F800000ULL);
12751
12752   // Check whether the sign bit is set.
12753   SDValue SignSet = DAG.getSetCC(
12754       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12755       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12756
12757   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12758   SDValue FudgePtr = DAG.getConstantPool(
12759       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12760
12761   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12762   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12763   SDValue Four = DAG.getIntPtrConstant(4, dl);
12764   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12765                                Zero, Four);
12766   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12767
12768   // Load the value out, extending it from f32 to f80.
12769   // FIXME: Avoid the extend by constructing the right constant pool?
12770   SDValue Fudge = DAG.getExtLoad(
12771       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12772       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12773       false, false, false, 4);
12774   // Extend everything to 80 bits to force it to be done on x87.
12775   // TODO: Are there any fast-math-flags to propagate here?
12776   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12777   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12778                      DAG.getIntPtrConstant(0, dl));
12779 }
12780
12781 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12782 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
12783 // just return an <SDValue(), SDValue()> pair.
12784 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12785 // to i16, i32 or i64, and we lower it to a legal sequence.
12786 // If lowered to the final integer result we return a <result, SDValue()> pair.
12787 // Otherwise we lower it to a sequence ending with a FIST, return a
12788 // <FIST, StackSlot> pair, and the caller is responsible for loading
12789 // the final integer result from StackSlot.
12790 std::pair<SDValue,SDValue>
12791 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12792                                    bool IsSigned, bool IsReplace) const {
12793   SDLoc DL(Op);
12794
12795   EVT DstTy = Op.getValueType();
12796   EVT TheVT = Op.getOperand(0).getValueType();
12797   auto PtrVT = getPointerTy(DAG.getDataLayout());
12798
12799   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
12800     // f16 must be promoted before using the lowering in this routine.
12801     // fp128 does not use this lowering.
12802     return std::make_pair(SDValue(), SDValue());
12803   }
12804
12805   // If using FIST to compute an unsigned i64, we'll need some fixup
12806   // to handle values above the maximum signed i64.  A FIST is always
12807   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12808   bool UnsignedFixup = !IsSigned &&
12809                        DstTy == MVT::i64 &&
12810                        (!Subtarget->is64Bit() ||
12811                         !isScalarFPTypeInSSEReg(TheVT));
12812
12813   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12814     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12815     // The low 32 bits of the fist result will have the correct uint32 result.
12816     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12817     DstTy = MVT::i64;
12818   }
12819
12820   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12821          DstTy.getSimpleVT() >= MVT::i16 &&
12822          "Unknown FP_TO_INT to lower!");
12823
12824   // These are really Legal.
12825   if (DstTy == MVT::i32 &&
12826       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12827     return std::make_pair(SDValue(), SDValue());
12828   if (Subtarget->is64Bit() &&
12829       DstTy == MVT::i64 &&
12830       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12831     return std::make_pair(SDValue(), SDValue());
12832
12833   // We lower FP->int64 into FISTP64 followed by a load from a temporary
12834   // stack slot.
12835   MachineFunction &MF = DAG.getMachineFunction();
12836   unsigned MemSize = DstTy.getSizeInBits()/8;
12837   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12838   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12839
12840   unsigned Opc;
12841   switch (DstTy.getSimpleVT().SimpleTy) {
12842   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12843   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12844   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12845   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12846   }
12847
12848   SDValue Chain = DAG.getEntryNode();
12849   SDValue Value = Op.getOperand(0);
12850   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12851
12852   if (UnsignedFixup) {
12853     //
12854     // Conversion to unsigned i64 is implemented with a select,
12855     // depending on whether the source value fits in the range
12856     // of a signed i64.  Let Thresh be the FP equivalent of
12857     // 0x8000000000000000ULL.
12858     //
12859     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12860     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
12861     //  Fist-to-mem64 FistSrc
12862     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12863     //  to XOR'ing the high 32 bits with Adjust.
12864     //
12865     // Being a power of 2, Thresh is exactly representable in all FP formats.
12866     // For X87 we'd like to use the smallest FP type for this constant, but
12867     // for DAG type consistency we have to match the FP operand type.
12868
12869     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12870     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
12871     bool LosesInfo = false;
12872     if (TheVT == MVT::f64)
12873       // The rounding mode is irrelevant as the conversion should be exact.
12874       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12875                               &LosesInfo);
12876     else if (TheVT == MVT::f80)
12877       Status = Thresh.convert(APFloat::x87DoubleExtended,
12878                               APFloat::rmNearestTiesToEven, &LosesInfo);
12879
12880     assert(Status == APFloat::opOK && !LosesInfo &&
12881            "FP conversion should have been exact");
12882
12883     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12884
12885     SDValue Cmp = DAG.getSetCC(DL,
12886                                getSetCCResultType(DAG.getDataLayout(),
12887                                                   *DAG.getContext(), TheVT),
12888                                Value, ThreshVal, ISD::SETLT);
12889     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12890                            DAG.getConstant(0, DL, MVT::i32),
12891                            DAG.getConstant(0x80000000, DL, MVT::i32));
12892     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12893     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12894                                               *DAG.getContext(), TheVT),
12895                        Value, ThreshVal, ISD::SETLT);
12896     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12897   }
12898
12899   // FIXME This causes a redundant load/store if the SSE-class value is already
12900   // in memory, such as if it is on the callstack.
12901   if (isScalarFPTypeInSSEReg(TheVT)) {
12902     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12903     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12904                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12905                          false, 0);
12906     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12907     SDValue Ops[] = {
12908       Chain, StackSlot, DAG.getValueType(TheVT)
12909     };
12910
12911     MachineMemOperand *MMO =
12912         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12913                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12914     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12915     Chain = Value.getValue(1);
12916     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12917     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12918   }
12919
12920   MachineMemOperand *MMO =
12921       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12922                               MachineMemOperand::MOStore, MemSize, MemSize);
12923
12924   if (UnsignedFixup) {
12925
12926     // Insert the FIST, load its result as two i32's,
12927     // and XOR the high i32 with Adjust.
12928
12929     SDValue FistOps[] = { Chain, Value, StackSlot };
12930     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12931                                            FistOps, DstTy, MMO);
12932
12933     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12934                                 MachinePointerInfo(),
12935                                 false, false, false, 0);
12936     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12937                                    DAG.getConstant(4, DL, PtrVT));
12938
12939     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12940                                  MachinePointerInfo(),
12941                                  false, false, false, 0);
12942     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12943
12944     if (Subtarget->is64Bit()) {
12945       // Join High32 and Low32 into a 64-bit result.
12946       // (High32 << 32) | Low32
12947       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12948       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12949       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12950                            DAG.getConstant(32, DL, MVT::i8));
12951       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12952       return std::make_pair(Result, SDValue());
12953     }
12954
12955     SDValue ResultOps[] = { Low32, High32 };
12956
12957     SDValue pair = IsReplace
12958       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12959       : DAG.getMergeValues(ResultOps, DL);
12960     return std::make_pair(pair, SDValue());
12961   } else {
12962     // Build the FP_TO_INT*_IN_MEM
12963     SDValue Ops[] = { Chain, Value, StackSlot };
12964     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12965                                            Ops, DstTy, MMO);
12966     return std::make_pair(FIST, StackSlot);
12967   }
12968 }
12969
12970 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12971                               const X86Subtarget *Subtarget) {
12972   MVT VT = Op->getSimpleValueType(0);
12973   SDValue In = Op->getOperand(0);
12974   MVT InVT = In.getSimpleValueType();
12975   SDLoc dl(Op);
12976
12977   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12978     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12979
12980   // Optimize vectors in AVX mode:
12981   //
12982   //   v8i16 -> v8i32
12983   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12984   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12985   //   Concat upper and lower parts.
12986   //
12987   //   v4i32 -> v4i64
12988   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12989   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12990   //   Concat upper and lower parts.
12991   //
12992
12993   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12994       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12995       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12996     return SDValue();
12997
12998   if (Subtarget->hasInt256())
12999     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13000
13001   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13002   SDValue Undef = DAG.getUNDEF(InVT);
13003   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13004   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13005   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13006
13007   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13008                              VT.getVectorNumElements()/2);
13009
13010   OpLo = DAG.getBitcast(HVT, OpLo);
13011   OpHi = DAG.getBitcast(HVT, OpHi);
13012
13013   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13014 }
13015
13016 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13017                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13018   MVT VT = Op->getSimpleValueType(0);
13019   SDValue In = Op->getOperand(0);
13020   MVT InVT = In.getSimpleValueType();
13021   SDLoc DL(Op);
13022   unsigned int NumElts = VT.getVectorNumElements();
13023   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13024     return SDValue();
13025
13026   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13027     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13028
13029   assert(InVT.getVectorElementType() == MVT::i1);
13030   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13031   SDValue One =
13032    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13033   SDValue Zero =
13034    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13035
13036   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13037   if (VT.is512BitVector())
13038     return V;
13039   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13040 }
13041
13042 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13043                                SelectionDAG &DAG) {
13044   if (Subtarget->hasFp256())
13045     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13046       return Res;
13047
13048   return SDValue();
13049 }
13050
13051 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13052                                 SelectionDAG &DAG) {
13053   SDLoc DL(Op);
13054   MVT VT = Op.getSimpleValueType();
13055   SDValue In = Op.getOperand(0);
13056   MVT SVT = In.getSimpleValueType();
13057
13058   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13059     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13060
13061   if (Subtarget->hasFp256())
13062     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13063       return Res;
13064
13065   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13066          VT.getVectorNumElements() != SVT.getVectorNumElements());
13067   return SDValue();
13068 }
13069
13070 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13071   SDLoc DL(Op);
13072   MVT VT = Op.getSimpleValueType();
13073   SDValue In = Op.getOperand(0);
13074   MVT InVT = In.getSimpleValueType();
13075
13076   if (VT == MVT::i1) {
13077     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13078            "Invalid scalar TRUNCATE operation");
13079     if (InVT.getSizeInBits() >= 32)
13080       return SDValue();
13081     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13082     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13083   }
13084   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13085          "Invalid TRUNCATE operation");
13086
13087   // move vector to mask - truncate solution for SKX
13088   if (VT.getVectorElementType() == MVT::i1) {
13089     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13090         Subtarget->hasBWI())
13091       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13092     if ((InVT.is256BitVector() || InVT.is128BitVector())
13093         && InVT.getScalarSizeInBits() <= 16 &&
13094         Subtarget->hasBWI() && Subtarget->hasVLX())
13095       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13096     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13097         Subtarget->hasDQI())
13098       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
13099     if ((InVT.is256BitVector() || InVT.is128BitVector())
13100         && InVT.getScalarSizeInBits() >= 32 &&
13101         Subtarget->hasDQI() && Subtarget->hasVLX())
13102       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
13103   }
13104
13105   if (VT.getVectorElementType() == MVT::i1) {
13106     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13107     unsigned NumElts = InVT.getVectorNumElements();
13108     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
13109     if (InVT.getSizeInBits() < 512) {
13110       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
13111       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13112       InVT = ExtVT;
13113     }
13114
13115     SDValue OneV =
13116      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
13117     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
13118     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
13119   }
13120
13121   // vpmovqb/w/d, vpmovdb/w, vpmovwb
13122   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
13123       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
13124     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13125
13126   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13127     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13128     if (Subtarget->hasInt256()) {
13129       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13130       In = DAG.getBitcast(MVT::v8i32, In);
13131       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13132                                 ShufMask);
13133       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13134                          DAG.getIntPtrConstant(0, DL));
13135     }
13136
13137     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13138                                DAG.getIntPtrConstant(0, DL));
13139     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13140                                DAG.getIntPtrConstant(2, DL));
13141     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13142     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13143     static const int ShufMask[] = {0, 2, 4, 6};
13144     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13145   }
13146
13147   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13148     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13149     if (Subtarget->hasInt256()) {
13150       In = DAG.getBitcast(MVT::v32i8, In);
13151
13152       SmallVector<SDValue,32> pshufbMask;
13153       for (unsigned i = 0; i < 2; ++i) {
13154         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13155         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13156         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13157         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13158         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13159         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13160         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13161         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13162         for (unsigned j = 0; j < 8; ++j)
13163           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13164       }
13165       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13166       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13167       In = DAG.getBitcast(MVT::v4i64, In);
13168
13169       static const int ShufMask[] = {0,  2,  -1,  -1};
13170       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13171                                 &ShufMask[0]);
13172       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13173                        DAG.getIntPtrConstant(0, DL));
13174       return DAG.getBitcast(VT, In);
13175     }
13176
13177     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13178                                DAG.getIntPtrConstant(0, DL));
13179
13180     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13181                                DAG.getIntPtrConstant(4, DL));
13182
13183     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13184     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13185
13186     // The PSHUFB mask:
13187     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13188                                    -1, -1, -1, -1, -1, -1, -1, -1};
13189
13190     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13191     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13192     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13193
13194     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13195     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13196
13197     // The MOVLHPS Mask:
13198     static const int ShufMask2[] = {0, 1, 4, 5};
13199     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13200     return DAG.getBitcast(MVT::v8i16, res);
13201   }
13202
13203   // Handle truncation of V256 to V128 using shuffles.
13204   if (!VT.is128BitVector() || !InVT.is256BitVector())
13205     return SDValue();
13206
13207   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13208
13209   unsigned NumElems = VT.getVectorNumElements();
13210   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13211
13212   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13213   // Prepare truncation shuffle mask
13214   for (unsigned i = 0; i != NumElems; ++i)
13215     MaskVec[i] = i * 2;
13216   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13217                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13218   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13219                      DAG.getIntPtrConstant(0, DL));
13220 }
13221
13222 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13223                                            SelectionDAG &DAG) const {
13224   assert(!Op.getSimpleValueType().isVector());
13225
13226   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13227     /*IsSigned=*/ true, /*IsReplace=*/ false);
13228   SDValue FIST = Vals.first, StackSlot = Vals.second;
13229   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13230   if (!FIST.getNode())
13231     return Op;
13232
13233   if (StackSlot.getNode())
13234     // Load the result.
13235     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13236                        FIST, StackSlot, MachinePointerInfo(),
13237                        false, false, false, 0);
13238
13239   // The node is the result.
13240   return FIST;
13241 }
13242
13243 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13244                                            SelectionDAG &DAG) const {
13245   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13246     /*IsSigned=*/ false, /*IsReplace=*/ false);
13247   SDValue FIST = Vals.first, StackSlot = Vals.second;
13248   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13249   if (!FIST.getNode())
13250     return Op;
13251
13252   if (StackSlot.getNode())
13253     // Load the result.
13254     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13255                        FIST, StackSlot, MachinePointerInfo(),
13256                        false, false, false, 0);
13257
13258   // The node is the result.
13259   return FIST;
13260 }
13261
13262 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13263   SDLoc DL(Op);
13264   MVT VT = Op.getSimpleValueType();
13265   SDValue In = Op.getOperand(0);
13266   MVT SVT = In.getSimpleValueType();
13267
13268   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13269
13270   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13271                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13272                                  In, DAG.getUNDEF(SVT)));
13273 }
13274
13275 /// The only differences between FABS and FNEG are the mask and the logic op.
13276 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13277 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13278   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13279          "Wrong opcode for lowering FABS or FNEG.");
13280
13281   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13282
13283   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13284   // into an FNABS. We'll lower the FABS after that if it is still in use.
13285   if (IsFABS)
13286     for (SDNode *User : Op->uses())
13287       if (User->getOpcode() == ISD::FNEG)
13288         return Op;
13289
13290   SDLoc dl(Op);
13291   MVT VT = Op.getSimpleValueType();
13292
13293   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13294   // decide if we should generate a 16-byte constant mask when we only need 4 or
13295   // 8 bytes for the scalar case.
13296
13297   MVT LogicVT;
13298   MVT EltVT;
13299   unsigned NumElts;
13300
13301   if (VT.isVector()) {
13302     LogicVT = VT;
13303     EltVT = VT.getVectorElementType();
13304     NumElts = VT.getVectorNumElements();
13305   } else {
13306     // There are no scalar bitwise logical SSE/AVX instructions, so we
13307     // generate a 16-byte vector constant and logic op even for the scalar case.
13308     // Using a 16-byte mask allows folding the load of the mask with
13309     // the logic op, so it can save (~4 bytes) on code size.
13310     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13311     EltVT = VT;
13312     NumElts = (VT == MVT::f64) ? 2 : 4;
13313   }
13314
13315   unsigned EltBits = EltVT.getSizeInBits();
13316   LLVMContext *Context = DAG.getContext();
13317   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13318   APInt MaskElt =
13319     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13320   Constant *C = ConstantInt::get(*Context, MaskElt);
13321   C = ConstantVector::getSplat(NumElts, C);
13322   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13323   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13324   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13325   SDValue Mask =
13326       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13327                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13328                   false, false, false, Alignment);
13329
13330   SDValue Op0 = Op.getOperand(0);
13331   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13332   unsigned LogicOp =
13333     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13334   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13335
13336   if (VT.isVector())
13337     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13338
13339   // For the scalar case extend to a 128-bit vector, perform the logic op,
13340   // and extract the scalar result back out.
13341   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13342   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13343   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13344                      DAG.getIntPtrConstant(0, dl));
13345 }
13346
13347 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13348   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13349   LLVMContext *Context = DAG.getContext();
13350   SDValue Op0 = Op.getOperand(0);
13351   SDValue Op1 = Op.getOperand(1);
13352   SDLoc dl(Op);
13353   MVT VT = Op.getSimpleValueType();
13354   MVT SrcVT = Op1.getSimpleValueType();
13355
13356   // If second operand is smaller, extend it first.
13357   if (SrcVT.bitsLT(VT)) {
13358     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13359     SrcVT = VT;
13360   }
13361   // And if it is bigger, shrink it first.
13362   if (SrcVT.bitsGT(VT)) {
13363     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13364     SrcVT = VT;
13365   }
13366
13367   // At this point the operands and the result should have the same
13368   // type, and that won't be f80 since that is not custom lowered.
13369
13370   const fltSemantics &Sem =
13371       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
13372   const unsigned SizeInBits = VT.getSizeInBits();
13373
13374   SmallVector<Constant *, 4> CV(
13375       VT == MVT::f64 ? 2 : 4,
13376       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13377
13378   // First, clear all bits but the sign bit from the second operand (sign).
13379   CV[0] = ConstantFP::get(*Context,
13380                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13381   Constant *C = ConstantVector::get(CV);
13382   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13383   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13384
13385   // Perform all logic operations as 16-byte vectors because there are no
13386   // scalar FP logic instructions in SSE. This allows load folding of the
13387   // constants into the logic instructions.
13388   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13389   SDValue Mask1 =
13390       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13391                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13392                   false, false, false, 16);
13393   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13394   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13395
13396   // Next, clear the sign bit from the first operand (magnitude).
13397   // If it's a constant, we can clear it here.
13398   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13399     APFloat APF = Op0CN->getValueAPF();
13400     // If the magnitude is a positive zero, the sign bit alone is enough.
13401     if (APF.isPosZero())
13402       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13403                          DAG.getIntPtrConstant(0, dl));
13404     APF.clearSign();
13405     CV[0] = ConstantFP::get(*Context, APF);
13406   } else {
13407     CV[0] = ConstantFP::get(
13408         *Context,
13409         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13410   }
13411   C = ConstantVector::get(CV);
13412   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13413   SDValue Val =
13414       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13415                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13416                   false, false, false, 16);
13417   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13418   if (!isa<ConstantFPSDNode>(Op0)) {
13419     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13420     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13421   }
13422   // OR the magnitude value with the sign bit.
13423   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13424   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13425                      DAG.getIntPtrConstant(0, dl));
13426 }
13427
13428 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13429   SDValue N0 = Op.getOperand(0);
13430   SDLoc dl(Op);
13431   MVT VT = Op.getSimpleValueType();
13432
13433   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13434   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13435                                   DAG.getConstant(1, dl, VT));
13436   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13437 }
13438
13439 // Check whether an OR'd tree is PTEST-able.
13440 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13441                                       SelectionDAG &DAG) {
13442   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13443
13444   if (!Subtarget->hasSSE41())
13445     return SDValue();
13446
13447   if (!Op->hasOneUse())
13448     return SDValue();
13449
13450   SDNode *N = Op.getNode();
13451   SDLoc DL(N);
13452
13453   SmallVector<SDValue, 8> Opnds;
13454   DenseMap<SDValue, unsigned> VecInMap;
13455   SmallVector<SDValue, 8> VecIns;
13456   EVT VT = MVT::Other;
13457
13458   // Recognize a special case where a vector is casted into wide integer to
13459   // test all 0s.
13460   Opnds.push_back(N->getOperand(0));
13461   Opnds.push_back(N->getOperand(1));
13462
13463   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13464     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13465     // BFS traverse all OR'd operands.
13466     if (I->getOpcode() == ISD::OR) {
13467       Opnds.push_back(I->getOperand(0));
13468       Opnds.push_back(I->getOperand(1));
13469       // Re-evaluate the number of nodes to be traversed.
13470       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13471       continue;
13472     }
13473
13474     // Quit if a non-EXTRACT_VECTOR_ELT
13475     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13476       return SDValue();
13477
13478     // Quit if without a constant index.
13479     SDValue Idx = I->getOperand(1);
13480     if (!isa<ConstantSDNode>(Idx))
13481       return SDValue();
13482
13483     SDValue ExtractedFromVec = I->getOperand(0);
13484     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13485     if (M == VecInMap.end()) {
13486       VT = ExtractedFromVec.getValueType();
13487       // Quit if not 128/256-bit vector.
13488       if (!VT.is128BitVector() && !VT.is256BitVector())
13489         return SDValue();
13490       // Quit if not the same type.
13491       if (VecInMap.begin() != VecInMap.end() &&
13492           VT != VecInMap.begin()->first.getValueType())
13493         return SDValue();
13494       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13495       VecIns.push_back(ExtractedFromVec);
13496     }
13497     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13498   }
13499
13500   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13501          "Not extracted from 128-/256-bit vector.");
13502
13503   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13504
13505   for (DenseMap<SDValue, unsigned>::const_iterator
13506         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13507     // Quit if not all elements are used.
13508     if (I->second != FullMask)
13509       return SDValue();
13510   }
13511
13512   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13513
13514   // Cast all vectors into TestVT for PTEST.
13515   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13516     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13517
13518   // If more than one full vectors are evaluated, OR them first before PTEST.
13519   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13520     // Each iteration will OR 2 nodes and append the result until there is only
13521     // 1 node left, i.e. the final OR'd value of all vectors.
13522     SDValue LHS = VecIns[Slot];
13523     SDValue RHS = VecIns[Slot + 1];
13524     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13525   }
13526
13527   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13528                      VecIns.back(), VecIns.back());
13529 }
13530
13531 /// \brief return true if \c Op has a use that doesn't just read flags.
13532 static bool hasNonFlagsUse(SDValue Op) {
13533   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13534        ++UI) {
13535     SDNode *User = *UI;
13536     unsigned UOpNo = UI.getOperandNo();
13537     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13538       // Look pass truncate.
13539       UOpNo = User->use_begin().getOperandNo();
13540       User = *User->use_begin();
13541     }
13542
13543     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13544         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13545       return true;
13546   }
13547   return false;
13548 }
13549
13550 /// Emit nodes that will be selected as "test Op0,Op0", or something
13551 /// equivalent.
13552 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13553                                     SelectionDAG &DAG) const {
13554   if (Op.getValueType() == MVT::i1) {
13555     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13556     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13557                        DAG.getConstant(0, dl, MVT::i8));
13558   }
13559   // CF and OF aren't always set the way we want. Determine which
13560   // of these we need.
13561   bool NeedCF = false;
13562   bool NeedOF = false;
13563   switch (X86CC) {
13564   default: break;
13565   case X86::COND_A: case X86::COND_AE:
13566   case X86::COND_B: case X86::COND_BE:
13567     NeedCF = true;
13568     break;
13569   case X86::COND_G: case X86::COND_GE:
13570   case X86::COND_L: case X86::COND_LE:
13571   case X86::COND_O: case X86::COND_NO: {
13572     // Check if we really need to set the
13573     // Overflow flag. If NoSignedWrap is present
13574     // that is not actually needed.
13575     switch (Op->getOpcode()) {
13576     case ISD::ADD:
13577     case ISD::SUB:
13578     case ISD::MUL:
13579     case ISD::SHL: {
13580       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13581       if (BinNode->Flags.hasNoSignedWrap())
13582         break;
13583     }
13584     default:
13585       NeedOF = true;
13586       break;
13587     }
13588     break;
13589   }
13590   }
13591   // See if we can use the EFLAGS value from the operand instead of
13592   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13593   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13594   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13595     // Emit a CMP with 0, which is the TEST pattern.
13596     //if (Op.getValueType() == MVT::i1)
13597     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13598     //                     DAG.getConstant(0, MVT::i1));
13599     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13600                        DAG.getConstant(0, dl, Op.getValueType()));
13601   }
13602   unsigned Opcode = 0;
13603   unsigned NumOperands = 0;
13604
13605   // Truncate operations may prevent the merge of the SETCC instruction
13606   // and the arithmetic instruction before it. Attempt to truncate the operands
13607   // of the arithmetic instruction and use a reduced bit-width instruction.
13608   bool NeedTruncation = false;
13609   SDValue ArithOp = Op;
13610   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13611     SDValue Arith = Op->getOperand(0);
13612     // Both the trunc and the arithmetic op need to have one user each.
13613     if (Arith->hasOneUse())
13614       switch (Arith.getOpcode()) {
13615         default: break;
13616         case ISD::ADD:
13617         case ISD::SUB:
13618         case ISD::AND:
13619         case ISD::OR:
13620         case ISD::XOR: {
13621           NeedTruncation = true;
13622           ArithOp = Arith;
13623         }
13624       }
13625   }
13626
13627   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13628   // which may be the result of a CAST.  We use the variable 'Op', which is the
13629   // non-casted variable when we check for possible users.
13630   switch (ArithOp.getOpcode()) {
13631   case ISD::ADD:
13632     // Due to an isel shortcoming, be conservative if this add is likely to be
13633     // selected as part of a load-modify-store instruction. When the root node
13634     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13635     // uses of other nodes in the match, such as the ADD in this case. This
13636     // leads to the ADD being left around and reselected, with the result being
13637     // two adds in the output.  Alas, even if none our users are stores, that
13638     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13639     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13640     // climbing the DAG back to the root, and it doesn't seem to be worth the
13641     // effort.
13642     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13643          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13644       if (UI->getOpcode() != ISD::CopyToReg &&
13645           UI->getOpcode() != ISD::SETCC &&
13646           UI->getOpcode() != ISD::STORE)
13647         goto default_case;
13648
13649     if (ConstantSDNode *C =
13650         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13651       // An add of one will be selected as an INC.
13652       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13653         Opcode = X86ISD::INC;
13654         NumOperands = 1;
13655         break;
13656       }
13657
13658       // An add of negative one (subtract of one) will be selected as a DEC.
13659       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13660         Opcode = X86ISD::DEC;
13661         NumOperands = 1;
13662         break;
13663       }
13664     }
13665
13666     // Otherwise use a regular EFLAGS-setting add.
13667     Opcode = X86ISD::ADD;
13668     NumOperands = 2;
13669     break;
13670   case ISD::SHL:
13671   case ISD::SRL:
13672     // If we have a constant logical shift that's only used in a comparison
13673     // against zero turn it into an equivalent AND. This allows turning it into
13674     // a TEST instruction later.
13675     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13676         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13677       EVT VT = Op.getValueType();
13678       unsigned BitWidth = VT.getSizeInBits();
13679       unsigned ShAmt = Op->getConstantOperandVal(1);
13680       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13681         break;
13682       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13683                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13684                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13685       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13686         break;
13687       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13688                                 DAG.getConstant(Mask, dl, VT));
13689       DAG.ReplaceAllUsesWith(Op, New);
13690       Op = New;
13691     }
13692     break;
13693
13694   case ISD::AND:
13695     // If the primary and result isn't used, don't bother using X86ISD::AND,
13696     // because a TEST instruction will be better.
13697     if (!hasNonFlagsUse(Op))
13698       break;
13699     // FALL THROUGH
13700   case ISD::SUB:
13701   case ISD::OR:
13702   case ISD::XOR:
13703     // Due to the ISEL shortcoming noted above, be conservative if this op is
13704     // likely to be selected as part of a load-modify-store instruction.
13705     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13706            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13707       if (UI->getOpcode() == ISD::STORE)
13708         goto default_case;
13709
13710     // Otherwise use a regular EFLAGS-setting instruction.
13711     switch (ArithOp.getOpcode()) {
13712     default: llvm_unreachable("unexpected operator!");
13713     case ISD::SUB: Opcode = X86ISD::SUB; break;
13714     case ISD::XOR: Opcode = X86ISD::XOR; break;
13715     case ISD::AND: Opcode = X86ISD::AND; break;
13716     case ISD::OR: {
13717       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13718         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13719         if (EFLAGS.getNode())
13720           return EFLAGS;
13721       }
13722       Opcode = X86ISD::OR;
13723       break;
13724     }
13725     }
13726
13727     NumOperands = 2;
13728     break;
13729   case X86ISD::ADD:
13730   case X86ISD::SUB:
13731   case X86ISD::INC:
13732   case X86ISD::DEC:
13733   case X86ISD::OR:
13734   case X86ISD::XOR:
13735   case X86ISD::AND:
13736     return SDValue(Op.getNode(), 1);
13737   default:
13738   default_case:
13739     break;
13740   }
13741
13742   // If we found that truncation is beneficial, perform the truncation and
13743   // update 'Op'.
13744   if (NeedTruncation) {
13745     EVT VT = Op.getValueType();
13746     SDValue WideVal = Op->getOperand(0);
13747     EVT WideVT = WideVal.getValueType();
13748     unsigned ConvertedOp = 0;
13749     // Use a target machine opcode to prevent further DAGCombine
13750     // optimizations that may separate the arithmetic operations
13751     // from the setcc node.
13752     switch (WideVal.getOpcode()) {
13753       default: break;
13754       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13755       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13756       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13757       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13758       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13759     }
13760
13761     if (ConvertedOp) {
13762       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13763       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13764         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13765         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13766         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13767       }
13768     }
13769   }
13770
13771   if (Opcode == 0)
13772     // Emit a CMP with 0, which is the TEST pattern.
13773     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13774                        DAG.getConstant(0, dl, Op.getValueType()));
13775
13776   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13777   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13778
13779   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13780   DAG.ReplaceAllUsesWith(Op, New);
13781   return SDValue(New.getNode(), 1);
13782 }
13783
13784 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13785 /// equivalent.
13786 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13787                                    SDLoc dl, SelectionDAG &DAG) const {
13788   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13789     if (C->getAPIntValue() == 0)
13790       return EmitTest(Op0, X86CC, dl, DAG);
13791
13792      if (Op0.getValueType() == MVT::i1)
13793        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13794   }
13795
13796   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13797        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13798     // Do the comparison at i32 if it's smaller, besides the Atom case.
13799     // This avoids subregister aliasing issues. Keep the smaller reference
13800     // if we're optimizing for size, however, as that'll allow better folding
13801     // of memory operations.
13802     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13803         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13804         !Subtarget->isAtom()) {
13805       unsigned ExtendOp =
13806           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13807       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13808       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13809     }
13810     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13811     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13812     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13813                               Op0, Op1);
13814     return SDValue(Sub.getNode(), 1);
13815   }
13816   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13817 }
13818
13819 /// Convert a comparison if required by the subtarget.
13820 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13821                                                  SelectionDAG &DAG) const {
13822   // If the subtarget does not support the FUCOMI instruction, floating-point
13823   // comparisons have to be converted.
13824   if (Subtarget->hasCMov() ||
13825       Cmp.getOpcode() != X86ISD::CMP ||
13826       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13827       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13828     return Cmp;
13829
13830   // The instruction selector will select an FUCOM instruction instead of
13831   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13832   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13833   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13834   SDLoc dl(Cmp);
13835   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13836   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13837   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13838                             DAG.getConstant(8, dl, MVT::i8));
13839   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13840   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13841 }
13842
13843 /// The minimum architected relative accuracy is 2^-12. We need one
13844 /// Newton-Raphson step to have a good float result (24 bits of precision).
13845 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13846                                             DAGCombinerInfo &DCI,
13847                                             unsigned &RefinementSteps,
13848                                             bool &UseOneConstNR) const {
13849   EVT VT = Op.getValueType();
13850   const char *RecipOp;
13851
13852   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13853   // TODO: Add support for AVX512 (v16f32).
13854   // It is likely not profitable to do this for f64 because a double-precision
13855   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13856   // instructions: convert to single, rsqrtss, convert back to double, refine
13857   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13858   // along with FMA, this could be a throughput win.
13859   if (VT == MVT::f32 && Subtarget->hasSSE1())
13860     RecipOp = "sqrtf";
13861   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13862            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13863     RecipOp = "vec-sqrtf";
13864   else
13865     return SDValue();
13866
13867   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13868   if (!Recips.isEnabled(RecipOp))
13869     return SDValue();
13870
13871   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13872   UseOneConstNR = false;
13873   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13874 }
13875
13876 /// The minimum architected relative accuracy is 2^-12. We need one
13877 /// Newton-Raphson step to have a good float result (24 bits of precision).
13878 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13879                                             DAGCombinerInfo &DCI,
13880                                             unsigned &RefinementSteps) const {
13881   EVT VT = Op.getValueType();
13882   const char *RecipOp;
13883
13884   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13885   // TODO: Add support for AVX512 (v16f32).
13886   // It is likely not profitable to do this for f64 because a double-precision
13887   // reciprocal estimate with refinement on x86 prior to FMA requires
13888   // 15 instructions: convert to single, rcpss, convert back to double, refine
13889   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13890   // along with FMA, this could be a throughput win.
13891   if (VT == MVT::f32 && Subtarget->hasSSE1())
13892     RecipOp = "divf";
13893   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13894            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13895     RecipOp = "vec-divf";
13896   else
13897     return SDValue();
13898
13899   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13900   if (!Recips.isEnabled(RecipOp))
13901     return SDValue();
13902
13903   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13904   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13905 }
13906
13907 /// If we have at least two divisions that use the same divisor, convert to
13908 /// multplication by a reciprocal. This may need to be adjusted for a given
13909 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13910 /// This is because we still need one division to calculate the reciprocal and
13911 /// then we need two multiplies by that reciprocal as replacements for the
13912 /// original divisions.
13913 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13914   return 2;
13915 }
13916
13917 static bool isAllOnes(SDValue V) {
13918   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13919   return C && C->isAllOnesValue();
13920 }
13921
13922 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13923 /// if it's possible.
13924 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13925                                      SDLoc dl, SelectionDAG &DAG) const {
13926   SDValue Op0 = And.getOperand(0);
13927   SDValue Op1 = And.getOperand(1);
13928   if (Op0.getOpcode() == ISD::TRUNCATE)
13929     Op0 = Op0.getOperand(0);
13930   if (Op1.getOpcode() == ISD::TRUNCATE)
13931     Op1 = Op1.getOperand(0);
13932
13933   SDValue LHS, RHS;
13934   if (Op1.getOpcode() == ISD::SHL)
13935     std::swap(Op0, Op1);
13936   if (Op0.getOpcode() == ISD::SHL) {
13937     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13938       if (And00C->getZExtValue() == 1) {
13939         // If we looked past a truncate, check that it's only truncating away
13940         // known zeros.
13941         unsigned BitWidth = Op0.getValueSizeInBits();
13942         unsigned AndBitWidth = And.getValueSizeInBits();
13943         if (BitWidth > AndBitWidth) {
13944           APInt Zeros, Ones;
13945           DAG.computeKnownBits(Op0, Zeros, Ones);
13946           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13947             return SDValue();
13948         }
13949         LHS = Op1;
13950         RHS = Op0.getOperand(1);
13951       }
13952   } else if (Op1.getOpcode() == ISD::Constant) {
13953     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13954     uint64_t AndRHSVal = AndRHS->getZExtValue();
13955     SDValue AndLHS = Op0;
13956
13957     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13958       LHS = AndLHS.getOperand(0);
13959       RHS = AndLHS.getOperand(1);
13960     }
13961
13962     // Use BT if the immediate can't be encoded in a TEST instruction.
13963     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13964       LHS = AndLHS;
13965       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13966     }
13967   }
13968
13969   if (LHS.getNode()) {
13970     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13971     // instruction.  Since the shift amount is in-range-or-undefined, we know
13972     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13973     // the encoding for the i16 version is larger than the i32 version.
13974     // Also promote i16 to i32 for performance / code size reason.
13975     if (LHS.getValueType() == MVT::i8 ||
13976         LHS.getValueType() == MVT::i16)
13977       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13978
13979     // If the operand types disagree, extend the shift amount to match.  Since
13980     // BT ignores high bits (like shifts) we can use anyextend.
13981     if (LHS.getValueType() != RHS.getValueType())
13982       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13983
13984     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13985     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13986     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13987                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13988   }
13989
13990   return SDValue();
13991 }
13992
13993 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13994 /// mask CMPs.
13995 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13996                               SDValue &Op1) {
13997   unsigned SSECC;
13998   bool Swap = false;
13999
14000   // SSE Condition code mapping:
14001   //  0 - EQ
14002   //  1 - LT
14003   //  2 - LE
14004   //  3 - UNORD
14005   //  4 - NEQ
14006   //  5 - NLT
14007   //  6 - NLE
14008   //  7 - ORD
14009   switch (SetCCOpcode) {
14010   default: llvm_unreachable("Unexpected SETCC condition");
14011   case ISD::SETOEQ:
14012   case ISD::SETEQ:  SSECC = 0; break;
14013   case ISD::SETOGT:
14014   case ISD::SETGT:  Swap = true; // Fallthrough
14015   case ISD::SETLT:
14016   case ISD::SETOLT: SSECC = 1; break;
14017   case ISD::SETOGE:
14018   case ISD::SETGE:  Swap = true; // Fallthrough
14019   case ISD::SETLE:
14020   case ISD::SETOLE: SSECC = 2; break;
14021   case ISD::SETUO:  SSECC = 3; break;
14022   case ISD::SETUNE:
14023   case ISD::SETNE:  SSECC = 4; break;
14024   case ISD::SETULE: Swap = true; // Fallthrough
14025   case ISD::SETUGE: SSECC = 5; break;
14026   case ISD::SETULT: Swap = true; // Fallthrough
14027   case ISD::SETUGT: SSECC = 6; break;
14028   case ISD::SETO:   SSECC = 7; break;
14029   case ISD::SETUEQ:
14030   case ISD::SETONE: SSECC = 8; break;
14031   }
14032   if (Swap)
14033     std::swap(Op0, Op1);
14034
14035   return SSECC;
14036 }
14037
14038 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14039 // ones, and then concatenate the result back.
14040 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14041   MVT VT = Op.getSimpleValueType();
14042
14043   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14044          "Unsupported value type for operation");
14045
14046   unsigned NumElems = VT.getVectorNumElements();
14047   SDLoc dl(Op);
14048   SDValue CC = Op.getOperand(2);
14049
14050   // Extract the LHS vectors
14051   SDValue LHS = Op.getOperand(0);
14052   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14053   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14054
14055   // Extract the RHS vectors
14056   SDValue RHS = Op.getOperand(1);
14057   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14058   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14059
14060   // Issue the operation on the smaller types and concatenate the result back
14061   MVT EltVT = VT.getVectorElementType();
14062   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14063   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14064                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14065                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14066 }
14067
14068 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14069   SDValue Op0 = Op.getOperand(0);
14070   SDValue Op1 = Op.getOperand(1);
14071   SDValue CC = Op.getOperand(2);
14072   MVT VT = Op.getSimpleValueType();
14073   SDLoc dl(Op);
14074
14075   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
14076          "Unexpected type for boolean compare operation");
14077   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14078   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14079                                DAG.getConstant(-1, dl, VT));
14080   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14081                                DAG.getConstant(-1, dl, VT));
14082   switch (SetCCOpcode) {
14083   default: llvm_unreachable("Unexpected SETCC condition");
14084   case ISD::SETEQ:
14085     // (x == y) -> ~(x ^ y)
14086     return DAG.getNode(ISD::XOR, dl, VT,
14087                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14088                        DAG.getConstant(-1, dl, VT));
14089   case ISD::SETNE:
14090     // (x != y) -> (x ^ y)
14091     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14092   case ISD::SETUGT:
14093   case ISD::SETGT:
14094     // (x > y) -> (x & ~y)
14095     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14096   case ISD::SETULT:
14097   case ISD::SETLT:
14098     // (x < y) -> (~x & y)
14099     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14100   case ISD::SETULE:
14101   case ISD::SETLE:
14102     // (x <= y) -> (~x | y)
14103     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14104   case ISD::SETUGE:
14105   case ISD::SETGE:
14106     // (x >=y) -> (x | ~y)
14107     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14108   }
14109 }
14110
14111 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14112                                      const X86Subtarget *Subtarget) {
14113   SDValue Op0 = Op.getOperand(0);
14114   SDValue Op1 = Op.getOperand(1);
14115   SDValue CC = Op.getOperand(2);
14116   MVT VT = Op.getSimpleValueType();
14117   SDLoc dl(Op);
14118
14119   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
14120          Op.getValueType().getScalarType() == MVT::i1 &&
14121          "Cannot set masked compare for this operation");
14122
14123   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14124   unsigned  Opc = 0;
14125   bool Unsigned = false;
14126   bool Swap = false;
14127   unsigned SSECC;
14128   switch (SetCCOpcode) {
14129   default: llvm_unreachable("Unexpected SETCC condition");
14130   case ISD::SETNE:  SSECC = 4; break;
14131   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14132   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14133   case ISD::SETLT:  Swap = true; //fall-through
14134   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14135   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14136   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14137   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14138   case ISD::SETULE: Unsigned = true; //fall-through
14139   case ISD::SETLE:  SSECC = 2; break;
14140   }
14141
14142   if (Swap)
14143     std::swap(Op0, Op1);
14144   if (Opc)
14145     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14146   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14147   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14148                      DAG.getConstant(SSECC, dl, MVT::i8));
14149 }
14150
14151 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14152 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14153 /// return an empty value.
14154 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14155 {
14156   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14157   if (!BV)
14158     return SDValue();
14159
14160   MVT VT = Op1.getSimpleValueType();
14161   MVT EVT = VT.getVectorElementType();
14162   unsigned n = VT.getVectorNumElements();
14163   SmallVector<SDValue, 8> ULTOp1;
14164
14165   for (unsigned i = 0; i < n; ++i) {
14166     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14167     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
14168       return SDValue();
14169
14170     // Avoid underflow.
14171     APInt Val = Elt->getAPIntValue();
14172     if (Val == 0)
14173       return SDValue();
14174
14175     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14176   }
14177
14178   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14179 }
14180
14181 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14182                            SelectionDAG &DAG) {
14183   SDValue Op0 = Op.getOperand(0);
14184   SDValue Op1 = Op.getOperand(1);
14185   SDValue CC = Op.getOperand(2);
14186   MVT VT = Op.getSimpleValueType();
14187   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14188   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14189   SDLoc dl(Op);
14190
14191   if (isFP) {
14192 #ifndef NDEBUG
14193     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14194     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14195 #endif
14196
14197     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14198     unsigned Opc = X86ISD::CMPP;
14199     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14200       assert(VT.getVectorNumElements() <= 16);
14201       Opc = X86ISD::CMPM;
14202     }
14203     // In the two special cases we can't handle, emit two comparisons.
14204     if (SSECC == 8) {
14205       unsigned CC0, CC1;
14206       unsigned CombineOpc;
14207       if (SetCCOpcode == ISD::SETUEQ) {
14208         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14209       } else {
14210         assert(SetCCOpcode == ISD::SETONE);
14211         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14212       }
14213
14214       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14215                                  DAG.getConstant(CC0, dl, MVT::i8));
14216       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14217                                  DAG.getConstant(CC1, dl, MVT::i8));
14218       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14219     }
14220     // Handle all other FP comparisons here.
14221     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14222                        DAG.getConstant(SSECC, dl, MVT::i8));
14223   }
14224
14225   MVT VTOp0 = Op0.getSimpleValueType();
14226   assert(VTOp0 == Op1.getSimpleValueType() &&
14227          "Expected operands with same type!");
14228   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14229          "Invalid number of packed elements for source and destination!");
14230
14231   if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14232     // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14233     // legalizer to a wider vector type.  In the case of 'vsetcc' nodes, the
14234     // legalizer firstly checks if the first operand in input to the setcc has
14235     // a legal type. If so, then it promotes the return type to that same type.
14236     // Otherwise, the return type is promoted to the 'next legal type' which,
14237     // for a vector of MVT::i1 is always a 128-bit integer vector type.
14238     //
14239     // We reach this code only if the following two conditions are met:
14240     // 1. Both return type and operand type have been promoted to wider types
14241     //    by the type legalizer.
14242     // 2. The original operand type has been promoted to a 256-bit vector.
14243     //
14244     // Note that condition 2. only applies for AVX targets.
14245     SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14246     return DAG.getZExtOrTrunc(NewOp, dl, VT);
14247   }
14248
14249   // The non-AVX512 code below works under the assumption that source and
14250   // destination types are the same.
14251   assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14252          "Value types for source and destination must be the same!");
14253
14254   // Break 256-bit integer vector compare into smaller ones.
14255   if (VT.is256BitVector() && !Subtarget->hasInt256())
14256     return Lower256IntVSETCC(Op, DAG);
14257
14258   EVT OpVT = Op1.getValueType();
14259   if (OpVT.getVectorElementType() == MVT::i1)
14260     return LowerBoolVSETCC_AVX512(Op, DAG);
14261
14262   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14263   if (Subtarget->hasAVX512()) {
14264     if (Op1.getValueType().is512BitVector() ||
14265         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14266         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14267       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14268
14269     // In AVX-512 architecture setcc returns mask with i1 elements,
14270     // But there is no compare instruction for i8 and i16 elements in KNL.
14271     // We are not talking about 512-bit operands in this case, these
14272     // types are illegal.
14273     if (MaskResult &&
14274         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14275          OpVT.getVectorElementType().getSizeInBits() >= 8))
14276       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14277                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14278   }
14279
14280   // Lower using XOP integer comparisons.
14281   if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14282        VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14283     // Translate compare code to XOP PCOM compare mode.
14284     unsigned CmpMode = 0;
14285     switch (SetCCOpcode) {
14286     default: llvm_unreachable("Unexpected SETCC condition");
14287     case ISD::SETULT:
14288     case ISD::SETLT: CmpMode = 0x00; break;
14289     case ISD::SETULE:
14290     case ISD::SETLE: CmpMode = 0x01; break;
14291     case ISD::SETUGT:
14292     case ISD::SETGT: CmpMode = 0x02; break;
14293     case ISD::SETUGE:
14294     case ISD::SETGE: CmpMode = 0x03; break;
14295     case ISD::SETEQ: CmpMode = 0x04; break;
14296     case ISD::SETNE: CmpMode = 0x05; break;
14297     }
14298
14299     // Are we comparing unsigned or signed integers?
14300     unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14301       ? X86ISD::VPCOMU : X86ISD::VPCOM;
14302
14303     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14304                        DAG.getConstant(CmpMode, dl, MVT::i8));
14305   }
14306
14307   // We are handling one of the integer comparisons here.  Since SSE only has
14308   // GT and EQ comparisons for integer, swapping operands and multiple
14309   // operations may be required for some comparisons.
14310   unsigned Opc;
14311   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14312   bool Subus = false;
14313
14314   switch (SetCCOpcode) {
14315   default: llvm_unreachable("Unexpected SETCC condition");
14316   case ISD::SETNE:  Invert = true;
14317   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14318   case ISD::SETLT:  Swap = true;
14319   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14320   case ISD::SETGE:  Swap = true;
14321   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14322                     Invert = true; break;
14323   case ISD::SETULT: Swap = true;
14324   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14325                     FlipSigns = true; break;
14326   case ISD::SETUGE: Swap = true;
14327   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14328                     FlipSigns = true; Invert = true; break;
14329   }
14330
14331   // Special case: Use min/max operations for SETULE/SETUGE
14332   MVT VET = VT.getVectorElementType();
14333   bool hasMinMax =
14334        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14335     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14336
14337   if (hasMinMax) {
14338     switch (SetCCOpcode) {
14339     default: break;
14340     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14341     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14342     }
14343
14344     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14345   }
14346
14347   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14348   if (!MinMax && hasSubus) {
14349     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14350     // Op0 u<= Op1:
14351     //   t = psubus Op0, Op1
14352     //   pcmpeq t, <0..0>
14353     switch (SetCCOpcode) {
14354     default: break;
14355     case ISD::SETULT: {
14356       // If the comparison is against a constant we can turn this into a
14357       // setule.  With psubus, setule does not require a swap.  This is
14358       // beneficial because the constant in the register is no longer
14359       // destructed as the destination so it can be hoisted out of a loop.
14360       // Only do this pre-AVX since vpcmp* is no longer destructive.
14361       if (Subtarget->hasAVX())
14362         break;
14363       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14364       if (ULEOp1.getNode()) {
14365         Op1 = ULEOp1;
14366         Subus = true; Invert = false; Swap = false;
14367       }
14368       break;
14369     }
14370     // Psubus is better than flip-sign because it requires no inversion.
14371     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14372     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14373     }
14374
14375     if (Subus) {
14376       Opc = X86ISD::SUBUS;
14377       FlipSigns = false;
14378     }
14379   }
14380
14381   if (Swap)
14382     std::swap(Op0, Op1);
14383
14384   // Check that the operation in question is available (most are plain SSE2,
14385   // but PCMPGTQ and PCMPEQQ have different requirements).
14386   if (VT == MVT::v2i64) {
14387     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14388       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14389
14390       // First cast everything to the right type.
14391       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14392       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14393
14394       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14395       // bits of the inputs before performing those operations. The lower
14396       // compare is always unsigned.
14397       SDValue SB;
14398       if (FlipSigns) {
14399         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14400       } else {
14401         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14402         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14403         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14404                          Sign, Zero, Sign, Zero);
14405       }
14406       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14407       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14408
14409       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14410       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14411       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14412
14413       // Create masks for only the low parts/high parts of the 64 bit integers.
14414       static const int MaskHi[] = { 1, 1, 3, 3 };
14415       static const int MaskLo[] = { 0, 0, 2, 2 };
14416       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14417       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14418       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14419
14420       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14421       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14422
14423       if (Invert)
14424         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14425
14426       return DAG.getBitcast(VT, Result);
14427     }
14428
14429     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14430       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14431       // pcmpeqd + pshufd + pand.
14432       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14433
14434       // First cast everything to the right type.
14435       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14436       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14437
14438       // Do the compare.
14439       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14440
14441       // Make sure the lower and upper halves are both all-ones.
14442       static const int Mask[] = { 1, 0, 3, 2 };
14443       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14444       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14445
14446       if (Invert)
14447         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14448
14449       return DAG.getBitcast(VT, Result);
14450     }
14451   }
14452
14453   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14454   // bits of the inputs before performing those operations.
14455   if (FlipSigns) {
14456     EVT EltVT = VT.getVectorElementType();
14457     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14458                                  VT);
14459     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14460     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14461   }
14462
14463   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14464
14465   // If the logical-not of the result is required, perform that now.
14466   if (Invert)
14467     Result = DAG.getNOT(dl, Result, VT);
14468
14469   if (MinMax)
14470     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14471
14472   if (Subus)
14473     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14474                          getZeroVector(VT, Subtarget, DAG, dl));
14475
14476   return Result;
14477 }
14478
14479 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14480
14481   MVT VT = Op.getSimpleValueType();
14482
14483   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14484
14485   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14486          && "SetCC type must be 8-bit or 1-bit integer");
14487   SDValue Op0 = Op.getOperand(0);
14488   SDValue Op1 = Op.getOperand(1);
14489   SDLoc dl(Op);
14490   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14491
14492   // Optimize to BT if possible.
14493   // Lower (X & (1 << N)) == 0 to BT(X, N).
14494   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14495   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14496   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14497       Op1.getOpcode() == ISD::Constant &&
14498       cast<ConstantSDNode>(Op1)->isNullValue() &&
14499       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14500     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14501     if (NewSetCC.getNode()) {
14502       if (VT == MVT::i1)
14503         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14504       return NewSetCC;
14505     }
14506   }
14507
14508   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14509   // these.
14510   if (Op1.getOpcode() == ISD::Constant &&
14511       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14512        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14513       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14514
14515     // If the input is a setcc, then reuse the input setcc or use a new one with
14516     // the inverted condition.
14517     if (Op0.getOpcode() == X86ISD::SETCC) {
14518       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14519       bool Invert = (CC == ISD::SETNE) ^
14520         cast<ConstantSDNode>(Op1)->isNullValue();
14521       if (!Invert)
14522         return Op0;
14523
14524       CCode = X86::GetOppositeBranchCondition(CCode);
14525       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14526                                   DAG.getConstant(CCode, dl, MVT::i8),
14527                                   Op0.getOperand(1));
14528       if (VT == MVT::i1)
14529         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14530       return SetCC;
14531     }
14532   }
14533   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14534       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14535       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14536
14537     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14538     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14539   }
14540
14541   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14542   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14543   if (X86CC == X86::COND_INVALID)
14544     return SDValue();
14545
14546   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14547   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14548   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14549                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14550   if (VT == MVT::i1)
14551     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14552   return SetCC;
14553 }
14554
14555 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14556 static bool isX86LogicalCmp(SDValue Op) {
14557   unsigned Opc = Op.getNode()->getOpcode();
14558   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14559       Opc == X86ISD::SAHF)
14560     return true;
14561   if (Op.getResNo() == 1 &&
14562       (Opc == X86ISD::ADD ||
14563        Opc == X86ISD::SUB ||
14564        Opc == X86ISD::ADC ||
14565        Opc == X86ISD::SBB ||
14566        Opc == X86ISD::SMUL ||
14567        Opc == X86ISD::UMUL ||
14568        Opc == X86ISD::INC ||
14569        Opc == X86ISD::DEC ||
14570        Opc == X86ISD::OR ||
14571        Opc == X86ISD::XOR ||
14572        Opc == X86ISD::AND))
14573     return true;
14574
14575   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14576     return true;
14577
14578   return false;
14579 }
14580
14581 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14582   if (V.getOpcode() != ISD::TRUNCATE)
14583     return false;
14584
14585   SDValue VOp0 = V.getOperand(0);
14586   unsigned InBits = VOp0.getValueSizeInBits();
14587   unsigned Bits = V.getValueSizeInBits();
14588   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14589 }
14590
14591 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14592   bool addTest = true;
14593   SDValue Cond  = Op.getOperand(0);
14594   SDValue Op1 = Op.getOperand(1);
14595   SDValue Op2 = Op.getOperand(2);
14596   SDLoc DL(Op);
14597   EVT VT = Op1.getValueType();
14598   SDValue CC;
14599
14600   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14601   // are available or VBLENDV if AVX is available.
14602   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14603   if (Cond.getOpcode() == ISD::SETCC &&
14604       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14605        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14606       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14607     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14608     int SSECC = translateX86FSETCC(
14609         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14610
14611     if (SSECC != 8) {
14612       if (Subtarget->hasAVX512()) {
14613         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14614                                   DAG.getConstant(SSECC, DL, MVT::i8));
14615         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14616       }
14617
14618       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14619                                 DAG.getConstant(SSECC, DL, MVT::i8));
14620
14621       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14622       // of 3 logic instructions for size savings and potentially speed.
14623       // Unfortunately, there is no scalar form of VBLENDV.
14624
14625       // If either operand is a constant, don't try this. We can expect to
14626       // optimize away at least one of the logic instructions later in that
14627       // case, so that sequence would be faster than a variable blend.
14628
14629       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14630       // uses XMM0 as the selection register. That may need just as many
14631       // instructions as the AND/ANDN/OR sequence due to register moves, so
14632       // don't bother.
14633
14634       if (Subtarget->hasAVX() &&
14635           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14636
14637         // Convert to vectors, do a VSELECT, and convert back to scalar.
14638         // All of the conversions should be optimized away.
14639
14640         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14641         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14642         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14643         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14644
14645         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14646         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14647
14648         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14649
14650         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14651                            VSel, DAG.getIntPtrConstant(0, DL));
14652       }
14653       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14654       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14655       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14656     }
14657   }
14658
14659   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14660     SDValue Op1Scalar;
14661     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14662       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14663     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14664       Op1Scalar = Op1.getOperand(0);
14665     SDValue Op2Scalar;
14666     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14667       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14668     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14669       Op2Scalar = Op2.getOperand(0);
14670     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14671       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14672                                       Op1Scalar.getValueType(),
14673                                       Cond, Op1Scalar, Op2Scalar);
14674       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14675         return DAG.getBitcast(VT, newSelect);
14676       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14677       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14678                          DAG.getIntPtrConstant(0, DL));
14679     }
14680   }
14681
14682   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14683     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14684     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14685                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14686     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14687                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14688     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14689                                     Cond, Op1, Op2);
14690     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14691   }
14692
14693   if (Cond.getOpcode() == ISD::SETCC) {
14694     SDValue NewCond = LowerSETCC(Cond, DAG);
14695     if (NewCond.getNode())
14696       Cond = NewCond;
14697   }
14698
14699   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14700   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14701   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14702   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14703   if (Cond.getOpcode() == X86ISD::SETCC &&
14704       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14705       isZero(Cond.getOperand(1).getOperand(1))) {
14706     SDValue Cmp = Cond.getOperand(1);
14707
14708     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14709
14710     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14711         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14712       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14713
14714       SDValue CmpOp0 = Cmp.getOperand(0);
14715       // Apply further optimizations for special cases
14716       // (select (x != 0), -1, 0) -> neg & sbb
14717       // (select (x == 0), 0, -1) -> neg & sbb
14718       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14719         if (YC->isNullValue() &&
14720             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14721           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14722           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14723                                     DAG.getConstant(0, DL,
14724                                                     CmpOp0.getValueType()),
14725                                     CmpOp0);
14726           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14727                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14728                                     SDValue(Neg.getNode(), 1));
14729           return Res;
14730         }
14731
14732       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14733                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14734       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14735
14736       SDValue Res =   // Res = 0 or -1.
14737         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14738                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14739
14740       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14741         Res = DAG.getNOT(DL, Res, Res.getValueType());
14742
14743       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14744       if (!N2C || !N2C->isNullValue())
14745         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14746       return Res;
14747     }
14748   }
14749
14750   // Look past (and (setcc_carry (cmp ...)), 1).
14751   if (Cond.getOpcode() == ISD::AND &&
14752       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14753     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14754     if (C && C->getAPIntValue() == 1)
14755       Cond = Cond.getOperand(0);
14756   }
14757
14758   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14759   // setting operand in place of the X86ISD::SETCC.
14760   unsigned CondOpcode = Cond.getOpcode();
14761   if (CondOpcode == X86ISD::SETCC ||
14762       CondOpcode == X86ISD::SETCC_CARRY) {
14763     CC = Cond.getOperand(0);
14764
14765     SDValue Cmp = Cond.getOperand(1);
14766     unsigned Opc = Cmp.getOpcode();
14767     MVT VT = Op.getSimpleValueType();
14768
14769     bool IllegalFPCMov = false;
14770     if (VT.isFloatingPoint() && !VT.isVector() &&
14771         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14772       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14773
14774     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14775         Opc == X86ISD::BT) { // FIXME
14776       Cond = Cmp;
14777       addTest = false;
14778     }
14779   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14780              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14781              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14782               Cond.getOperand(0).getValueType() != MVT::i8)) {
14783     SDValue LHS = Cond.getOperand(0);
14784     SDValue RHS = Cond.getOperand(1);
14785     unsigned X86Opcode;
14786     unsigned X86Cond;
14787     SDVTList VTs;
14788     switch (CondOpcode) {
14789     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14790     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14791     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14792     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14793     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14794     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14795     default: llvm_unreachable("unexpected overflowing operator");
14796     }
14797     if (CondOpcode == ISD::UMULO)
14798       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14799                           MVT::i32);
14800     else
14801       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14802
14803     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14804
14805     if (CondOpcode == ISD::UMULO)
14806       Cond = X86Op.getValue(2);
14807     else
14808       Cond = X86Op.getValue(1);
14809
14810     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14811     addTest = false;
14812   }
14813
14814   if (addTest) {
14815     // Look past the truncate if the high bits are known zero.
14816     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14817       Cond = Cond.getOperand(0);
14818
14819     // We know the result of AND is compared against zero. Try to match
14820     // it to BT.
14821     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14822       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14823       if (NewSetCC.getNode()) {
14824         CC = NewSetCC.getOperand(0);
14825         Cond = NewSetCC.getOperand(1);
14826         addTest = false;
14827       }
14828     }
14829   }
14830
14831   if (addTest) {
14832     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14833     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14834   }
14835
14836   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14837   // a <  b ?  0 : -1 -> RES = setcc_carry
14838   // a >= b ? -1 :  0 -> RES = setcc_carry
14839   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14840   if (Cond.getOpcode() == X86ISD::SUB) {
14841     Cond = ConvertCmpIfNecessary(Cond, DAG);
14842     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14843
14844     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14845         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14846       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14847                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14848                                 Cond);
14849       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14850         return DAG.getNOT(DL, Res, Res.getValueType());
14851       return Res;
14852     }
14853   }
14854
14855   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14856   // widen the cmov and push the truncate through. This avoids introducing a new
14857   // branch during isel and doesn't add any extensions.
14858   if (Op.getValueType() == MVT::i8 &&
14859       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14860     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14861     if (T1.getValueType() == T2.getValueType() &&
14862         // Blacklist CopyFromReg to avoid partial register stalls.
14863         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14864       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14865       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14866       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14867     }
14868   }
14869
14870   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14871   // condition is true.
14872   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14873   SDValue Ops[] = { Op2, Op1, CC, Cond };
14874   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14875 }
14876
14877 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14878                                        const X86Subtarget *Subtarget,
14879                                        SelectionDAG &DAG) {
14880   MVT VT = Op->getSimpleValueType(0);
14881   SDValue In = Op->getOperand(0);
14882   MVT InVT = In.getSimpleValueType();
14883   MVT VTElt = VT.getVectorElementType();
14884   MVT InVTElt = InVT.getVectorElementType();
14885   SDLoc dl(Op);
14886
14887   // SKX processor
14888   if ((InVTElt == MVT::i1) &&
14889       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14890         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14891
14892        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14893         VTElt.getSizeInBits() <= 16)) ||
14894
14895        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14896         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14897
14898        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14899         VTElt.getSizeInBits() >= 32))))
14900     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14901
14902   unsigned int NumElts = VT.getVectorNumElements();
14903
14904   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14905     return SDValue();
14906
14907   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14908     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14909       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14910     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14911   }
14912
14913   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14914   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14915   SDValue NegOne =
14916    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14917                    ExtVT);
14918   SDValue Zero =
14919    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14920
14921   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14922   if (VT.is512BitVector())
14923     return V;
14924   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14925 }
14926
14927 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14928                                              const X86Subtarget *Subtarget,
14929                                              SelectionDAG &DAG) {
14930   SDValue In = Op->getOperand(0);
14931   MVT VT = Op->getSimpleValueType(0);
14932   MVT InVT = In.getSimpleValueType();
14933   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14934
14935   MVT InSVT = InVT.getScalarType();
14936   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14937
14938   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14939     return SDValue();
14940   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14941     return SDValue();
14942
14943   SDLoc dl(Op);
14944
14945   // SSE41 targets can use the pmovsx* instructions directly.
14946   if (Subtarget->hasSSE41())
14947     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14948
14949   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14950   SDValue Curr = In;
14951   MVT CurrVT = InVT;
14952
14953   // As SRAI is only available on i16/i32 types, we expand only up to i32
14954   // and handle i64 separately.
14955   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14956     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14957     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14958     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14959     Curr = DAG.getBitcast(CurrVT, Curr);
14960   }
14961
14962   SDValue SignExt = Curr;
14963   if (CurrVT != InVT) {
14964     unsigned SignExtShift =
14965         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14966     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14967                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14968   }
14969
14970   if (CurrVT == VT)
14971     return SignExt;
14972
14973   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14974     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14975                                DAG.getConstant(31, dl, MVT::i8));
14976     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14977     return DAG.getBitcast(VT, Ext);
14978   }
14979
14980   return SDValue();
14981 }
14982
14983 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14984                                 SelectionDAG &DAG) {
14985   MVT VT = Op->getSimpleValueType(0);
14986   SDValue In = Op->getOperand(0);
14987   MVT InVT = In.getSimpleValueType();
14988   SDLoc dl(Op);
14989
14990   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14991     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14992
14993   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14994       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14995       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14996     return SDValue();
14997
14998   if (Subtarget->hasInt256())
14999     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15000
15001   // Optimize vectors in AVX mode
15002   // Sign extend  v8i16 to v8i32 and
15003   //              v4i32 to v4i64
15004   //
15005   // Divide input vector into two parts
15006   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15007   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15008   // concat the vectors to original VT
15009
15010   unsigned NumElems = InVT.getVectorNumElements();
15011   SDValue Undef = DAG.getUNDEF(InVT);
15012
15013   SmallVector<int,8> ShufMask1(NumElems, -1);
15014   for (unsigned i = 0; i != NumElems/2; ++i)
15015     ShufMask1[i] = i;
15016
15017   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15018
15019   SmallVector<int,8> ShufMask2(NumElems, -1);
15020   for (unsigned i = 0; i != NumElems/2; ++i)
15021     ShufMask2[i] = i + NumElems/2;
15022
15023   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15024
15025   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
15026                                 VT.getVectorNumElements()/2);
15027
15028   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15029   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15030
15031   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15032 }
15033
15034 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15035 // may emit an illegal shuffle but the expansion is still better than scalar
15036 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15037 // we'll emit a shuffle and a arithmetic shift.
15038 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15039 // TODO: It is possible to support ZExt by zeroing the undef values during
15040 // the shuffle phase or after the shuffle.
15041 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15042                                  SelectionDAG &DAG) {
15043   MVT RegVT = Op.getSimpleValueType();
15044   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15045   assert(RegVT.isInteger() &&
15046          "We only custom lower integer vector sext loads.");
15047
15048   // Nothing useful we can do without SSE2 shuffles.
15049   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15050
15051   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15052   SDLoc dl(Ld);
15053   EVT MemVT = Ld->getMemoryVT();
15054   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15055   unsigned RegSz = RegVT.getSizeInBits();
15056
15057   ISD::LoadExtType Ext = Ld->getExtensionType();
15058
15059   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15060          && "Only anyext and sext are currently implemented.");
15061   assert(MemVT != RegVT && "Cannot extend to the same type");
15062   assert(MemVT.isVector() && "Must load a vector from memory");
15063
15064   unsigned NumElems = RegVT.getVectorNumElements();
15065   unsigned MemSz = MemVT.getSizeInBits();
15066   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15067
15068   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15069     // The only way in which we have a legal 256-bit vector result but not the
15070     // integer 256-bit operations needed to directly lower a sextload is if we
15071     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15072     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15073     // correctly legalized. We do this late to allow the canonical form of
15074     // sextload to persist throughout the rest of the DAG combiner -- it wants
15075     // to fold together any extensions it can, and so will fuse a sign_extend
15076     // of an sextload into a sextload targeting a wider value.
15077     SDValue Load;
15078     if (MemSz == 128) {
15079       // Just switch this to a normal load.
15080       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15081                                        "it must be a legal 128-bit vector "
15082                                        "type!");
15083       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15084                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15085                   Ld->isInvariant(), Ld->getAlignment());
15086     } else {
15087       assert(MemSz < 128 &&
15088              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15089       // Do an sext load to a 128-bit vector type. We want to use the same
15090       // number of elements, but elements half as wide. This will end up being
15091       // recursively lowered by this routine, but will succeed as we definitely
15092       // have all the necessary features if we're using AVX1.
15093       EVT HalfEltVT =
15094           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15095       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15096       Load =
15097           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15098                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15099                          Ld->isNonTemporal(), Ld->isInvariant(),
15100                          Ld->getAlignment());
15101     }
15102
15103     // Replace chain users with the new chain.
15104     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15105     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15106
15107     // Finally, do a normal sign-extend to the desired register.
15108     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15109   }
15110
15111   // All sizes must be a power of two.
15112   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15113          "Non-power-of-two elements are not custom lowered!");
15114
15115   // Attempt to load the original value using scalar loads.
15116   // Find the largest scalar type that divides the total loaded size.
15117   MVT SclrLoadTy = MVT::i8;
15118   for (MVT Tp : MVT::integer_valuetypes()) {
15119     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15120       SclrLoadTy = Tp;
15121     }
15122   }
15123
15124   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15125   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15126       (64 <= MemSz))
15127     SclrLoadTy = MVT::f64;
15128
15129   // Calculate the number of scalar loads that we need to perform
15130   // in order to load our vector from memory.
15131   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15132
15133   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15134          "Can only lower sext loads with a single scalar load!");
15135
15136   unsigned loadRegZize = RegSz;
15137   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15138     loadRegZize = 128;
15139
15140   // Represent our vector as a sequence of elements which are the
15141   // largest scalar that we can load.
15142   EVT LoadUnitVecVT = EVT::getVectorVT(
15143       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15144
15145   // Represent the data using the same element type that is stored in
15146   // memory. In practice, we ''widen'' MemVT.
15147   EVT WideVecVT =
15148       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15149                        loadRegZize / MemVT.getScalarType().getSizeInBits());
15150
15151   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15152          "Invalid vector type");
15153
15154   // We can't shuffle using an illegal type.
15155   assert(TLI.isTypeLegal(WideVecVT) &&
15156          "We only lower types that form legal widened vector types");
15157
15158   SmallVector<SDValue, 8> Chains;
15159   SDValue Ptr = Ld->getBasePtr();
15160   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15161                                       TLI.getPointerTy(DAG.getDataLayout()));
15162   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15163
15164   for (unsigned i = 0; i < NumLoads; ++i) {
15165     // Perform a single load.
15166     SDValue ScalarLoad =
15167         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15168                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15169                     Ld->getAlignment());
15170     Chains.push_back(ScalarLoad.getValue(1));
15171     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15172     // another round of DAGCombining.
15173     if (i == 0)
15174       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15175     else
15176       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15177                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
15178
15179     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15180   }
15181
15182   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15183
15184   // Bitcast the loaded value to a vector of the original element type, in
15185   // the size of the target vector type.
15186   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15187   unsigned SizeRatio = RegSz / MemSz;
15188
15189   if (Ext == ISD::SEXTLOAD) {
15190     // If we have SSE4.1, we can directly emit a VSEXT node.
15191     if (Subtarget->hasSSE41()) {
15192       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15193       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15194       return Sext;
15195     }
15196
15197     // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15198     // lanes.
15199     assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15200            "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15201
15202     SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15203     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15204     return Shuff;
15205   }
15206
15207   // Redistribute the loaded elements into the different locations.
15208   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15209   for (unsigned i = 0; i != NumElems; ++i)
15210     ShuffleVec[i * SizeRatio] = i;
15211
15212   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15213                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15214
15215   // Bitcast to the requested type.
15216   Shuff = DAG.getBitcast(RegVT, Shuff);
15217   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15218   return Shuff;
15219 }
15220
15221 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15222 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15223 // from the AND / OR.
15224 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15225   Opc = Op.getOpcode();
15226   if (Opc != ISD::OR && Opc != ISD::AND)
15227     return false;
15228   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15229           Op.getOperand(0).hasOneUse() &&
15230           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15231           Op.getOperand(1).hasOneUse());
15232 }
15233
15234 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15235 // 1 and that the SETCC node has a single use.
15236 static bool isXor1OfSetCC(SDValue Op) {
15237   if (Op.getOpcode() != ISD::XOR)
15238     return false;
15239   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15240   if (N1C && N1C->getAPIntValue() == 1) {
15241     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15242       Op.getOperand(0).hasOneUse();
15243   }
15244   return false;
15245 }
15246
15247 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15248   bool addTest = true;
15249   SDValue Chain = Op.getOperand(0);
15250   SDValue Cond  = Op.getOperand(1);
15251   SDValue Dest  = Op.getOperand(2);
15252   SDLoc dl(Op);
15253   SDValue CC;
15254   bool Inverted = false;
15255
15256   if (Cond.getOpcode() == ISD::SETCC) {
15257     // Check for setcc([su]{add,sub,mul}o == 0).
15258     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15259         isa<ConstantSDNode>(Cond.getOperand(1)) &&
15260         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
15261         Cond.getOperand(0).getResNo() == 1 &&
15262         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15263          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15264          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15265          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15266          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15267          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15268       Inverted = true;
15269       Cond = Cond.getOperand(0);
15270     } else {
15271       SDValue NewCond = LowerSETCC(Cond, DAG);
15272       if (NewCond.getNode())
15273         Cond = NewCond;
15274     }
15275   }
15276 #if 0
15277   // FIXME: LowerXALUO doesn't handle these!!
15278   else if (Cond.getOpcode() == X86ISD::ADD  ||
15279            Cond.getOpcode() == X86ISD::SUB  ||
15280            Cond.getOpcode() == X86ISD::SMUL ||
15281            Cond.getOpcode() == X86ISD::UMUL)
15282     Cond = LowerXALUO(Cond, DAG);
15283 #endif
15284
15285   // Look pass (and (setcc_carry (cmp ...)), 1).
15286   if (Cond.getOpcode() == ISD::AND &&
15287       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15288     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15289     if (C && C->getAPIntValue() == 1)
15290       Cond = Cond.getOperand(0);
15291   }
15292
15293   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15294   // setting operand in place of the X86ISD::SETCC.
15295   unsigned CondOpcode = Cond.getOpcode();
15296   if (CondOpcode == X86ISD::SETCC ||
15297       CondOpcode == X86ISD::SETCC_CARRY) {
15298     CC = Cond.getOperand(0);
15299
15300     SDValue Cmp = Cond.getOperand(1);
15301     unsigned Opc = Cmp.getOpcode();
15302     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15303     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15304       Cond = Cmp;
15305       addTest = false;
15306     } else {
15307       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15308       default: break;
15309       case X86::COND_O:
15310       case X86::COND_B:
15311         // These can only come from an arithmetic instruction with overflow,
15312         // e.g. SADDO, UADDO.
15313         Cond = Cond.getNode()->getOperand(1);
15314         addTest = false;
15315         break;
15316       }
15317     }
15318   }
15319   CondOpcode = Cond.getOpcode();
15320   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15321       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15322       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15323        Cond.getOperand(0).getValueType() != MVT::i8)) {
15324     SDValue LHS = Cond.getOperand(0);
15325     SDValue RHS = Cond.getOperand(1);
15326     unsigned X86Opcode;
15327     unsigned X86Cond;
15328     SDVTList VTs;
15329     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15330     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15331     // X86ISD::INC).
15332     switch (CondOpcode) {
15333     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15334     case ISD::SADDO:
15335       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15336         if (C->isOne()) {
15337           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15338           break;
15339         }
15340       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15341     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15342     case ISD::SSUBO:
15343       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15344         if (C->isOne()) {
15345           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15346           break;
15347         }
15348       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15349     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15350     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15351     default: llvm_unreachable("unexpected overflowing operator");
15352     }
15353     if (Inverted)
15354       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15355     if (CondOpcode == ISD::UMULO)
15356       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15357                           MVT::i32);
15358     else
15359       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15360
15361     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15362
15363     if (CondOpcode == ISD::UMULO)
15364       Cond = X86Op.getValue(2);
15365     else
15366       Cond = X86Op.getValue(1);
15367
15368     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15369     addTest = false;
15370   } else {
15371     unsigned CondOpc;
15372     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15373       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15374       if (CondOpc == ISD::OR) {
15375         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15376         // two branches instead of an explicit OR instruction with a
15377         // separate test.
15378         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15379             isX86LogicalCmp(Cmp)) {
15380           CC = Cond.getOperand(0).getOperand(0);
15381           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15382                               Chain, Dest, CC, Cmp);
15383           CC = Cond.getOperand(1).getOperand(0);
15384           Cond = Cmp;
15385           addTest = false;
15386         }
15387       } else { // ISD::AND
15388         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15389         // two branches instead of an explicit AND instruction with a
15390         // separate test. However, we only do this if this block doesn't
15391         // have a fall-through edge, because this requires an explicit
15392         // jmp when the condition is false.
15393         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15394             isX86LogicalCmp(Cmp) &&
15395             Op.getNode()->hasOneUse()) {
15396           X86::CondCode CCode =
15397             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15398           CCode = X86::GetOppositeBranchCondition(CCode);
15399           CC = DAG.getConstant(CCode, dl, MVT::i8);
15400           SDNode *User = *Op.getNode()->use_begin();
15401           // Look for an unconditional branch following this conditional branch.
15402           // We need this because we need to reverse the successors in order
15403           // to implement FCMP_OEQ.
15404           if (User->getOpcode() == ISD::BR) {
15405             SDValue FalseBB = User->getOperand(1);
15406             SDNode *NewBR =
15407               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15408             assert(NewBR == User);
15409             (void)NewBR;
15410             Dest = FalseBB;
15411
15412             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15413                                 Chain, Dest, CC, Cmp);
15414             X86::CondCode CCode =
15415               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15416             CCode = X86::GetOppositeBranchCondition(CCode);
15417             CC = DAG.getConstant(CCode, dl, MVT::i8);
15418             Cond = Cmp;
15419             addTest = false;
15420           }
15421         }
15422       }
15423     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15424       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15425       // It should be transformed during dag combiner except when the condition
15426       // is set by a arithmetics with overflow node.
15427       X86::CondCode CCode =
15428         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15429       CCode = X86::GetOppositeBranchCondition(CCode);
15430       CC = DAG.getConstant(CCode, dl, MVT::i8);
15431       Cond = Cond.getOperand(0).getOperand(1);
15432       addTest = false;
15433     } else if (Cond.getOpcode() == ISD::SETCC &&
15434                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15435       // For FCMP_OEQ, we can emit
15436       // two branches instead of an explicit AND instruction with a
15437       // separate test. However, we only do this if this block doesn't
15438       // have a fall-through edge, because this requires an explicit
15439       // jmp when the condition is false.
15440       if (Op.getNode()->hasOneUse()) {
15441         SDNode *User = *Op.getNode()->use_begin();
15442         // Look for an unconditional branch following this conditional branch.
15443         // We need this because we need to reverse the successors in order
15444         // to implement FCMP_OEQ.
15445         if (User->getOpcode() == ISD::BR) {
15446           SDValue FalseBB = User->getOperand(1);
15447           SDNode *NewBR =
15448             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15449           assert(NewBR == User);
15450           (void)NewBR;
15451           Dest = FalseBB;
15452
15453           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15454                                     Cond.getOperand(0), Cond.getOperand(1));
15455           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15456           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15457           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15458                               Chain, Dest, CC, Cmp);
15459           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15460           Cond = Cmp;
15461           addTest = false;
15462         }
15463       }
15464     } else if (Cond.getOpcode() == ISD::SETCC &&
15465                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15466       // For FCMP_UNE, we can emit
15467       // two branches instead of an explicit AND instruction with a
15468       // separate test. However, we only do this if this block doesn't
15469       // have a fall-through edge, because this requires an explicit
15470       // jmp when the condition is false.
15471       if (Op.getNode()->hasOneUse()) {
15472         SDNode *User = *Op.getNode()->use_begin();
15473         // Look for an unconditional branch following this conditional branch.
15474         // We need this because we need to reverse the successors in order
15475         // to implement FCMP_UNE.
15476         if (User->getOpcode() == ISD::BR) {
15477           SDValue FalseBB = User->getOperand(1);
15478           SDNode *NewBR =
15479             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15480           assert(NewBR == User);
15481           (void)NewBR;
15482
15483           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15484                                     Cond.getOperand(0), Cond.getOperand(1));
15485           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15486           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15487           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15488                               Chain, Dest, CC, Cmp);
15489           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15490           Cond = Cmp;
15491           addTest = false;
15492           Dest = FalseBB;
15493         }
15494       }
15495     }
15496   }
15497
15498   if (addTest) {
15499     // Look pass the truncate if the high bits are known zero.
15500     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15501         Cond = Cond.getOperand(0);
15502
15503     // We know the result of AND is compared against zero. Try to match
15504     // it to BT.
15505     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15506       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15507       if (NewSetCC.getNode()) {
15508         CC = NewSetCC.getOperand(0);
15509         Cond = NewSetCC.getOperand(1);
15510         addTest = false;
15511       }
15512     }
15513   }
15514
15515   if (addTest) {
15516     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15517     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15518     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15519   }
15520   Cond = ConvertCmpIfNecessary(Cond, DAG);
15521   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15522                      Chain, Dest, CC, Cond);
15523 }
15524
15525 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15526 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15527 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15528 // that the guard pages used by the OS virtual memory manager are allocated in
15529 // correct sequence.
15530 SDValue
15531 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15532                                            SelectionDAG &DAG) const {
15533   MachineFunction &MF = DAG.getMachineFunction();
15534   bool SplitStack = MF.shouldSplitStack();
15535   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15536                SplitStack;
15537   SDLoc dl(Op);
15538
15539   if (!Lower) {
15540     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15541     SDNode* Node = Op.getNode();
15542
15543     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15544     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15545         " not tell us which reg is the stack pointer!");
15546     EVT VT = Node->getValueType(0);
15547     SDValue Tmp1 = SDValue(Node, 0);
15548     SDValue Tmp2 = SDValue(Node, 1);
15549     SDValue Tmp3 = Node->getOperand(2);
15550     SDValue Chain = Tmp1.getOperand(0);
15551
15552     // Chain the dynamic stack allocation so that it doesn't modify the stack
15553     // pointer when other instructions are using the stack.
15554     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15555         SDLoc(Node));
15556
15557     SDValue Size = Tmp2.getOperand(1);
15558     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15559     Chain = SP.getValue(1);
15560     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15561     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15562     unsigned StackAlign = TFI.getStackAlignment();
15563     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15564     if (Align > StackAlign)
15565       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15566           DAG.getConstant(-(uint64_t)Align, dl, VT));
15567     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15568
15569     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15570         DAG.getIntPtrConstant(0, dl, true), SDValue(),
15571         SDLoc(Node));
15572
15573     SDValue Ops[2] = { Tmp1, Tmp2 };
15574     return DAG.getMergeValues(Ops, dl);
15575   }
15576
15577   // Get the inputs.
15578   SDValue Chain = Op.getOperand(0);
15579   SDValue Size  = Op.getOperand(1);
15580   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15581   EVT VT = Op.getNode()->getValueType(0);
15582
15583   bool Is64Bit = Subtarget->is64Bit();
15584   MVT SPTy = getPointerTy(DAG.getDataLayout());
15585
15586   if (SplitStack) {
15587     MachineRegisterInfo &MRI = MF.getRegInfo();
15588
15589     if (Is64Bit) {
15590       // The 64 bit implementation of segmented stacks needs to clobber both r10
15591       // r11. This makes it impossible to use it along with nested parameters.
15592       const Function *F = MF.getFunction();
15593
15594       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15595            I != E; ++I)
15596         if (I->hasNestAttr())
15597           report_fatal_error("Cannot use segmented stacks with functions that "
15598                              "have nested arguments.");
15599     }
15600
15601     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15602     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15603     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15604     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15605                                 DAG.getRegister(Vreg, SPTy));
15606     SDValue Ops1[2] = { Value, Chain };
15607     return DAG.getMergeValues(Ops1, dl);
15608   } else {
15609     SDValue Flag;
15610     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15611
15612     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15613     Flag = Chain.getValue(1);
15614     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15615
15616     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15617
15618     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15619     unsigned SPReg = RegInfo->getStackRegister();
15620     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15621     Chain = SP.getValue(1);
15622
15623     if (Align) {
15624       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15625                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15626       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15627     }
15628
15629     SDValue Ops1[2] = { SP, Chain };
15630     return DAG.getMergeValues(Ops1, dl);
15631   }
15632 }
15633
15634 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15635   MachineFunction &MF = DAG.getMachineFunction();
15636   auto PtrVT = getPointerTy(MF.getDataLayout());
15637   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15638
15639   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15640   SDLoc DL(Op);
15641
15642   if (!Subtarget->is64Bit() ||
15643       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15644     // vastart just stores the address of the VarArgsFrameIndex slot into the
15645     // memory location argument.
15646     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15647     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15648                         MachinePointerInfo(SV), false, false, 0);
15649   }
15650
15651   // __va_list_tag:
15652   //   gp_offset         (0 - 6 * 8)
15653   //   fp_offset         (48 - 48 + 8 * 16)
15654   //   overflow_arg_area (point to parameters coming in memory).
15655   //   reg_save_area
15656   SmallVector<SDValue, 8> MemOps;
15657   SDValue FIN = Op.getOperand(1);
15658   // Store gp_offset
15659   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15660                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15661                                                DL, MVT::i32),
15662                                FIN, MachinePointerInfo(SV), false, false, 0);
15663   MemOps.push_back(Store);
15664
15665   // Store fp_offset
15666   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15667   Store = DAG.getStore(Op.getOperand(0), DL,
15668                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15669                                        MVT::i32),
15670                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15671   MemOps.push_back(Store);
15672
15673   // Store ptr to overflow_arg_area
15674   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15675   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15676   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15677                        MachinePointerInfo(SV, 8),
15678                        false, false, 0);
15679   MemOps.push_back(Store);
15680
15681   // Store ptr to reg_save_area.
15682   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15683       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15684   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15685   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15686       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15687   MemOps.push_back(Store);
15688   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15689 }
15690
15691 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15692   assert(Subtarget->is64Bit() &&
15693          "LowerVAARG only handles 64-bit va_arg!");
15694   assert(Op.getNode()->getNumOperands() == 4);
15695
15696   MachineFunction &MF = DAG.getMachineFunction();
15697   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15698     // The Win64 ABI uses char* instead of a structure.
15699     return DAG.expandVAArg(Op.getNode());
15700
15701   SDValue Chain = Op.getOperand(0);
15702   SDValue SrcPtr = Op.getOperand(1);
15703   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15704   unsigned Align = Op.getConstantOperandVal(3);
15705   SDLoc dl(Op);
15706
15707   EVT ArgVT = Op.getNode()->getValueType(0);
15708   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15709   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15710   uint8_t ArgMode;
15711
15712   // Decide which area this value should be read from.
15713   // TODO: Implement the AMD64 ABI in its entirety. This simple
15714   // selection mechanism works only for the basic types.
15715   if (ArgVT == MVT::f80) {
15716     llvm_unreachable("va_arg for f80 not yet implemented");
15717   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15718     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15719   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15720     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15721   } else {
15722     llvm_unreachable("Unhandled argument type in LowerVAARG");
15723   }
15724
15725   if (ArgMode == 2) {
15726     // Sanity Check: Make sure using fp_offset makes sense.
15727     assert(!Subtarget->useSoftFloat() &&
15728            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15729            Subtarget->hasSSE1());
15730   }
15731
15732   // Insert VAARG_64 node into the DAG
15733   // VAARG_64 returns two values: Variable Argument Address, Chain
15734   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15735                        DAG.getConstant(ArgMode, dl, MVT::i8),
15736                        DAG.getConstant(Align, dl, MVT::i32)};
15737   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15738   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15739                                           VTs, InstOps, MVT::i64,
15740                                           MachinePointerInfo(SV),
15741                                           /*Align=*/0,
15742                                           /*Volatile=*/false,
15743                                           /*ReadMem=*/true,
15744                                           /*WriteMem=*/true);
15745   Chain = VAARG.getValue(1);
15746
15747   // Load the next argument and return it
15748   return DAG.getLoad(ArgVT, dl,
15749                      Chain,
15750                      VAARG,
15751                      MachinePointerInfo(),
15752                      false, false, false, 0);
15753 }
15754
15755 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15756                            SelectionDAG &DAG) {
15757   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15758   // where a va_list is still an i8*.
15759   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15760   if (Subtarget->isCallingConvWin64(
15761         DAG.getMachineFunction().getFunction()->getCallingConv()))
15762     // Probably a Win64 va_copy.
15763     return DAG.expandVACopy(Op.getNode());
15764
15765   SDValue Chain = Op.getOperand(0);
15766   SDValue DstPtr = Op.getOperand(1);
15767   SDValue SrcPtr = Op.getOperand(2);
15768   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15769   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15770   SDLoc DL(Op);
15771
15772   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15773                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15774                        false, false,
15775                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15776 }
15777
15778 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15779 // amount is a constant. Takes immediate version of shift as input.
15780 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15781                                           SDValue SrcOp, uint64_t ShiftAmt,
15782                                           SelectionDAG &DAG) {
15783   MVT ElementType = VT.getVectorElementType();
15784
15785   // Fold this packed shift into its first operand if ShiftAmt is 0.
15786   if (ShiftAmt == 0)
15787     return SrcOp;
15788
15789   // Check for ShiftAmt >= element width
15790   if (ShiftAmt >= ElementType.getSizeInBits()) {
15791     if (Opc == X86ISD::VSRAI)
15792       ShiftAmt = ElementType.getSizeInBits() - 1;
15793     else
15794       return DAG.getConstant(0, dl, VT);
15795   }
15796
15797   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15798          && "Unknown target vector shift-by-constant node");
15799
15800   // Fold this packed vector shift into a build vector if SrcOp is a
15801   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15802   if (VT == SrcOp.getSimpleValueType() &&
15803       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15804     SmallVector<SDValue, 8> Elts;
15805     unsigned NumElts = SrcOp->getNumOperands();
15806     ConstantSDNode *ND;
15807
15808     switch(Opc) {
15809     default: llvm_unreachable(nullptr);
15810     case X86ISD::VSHLI:
15811       for (unsigned i=0; i!=NumElts; ++i) {
15812         SDValue CurrentOp = SrcOp->getOperand(i);
15813         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15814           Elts.push_back(CurrentOp);
15815           continue;
15816         }
15817         ND = cast<ConstantSDNode>(CurrentOp);
15818         const APInt &C = ND->getAPIntValue();
15819         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15820       }
15821       break;
15822     case X86ISD::VSRLI:
15823       for (unsigned i=0; i!=NumElts; ++i) {
15824         SDValue CurrentOp = SrcOp->getOperand(i);
15825         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15826           Elts.push_back(CurrentOp);
15827           continue;
15828         }
15829         ND = cast<ConstantSDNode>(CurrentOp);
15830         const APInt &C = ND->getAPIntValue();
15831         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15832       }
15833       break;
15834     case X86ISD::VSRAI:
15835       for (unsigned i=0; i!=NumElts; ++i) {
15836         SDValue CurrentOp = SrcOp->getOperand(i);
15837         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15838           Elts.push_back(CurrentOp);
15839           continue;
15840         }
15841         ND = cast<ConstantSDNode>(CurrentOp);
15842         const APInt &C = ND->getAPIntValue();
15843         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15844       }
15845       break;
15846     }
15847
15848     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15849   }
15850
15851   return DAG.getNode(Opc, dl, VT, SrcOp,
15852                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15853 }
15854
15855 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15856 // may or may not be a constant. Takes immediate version of shift as input.
15857 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15858                                    SDValue SrcOp, SDValue ShAmt,
15859                                    SelectionDAG &DAG) {
15860   MVT SVT = ShAmt.getSimpleValueType();
15861   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15862
15863   // Catch shift-by-constant.
15864   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15865     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15866                                       CShAmt->getZExtValue(), DAG);
15867
15868   // Change opcode to non-immediate version
15869   switch (Opc) {
15870     default: llvm_unreachable("Unknown target vector shift node");
15871     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15872     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15873     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15874   }
15875
15876   const X86Subtarget &Subtarget =
15877       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15878   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15879       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15880     // Let the shuffle legalizer expand this shift amount node.
15881     SDValue Op0 = ShAmt.getOperand(0);
15882     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15883     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15884   } else {
15885     // Need to build a vector containing shift amount.
15886     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15887     SmallVector<SDValue, 4> ShOps;
15888     ShOps.push_back(ShAmt);
15889     if (SVT == MVT::i32) {
15890       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15891       ShOps.push_back(DAG.getUNDEF(SVT));
15892     }
15893     ShOps.push_back(DAG.getUNDEF(SVT));
15894
15895     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15896     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15897   }
15898
15899   // The return type has to be a 128-bit type with the same element
15900   // type as the input type.
15901   MVT EltVT = VT.getVectorElementType();
15902   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15903
15904   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15905   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15906 }
15907
15908 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15909 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15910 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15911 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15912                                     SDValue PreservedSrc,
15913                                     const X86Subtarget *Subtarget,
15914                                     SelectionDAG &DAG) {
15915     EVT VT = Op.getValueType();
15916     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15917                                   MVT::i1, VT.getVectorNumElements());
15918     SDValue VMask = SDValue();
15919     unsigned OpcodeSelect = ISD::VSELECT;
15920     SDLoc dl(Op);
15921
15922     assert(MaskVT.isSimple() && "invalid mask type");
15923
15924     if (isAllOnes(Mask))
15925       return Op;
15926
15927     if (MaskVT.bitsGT(Mask.getValueType())) {
15928       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15929                                          MaskVT.getSizeInBits());
15930       VMask = DAG.getBitcast(MaskVT,
15931                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15932     } else {
15933       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15934                                        Mask.getValueType().getSizeInBits());
15935       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15936       // are extracted by EXTRACT_SUBVECTOR.
15937       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15938                           DAG.getBitcast(BitcastVT, Mask),
15939                           DAG.getIntPtrConstant(0, dl));
15940     }
15941
15942     switch (Op.getOpcode()) {
15943       default: break;
15944       case X86ISD::PCMPEQM:
15945       case X86ISD::PCMPGTM:
15946       case X86ISD::CMPM:
15947       case X86ISD::CMPMU:
15948         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15949       case X86ISD::VFPCLASS:
15950         return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
15951       case X86ISD::VTRUNC:
15952       case X86ISD::VTRUNCS:
15953       case X86ISD::VTRUNCUS:
15954         // We can't use ISD::VSELECT here because it is not always "Legal"
15955         // for the destination type. For example vpmovqb require only AVX512
15956         // and vselect that can operate on byte element type require BWI
15957         OpcodeSelect = X86ISD::SELECT;
15958         break;
15959     }
15960     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15961       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15962     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15963 }
15964
15965 /// \brief Creates an SDNode for a predicated scalar operation.
15966 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15967 /// The mask is coming as MVT::i8 and it should be truncated
15968 /// to MVT::i1 while lowering masking intrinsics.
15969 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15970 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15971 /// for a scalar instruction.
15972 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15973                                     SDValue PreservedSrc,
15974                                     const X86Subtarget *Subtarget,
15975                                     SelectionDAG &DAG) {
15976   if (isAllOnes(Mask))
15977     return Op;
15978
15979   EVT VT = Op.getValueType();
15980   SDLoc dl(Op);
15981   // The mask should be of type MVT::i1
15982   SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15983
15984   if (Op.getOpcode() == X86ISD::FSETCC)
15985     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
15986
15987   if (PreservedSrc.getOpcode() == ISD::UNDEF)
15988     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15989   return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15990 }
15991
15992 static int getSEHRegistrationNodeSize(const Function *Fn) {
15993   if (!Fn->hasPersonalityFn())
15994     report_fatal_error(
15995         "querying registration node size for function without personality");
15996   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15997   // WinEHStatePass for the full struct definition.
15998   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15999   case EHPersonality::MSVC_X86SEH: return 24;
16000   case EHPersonality::MSVC_CXX: return 16;
16001   default: break;
16002   }
16003   report_fatal_error("can only recover FP for MSVC EH personality functions");
16004 }
16005
16006 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
16007 /// function or when returning to a parent frame after catching an exception, we
16008 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
16009 /// Here's the math:
16010 ///   RegNodeBase = EntryEBP - RegNodeSize
16011 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
16012 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16013 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16014 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16015                                    SDValue EntryEBP) {
16016   MachineFunction &MF = DAG.getMachineFunction();
16017   SDLoc dl;
16018
16019   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16020   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16021
16022   // It's possible that the parent function no longer has a personality function
16023   // if the exceptional code was optimized away, in which case we just return
16024   // the incoming EBP.
16025   if (!Fn->hasPersonalityFn())
16026     return EntryEBP;
16027
16028   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16029
16030   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16031   // registration.
16032   MCSymbol *OffsetSym =
16033       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16034           GlobalValue::getRealLinkageName(Fn->getName()));
16035   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16036   SDValue RegNodeFrameOffset =
16037       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16038
16039   // RegNodeBase = EntryEBP - RegNodeSize
16040   // ParentFP = RegNodeBase - RegNodeFrameOffset
16041   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16042                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
16043   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
16044 }
16045
16046 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16047                                        SelectionDAG &DAG) {
16048   SDLoc dl(Op);
16049   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16050   EVT VT = Op.getValueType();
16051   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16052   if (IntrData) {
16053     switch(IntrData->Type) {
16054     case INTR_TYPE_1OP:
16055       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16056     case INTR_TYPE_2OP:
16057       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16058         Op.getOperand(2));
16059     case INTR_TYPE_2OP_IMM8:
16060       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16061                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16062     case INTR_TYPE_3OP:
16063       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16064         Op.getOperand(2), Op.getOperand(3));
16065     case INTR_TYPE_4OP:
16066       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16067         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16068     case INTR_TYPE_1OP_MASK_RM: {
16069       SDValue Src = Op.getOperand(1);
16070       SDValue PassThru = Op.getOperand(2);
16071       SDValue Mask = Op.getOperand(3);
16072       SDValue RoundingMode;
16073       // We allways add rounding mode to the Node.
16074       // If the rounding mode is not specified, we add the
16075       // "current direction" mode.
16076       if (Op.getNumOperands() == 4)
16077         RoundingMode =
16078           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16079       else
16080         RoundingMode = Op.getOperand(4);
16081       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16082       if (IntrWithRoundingModeOpcode != 0)
16083         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16084             X86::STATIC_ROUNDING::CUR_DIRECTION)
16085           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16086                                       dl, Op.getValueType(), Src, RoundingMode),
16087                                       Mask, PassThru, Subtarget, DAG);
16088       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16089                                               RoundingMode),
16090                                   Mask, PassThru, Subtarget, DAG);
16091     }
16092     case INTR_TYPE_1OP_MASK: {
16093       SDValue Src = Op.getOperand(1);
16094       SDValue PassThru = Op.getOperand(2);
16095       SDValue Mask = Op.getOperand(3);
16096       // We add rounding mode to the Node when
16097       //   - RM Opcode is specified and
16098       //   - RM is not "current direction".
16099       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16100       if (IntrWithRoundingModeOpcode != 0) {
16101         SDValue Rnd = Op.getOperand(4);
16102         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16103         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16104           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16105                                       dl, Op.getValueType(),
16106                                       Src, Rnd),
16107                                       Mask, PassThru, Subtarget, DAG);
16108         }
16109       }
16110       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16111                                   Mask, PassThru, Subtarget, DAG);
16112     }
16113     case INTR_TYPE_SCALAR_MASK: {
16114       SDValue Src1 = Op.getOperand(1);
16115       SDValue Src2 = Op.getOperand(2);
16116       SDValue passThru = Op.getOperand(3);
16117       SDValue Mask = Op.getOperand(4);
16118       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16119                                   Mask, passThru, Subtarget, DAG);
16120     }
16121     case INTR_TYPE_SCALAR_MASK_RM: {
16122       SDValue Src1 = Op.getOperand(1);
16123       SDValue Src2 = Op.getOperand(2);
16124       SDValue Src0 = Op.getOperand(3);
16125       SDValue Mask = Op.getOperand(4);
16126       // There are 2 kinds of intrinsics in this group:
16127       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16128       // (2) With rounding mode and sae - 7 operands.
16129       if (Op.getNumOperands() == 6) {
16130         SDValue Sae  = Op.getOperand(5);
16131         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16132         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16133                                                 Sae),
16134                                     Mask, Src0, Subtarget, DAG);
16135       }
16136       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16137       SDValue RoundingMode  = Op.getOperand(5);
16138       SDValue Sae  = Op.getOperand(6);
16139       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16140                                               RoundingMode, Sae),
16141                                   Mask, Src0, Subtarget, DAG);
16142     }
16143     case INTR_TYPE_2OP_MASK:
16144     case INTR_TYPE_2OP_IMM8_MASK: {
16145       SDValue Src1 = Op.getOperand(1);
16146       SDValue Src2 = Op.getOperand(2);
16147       SDValue PassThru = Op.getOperand(3);
16148       SDValue Mask = Op.getOperand(4);
16149
16150       if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16151         Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16152
16153       // We specify 2 possible opcodes for intrinsics with rounding modes.
16154       // First, we check if the intrinsic may have non-default rounding mode,
16155       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16156       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16157       if (IntrWithRoundingModeOpcode != 0) {
16158         SDValue Rnd = Op.getOperand(5);
16159         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16160         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16161           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16162                                       dl, Op.getValueType(),
16163                                       Src1, Src2, Rnd),
16164                                       Mask, PassThru, Subtarget, DAG);
16165         }
16166       }
16167       // TODO: Intrinsics should have fast-math-flags to propagate.
16168       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16169                                   Mask, PassThru, Subtarget, DAG);
16170     }
16171     case INTR_TYPE_2OP_MASK_RM: {
16172       SDValue Src1 = Op.getOperand(1);
16173       SDValue Src2 = Op.getOperand(2);
16174       SDValue PassThru = Op.getOperand(3);
16175       SDValue Mask = Op.getOperand(4);
16176       // We specify 2 possible modes for intrinsics, with/without rounding
16177       // modes.
16178       // First, we check if the intrinsic have rounding mode (6 operands),
16179       // if not, we set rounding mode to "current".
16180       SDValue Rnd;
16181       if (Op.getNumOperands() == 6)
16182         Rnd = Op.getOperand(5);
16183       else
16184         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16185       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16186                                               Src1, Src2, Rnd),
16187                                   Mask, PassThru, Subtarget, DAG);
16188     }
16189     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16190       SDValue Src1 = Op.getOperand(1);
16191       SDValue Src2 = Op.getOperand(2);
16192       SDValue Src3 = Op.getOperand(3);
16193       SDValue PassThru = Op.getOperand(4);
16194       SDValue Mask = Op.getOperand(5);
16195       SDValue Sae  = Op.getOperand(6);
16196
16197       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16198                                               Src2, Src3, Sae),
16199                                   Mask, PassThru, Subtarget, DAG);
16200     }
16201     case INTR_TYPE_3OP_MASK_RM: {
16202       SDValue Src1 = Op.getOperand(1);
16203       SDValue Src2 = Op.getOperand(2);
16204       SDValue Imm = Op.getOperand(3);
16205       SDValue PassThru = Op.getOperand(4);
16206       SDValue Mask = Op.getOperand(5);
16207       // We specify 2 possible modes for intrinsics, with/without rounding
16208       // modes.
16209       // First, we check if the intrinsic have rounding mode (7 operands),
16210       // if not, we set rounding mode to "current".
16211       SDValue Rnd;
16212       if (Op.getNumOperands() == 7)
16213         Rnd = Op.getOperand(6);
16214       else
16215         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16216       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16217         Src1, Src2, Imm, Rnd),
16218         Mask, PassThru, Subtarget, DAG);
16219     }
16220     case INTR_TYPE_3OP_IMM8_MASK:
16221     case INTR_TYPE_3OP_MASK:
16222     case INSERT_SUBVEC: {
16223       SDValue Src1 = Op.getOperand(1);
16224       SDValue Src2 = Op.getOperand(2);
16225       SDValue Src3 = Op.getOperand(3);
16226       SDValue PassThru = Op.getOperand(4);
16227       SDValue Mask = Op.getOperand(5);
16228
16229       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16230         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16231       else if (IntrData->Type == INSERT_SUBVEC) {
16232         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16233         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16234         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16235         Imm *= Src2.getValueType().getVectorNumElements();
16236         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16237       }
16238
16239       // We specify 2 possible opcodes for intrinsics with rounding modes.
16240       // First, we check if the intrinsic may have non-default rounding mode,
16241       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16242       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16243       if (IntrWithRoundingModeOpcode != 0) {
16244         SDValue Rnd = Op.getOperand(6);
16245         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16246         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16247           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16248                                       dl, Op.getValueType(),
16249                                       Src1, Src2, Src3, Rnd),
16250                                       Mask, PassThru, Subtarget, DAG);
16251         }
16252       }
16253       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16254                                               Src1, Src2, Src3),
16255                                   Mask, PassThru, Subtarget, DAG);
16256     }
16257     case VPERM_3OP_MASKZ:
16258     case VPERM_3OP_MASK:
16259     case FMA_OP_MASK3:
16260     case FMA_OP_MASKZ:
16261     case FMA_OP_MASK: {
16262       SDValue Src1 = Op.getOperand(1);
16263       SDValue Src2 = Op.getOperand(2);
16264       SDValue Src3 = Op.getOperand(3);
16265       SDValue Mask = Op.getOperand(4);
16266       EVT VT = Op.getValueType();
16267       SDValue PassThru = SDValue();
16268
16269       // set PassThru element
16270       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
16271         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16272       else if (IntrData->Type == FMA_OP_MASK3)
16273         PassThru = Src3;
16274       else
16275         PassThru = Src1;
16276
16277       // We specify 2 possible opcodes for intrinsics with rounding modes.
16278       // First, we check if the intrinsic may have non-default rounding mode,
16279       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16280       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16281       if (IntrWithRoundingModeOpcode != 0) {
16282         SDValue Rnd = Op.getOperand(5);
16283         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16284             X86::STATIC_ROUNDING::CUR_DIRECTION)
16285           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16286                                                   dl, Op.getValueType(),
16287                                                   Src1, Src2, Src3, Rnd),
16288                                       Mask, PassThru, Subtarget, DAG);
16289       }
16290       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16291                                               dl, Op.getValueType(),
16292                                               Src1, Src2, Src3),
16293                                   Mask, PassThru, Subtarget, DAG);
16294     }
16295     case TERLOG_OP_MASK:
16296     case TERLOG_OP_MASKZ: {
16297       SDValue Src1 = Op.getOperand(1);
16298       SDValue Src2 = Op.getOperand(2);
16299       SDValue Src3 = Op.getOperand(3);
16300       SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16301       SDValue Mask = Op.getOperand(5);
16302       EVT VT = Op.getValueType();
16303       SDValue PassThru = Src1;
16304       // Set PassThru element.
16305       if (IntrData->Type == TERLOG_OP_MASKZ)
16306         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16307
16308       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16309                                               Src1, Src2, Src3, Src4),
16310                                   Mask, PassThru, Subtarget, DAG);
16311     }
16312     case FPCLASS: {
16313       // FPclass intrinsics with mask
16314        SDValue Src1 = Op.getOperand(1);
16315        EVT VT = Src1.getValueType();
16316        EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16317                                       VT.getVectorNumElements());
16318        SDValue Imm = Op.getOperand(2);
16319        SDValue Mask = Op.getOperand(3);
16320        EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16321                                         Mask.getValueType().getSizeInBits());
16322        SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16323        SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16324                                                  DAG.getTargetConstant(0, dl, MaskVT),
16325                                                  Subtarget, DAG);
16326        SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16327                                  DAG.getUNDEF(BitcastVT), FPclassMask,
16328                                  DAG.getIntPtrConstant(0, dl));
16329        return DAG.getBitcast(Op.getValueType(), Res);
16330     }
16331     case CMP_MASK:
16332     case CMP_MASK_CC: {
16333       // Comparison intrinsics with masks.
16334       // Example of transformation:
16335       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16336       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16337       // (i8 (bitcast
16338       //   (v8i1 (insert_subvector undef,
16339       //           (v2i1 (and (PCMPEQM %a, %b),
16340       //                      (extract_subvector
16341       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16342       EVT VT = Op.getOperand(1).getValueType();
16343       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16344                                     VT.getVectorNumElements());
16345       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16346       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16347                                        Mask.getValueType().getSizeInBits());
16348       SDValue Cmp;
16349       if (IntrData->Type == CMP_MASK_CC) {
16350         SDValue CC = Op.getOperand(3);
16351         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16352         // We specify 2 possible opcodes for intrinsics with rounding modes.
16353         // First, we check if the intrinsic may have non-default rounding mode,
16354         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16355         if (IntrData->Opc1 != 0) {
16356           SDValue Rnd = Op.getOperand(5);
16357           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16358               X86::STATIC_ROUNDING::CUR_DIRECTION)
16359             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16360                               Op.getOperand(2), CC, Rnd);
16361         }
16362         //default rounding mode
16363         if(!Cmp.getNode())
16364             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16365                               Op.getOperand(2), CC);
16366
16367       } else {
16368         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16369         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16370                           Op.getOperand(2));
16371       }
16372       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16373                                              DAG.getTargetConstant(0, dl,
16374                                                                    MaskVT),
16375                                              Subtarget, DAG);
16376       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16377                                 DAG.getUNDEF(BitcastVT), CmpMask,
16378                                 DAG.getIntPtrConstant(0, dl));
16379       return DAG.getBitcast(Op.getValueType(), Res);
16380     }
16381     case CMP_MASK_SCALAR_CC: {
16382       SDValue Src1 = Op.getOperand(1);
16383       SDValue Src2 = Op.getOperand(2);
16384       SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16385       SDValue Mask = Op.getOperand(4);
16386
16387       SDValue Cmp;
16388       if (IntrData->Opc1 != 0) {
16389         SDValue Rnd = Op.getOperand(5);
16390         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16391             X86::STATIC_ROUNDING::CUR_DIRECTION)
16392           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16393       }
16394       //default rounding mode
16395       if(!Cmp.getNode())
16396         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16397
16398       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16399                                              DAG.getTargetConstant(0, dl,
16400                                                                    MVT::i1),
16401                                              Subtarget, DAG);
16402
16403       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16404                          DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16405                          DAG.getValueType(MVT::i1));
16406     }
16407     case COMI: { // Comparison intrinsics
16408       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16409       SDValue LHS = Op.getOperand(1);
16410       SDValue RHS = Op.getOperand(2);
16411       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16412       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16413       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16414       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16415                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16416       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16417     }
16418     case VSHIFT:
16419       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16420                                  Op.getOperand(1), Op.getOperand(2), DAG);
16421     case VSHIFT_MASK:
16422       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16423                                                       Op.getSimpleValueType(),
16424                                                       Op.getOperand(1),
16425                                                       Op.getOperand(2), DAG),
16426                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16427                                   DAG);
16428     case COMPRESS_EXPAND_IN_REG: {
16429       SDValue Mask = Op.getOperand(3);
16430       SDValue DataToCompress = Op.getOperand(1);
16431       SDValue PassThru = Op.getOperand(2);
16432       if (isAllOnes(Mask)) // return data as is
16433         return Op.getOperand(1);
16434
16435       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16436                                               DataToCompress),
16437                                   Mask, PassThru, Subtarget, DAG);
16438     }
16439     case BLEND: {
16440       SDValue Mask = Op.getOperand(3);
16441       EVT VT = Op.getValueType();
16442       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16443                                     VT.getVectorNumElements());
16444       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16445                                        Mask.getValueType().getSizeInBits());
16446       SDLoc dl(Op);
16447       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16448                                   DAG.getBitcast(BitcastVT, Mask),
16449                                   DAG.getIntPtrConstant(0, dl));
16450       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16451                          Op.getOperand(2));
16452     }
16453     default:
16454       break;
16455     }
16456   }
16457
16458   switch (IntNo) {
16459   default: return SDValue();    // Don't custom lower most intrinsics.
16460
16461   case Intrinsic::x86_avx2_permd:
16462   case Intrinsic::x86_avx2_permps:
16463     // Operands intentionally swapped. Mask is last operand to intrinsic,
16464     // but second operand for node/instruction.
16465     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16466                        Op.getOperand(2), Op.getOperand(1));
16467
16468   // ptest and testp intrinsics. The intrinsic these come from are designed to
16469   // return an integer value, not just an instruction so lower it to the ptest
16470   // or testp pattern and a setcc for the result.
16471   case Intrinsic::x86_sse41_ptestz:
16472   case Intrinsic::x86_sse41_ptestc:
16473   case Intrinsic::x86_sse41_ptestnzc:
16474   case Intrinsic::x86_avx_ptestz_256:
16475   case Intrinsic::x86_avx_ptestc_256:
16476   case Intrinsic::x86_avx_ptestnzc_256:
16477   case Intrinsic::x86_avx_vtestz_ps:
16478   case Intrinsic::x86_avx_vtestc_ps:
16479   case Intrinsic::x86_avx_vtestnzc_ps:
16480   case Intrinsic::x86_avx_vtestz_pd:
16481   case Intrinsic::x86_avx_vtestc_pd:
16482   case Intrinsic::x86_avx_vtestnzc_pd:
16483   case Intrinsic::x86_avx_vtestz_ps_256:
16484   case Intrinsic::x86_avx_vtestc_ps_256:
16485   case Intrinsic::x86_avx_vtestnzc_ps_256:
16486   case Intrinsic::x86_avx_vtestz_pd_256:
16487   case Intrinsic::x86_avx_vtestc_pd_256:
16488   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16489     bool IsTestPacked = false;
16490     unsigned X86CC;
16491     switch (IntNo) {
16492     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16493     case Intrinsic::x86_avx_vtestz_ps:
16494     case Intrinsic::x86_avx_vtestz_pd:
16495     case Intrinsic::x86_avx_vtestz_ps_256:
16496     case Intrinsic::x86_avx_vtestz_pd_256:
16497       IsTestPacked = true; // Fallthrough
16498     case Intrinsic::x86_sse41_ptestz:
16499     case Intrinsic::x86_avx_ptestz_256:
16500       // ZF = 1
16501       X86CC = X86::COND_E;
16502       break;
16503     case Intrinsic::x86_avx_vtestc_ps:
16504     case Intrinsic::x86_avx_vtestc_pd:
16505     case Intrinsic::x86_avx_vtestc_ps_256:
16506     case Intrinsic::x86_avx_vtestc_pd_256:
16507       IsTestPacked = true; // Fallthrough
16508     case Intrinsic::x86_sse41_ptestc:
16509     case Intrinsic::x86_avx_ptestc_256:
16510       // CF = 1
16511       X86CC = X86::COND_B;
16512       break;
16513     case Intrinsic::x86_avx_vtestnzc_ps:
16514     case Intrinsic::x86_avx_vtestnzc_pd:
16515     case Intrinsic::x86_avx_vtestnzc_ps_256:
16516     case Intrinsic::x86_avx_vtestnzc_pd_256:
16517       IsTestPacked = true; // Fallthrough
16518     case Intrinsic::x86_sse41_ptestnzc:
16519     case Intrinsic::x86_avx_ptestnzc_256:
16520       // ZF and CF = 0
16521       X86CC = X86::COND_A;
16522       break;
16523     }
16524
16525     SDValue LHS = Op.getOperand(1);
16526     SDValue RHS = Op.getOperand(2);
16527     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16528     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16529     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16530     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16531     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16532   }
16533   case Intrinsic::x86_avx512_kortestz_w:
16534   case Intrinsic::x86_avx512_kortestc_w: {
16535     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16536     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16537     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16538     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16539     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16540     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16541     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16542   }
16543
16544   case Intrinsic::x86_sse42_pcmpistria128:
16545   case Intrinsic::x86_sse42_pcmpestria128:
16546   case Intrinsic::x86_sse42_pcmpistric128:
16547   case Intrinsic::x86_sse42_pcmpestric128:
16548   case Intrinsic::x86_sse42_pcmpistrio128:
16549   case Intrinsic::x86_sse42_pcmpestrio128:
16550   case Intrinsic::x86_sse42_pcmpistris128:
16551   case Intrinsic::x86_sse42_pcmpestris128:
16552   case Intrinsic::x86_sse42_pcmpistriz128:
16553   case Intrinsic::x86_sse42_pcmpestriz128: {
16554     unsigned Opcode;
16555     unsigned X86CC;
16556     switch (IntNo) {
16557     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16558     case Intrinsic::x86_sse42_pcmpistria128:
16559       Opcode = X86ISD::PCMPISTRI;
16560       X86CC = X86::COND_A;
16561       break;
16562     case Intrinsic::x86_sse42_pcmpestria128:
16563       Opcode = X86ISD::PCMPESTRI;
16564       X86CC = X86::COND_A;
16565       break;
16566     case Intrinsic::x86_sse42_pcmpistric128:
16567       Opcode = X86ISD::PCMPISTRI;
16568       X86CC = X86::COND_B;
16569       break;
16570     case Intrinsic::x86_sse42_pcmpestric128:
16571       Opcode = X86ISD::PCMPESTRI;
16572       X86CC = X86::COND_B;
16573       break;
16574     case Intrinsic::x86_sse42_pcmpistrio128:
16575       Opcode = X86ISD::PCMPISTRI;
16576       X86CC = X86::COND_O;
16577       break;
16578     case Intrinsic::x86_sse42_pcmpestrio128:
16579       Opcode = X86ISD::PCMPESTRI;
16580       X86CC = X86::COND_O;
16581       break;
16582     case Intrinsic::x86_sse42_pcmpistris128:
16583       Opcode = X86ISD::PCMPISTRI;
16584       X86CC = X86::COND_S;
16585       break;
16586     case Intrinsic::x86_sse42_pcmpestris128:
16587       Opcode = X86ISD::PCMPESTRI;
16588       X86CC = X86::COND_S;
16589       break;
16590     case Intrinsic::x86_sse42_pcmpistriz128:
16591       Opcode = X86ISD::PCMPISTRI;
16592       X86CC = X86::COND_E;
16593       break;
16594     case Intrinsic::x86_sse42_pcmpestriz128:
16595       Opcode = X86ISD::PCMPESTRI;
16596       X86CC = X86::COND_E;
16597       break;
16598     }
16599     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16600     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16601     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16602     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16603                                 DAG.getConstant(X86CC, dl, MVT::i8),
16604                                 SDValue(PCMP.getNode(), 1));
16605     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16606   }
16607
16608   case Intrinsic::x86_sse42_pcmpistri128:
16609   case Intrinsic::x86_sse42_pcmpestri128: {
16610     unsigned Opcode;
16611     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16612       Opcode = X86ISD::PCMPISTRI;
16613     else
16614       Opcode = X86ISD::PCMPESTRI;
16615
16616     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16617     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16618     return DAG.getNode(Opcode, dl, VTs, NewOps);
16619   }
16620
16621   case Intrinsic::x86_seh_lsda: {
16622     // Compute the symbol for the LSDA. We know it'll get emitted later.
16623     MachineFunction &MF = DAG.getMachineFunction();
16624     SDValue Op1 = Op.getOperand(1);
16625     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16626     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16627         GlobalValue::getRealLinkageName(Fn->getName()));
16628
16629     // Generate a simple absolute symbol reference. This intrinsic is only
16630     // supported on 32-bit Windows, which isn't PIC.
16631     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16632     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16633   }
16634
16635   case Intrinsic::x86_seh_recoverfp: {
16636     SDValue FnOp = Op.getOperand(1);
16637     SDValue IncomingFPOp = Op.getOperand(2);
16638     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16639     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16640     if (!Fn)
16641       report_fatal_error(
16642           "llvm.x86.seh.recoverfp must take a function as the first argument");
16643     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16644   }
16645
16646   case Intrinsic::localaddress: {
16647     // Returns one of the stack, base, or frame pointer registers, depending on
16648     // which is used to reference local variables.
16649     MachineFunction &MF = DAG.getMachineFunction();
16650     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16651     unsigned Reg;
16652     if (RegInfo->hasBasePointer(MF))
16653       Reg = RegInfo->getBaseRegister();
16654     else // This function handles the SP or FP case.
16655       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16656     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16657   }
16658   }
16659 }
16660
16661 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16662                               SDValue Src, SDValue Mask, SDValue Base,
16663                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16664                               const X86Subtarget * Subtarget) {
16665   SDLoc dl(Op);
16666   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16667   if (!C)
16668     llvm_unreachable("Invalid scale type");
16669   unsigned ScaleVal = C->getZExtValue();
16670   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16671     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16672
16673   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16674   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16675                              Index.getSimpleValueType().getVectorNumElements());
16676   SDValue MaskInReg;
16677   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16678   if (MaskC)
16679     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16680   else {
16681     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16682                                      Mask.getValueType().getSizeInBits());
16683
16684     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16685     // are extracted by EXTRACT_SUBVECTOR.
16686     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16687                             DAG.getBitcast(BitcastVT, Mask),
16688                             DAG.getIntPtrConstant(0, dl));
16689   }
16690   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16691   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16692   SDValue Segment = DAG.getRegister(0, MVT::i32);
16693   if (Src.getOpcode() == ISD::UNDEF)
16694     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16695   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16696   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16697   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16698   return DAG.getMergeValues(RetOps, dl);
16699 }
16700
16701 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16702                                SDValue Src, SDValue Mask, SDValue Base,
16703                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16704   SDLoc dl(Op);
16705   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16706   if (!C)
16707     llvm_unreachable("Invalid scale type");
16708   unsigned ScaleVal = C->getZExtValue();
16709   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16710     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16711
16712   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16713   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16714   SDValue Segment = DAG.getRegister(0, MVT::i32);
16715   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16716                              Index.getSimpleValueType().getVectorNumElements());
16717   SDValue MaskInReg;
16718   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16719   if (MaskC)
16720     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16721   else {
16722     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16723                                      Mask.getValueType().getSizeInBits());
16724
16725     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16726     // are extracted by EXTRACT_SUBVECTOR.
16727     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16728                             DAG.getBitcast(BitcastVT, Mask),
16729                             DAG.getIntPtrConstant(0, dl));
16730   }
16731   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16732   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16733   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16734   return SDValue(Res, 1);
16735 }
16736
16737 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16738                                SDValue Mask, SDValue Base, SDValue Index,
16739                                SDValue ScaleOp, SDValue Chain) {
16740   SDLoc dl(Op);
16741   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16742   assert(C && "Invalid scale type");
16743   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16744   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16745   SDValue Segment = DAG.getRegister(0, MVT::i32);
16746   EVT MaskVT =
16747     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16748   SDValue MaskInReg;
16749   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16750   if (MaskC)
16751     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16752   else
16753     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16754   //SDVTList VTs = DAG.getVTList(MVT::Other);
16755   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16756   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16757   return SDValue(Res, 0);
16758 }
16759
16760 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16761 // read performance monitor counters (x86_rdpmc).
16762 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16763                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16764                               SmallVectorImpl<SDValue> &Results) {
16765   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16766   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16767   SDValue LO, HI;
16768
16769   // The ECX register is used to select the index of the performance counter
16770   // to read.
16771   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16772                                    N->getOperand(2));
16773   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16774
16775   // Reads the content of a 64-bit performance counter and returns it in the
16776   // registers EDX:EAX.
16777   if (Subtarget->is64Bit()) {
16778     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16779     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16780                             LO.getValue(2));
16781   } else {
16782     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16783     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16784                             LO.getValue(2));
16785   }
16786   Chain = HI.getValue(1);
16787
16788   if (Subtarget->is64Bit()) {
16789     // The EAX register is loaded with the low-order 32 bits. The EDX register
16790     // is loaded with the supported high-order bits of the counter.
16791     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16792                               DAG.getConstant(32, DL, MVT::i8));
16793     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16794     Results.push_back(Chain);
16795     return;
16796   }
16797
16798   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16799   SDValue Ops[] = { LO, HI };
16800   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16801   Results.push_back(Pair);
16802   Results.push_back(Chain);
16803 }
16804
16805 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16806 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16807 // also used to custom lower READCYCLECOUNTER nodes.
16808 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16809                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16810                               SmallVectorImpl<SDValue> &Results) {
16811   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16812   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16813   SDValue LO, HI;
16814
16815   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16816   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16817   // and the EAX register is loaded with the low-order 32 bits.
16818   if (Subtarget->is64Bit()) {
16819     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16820     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16821                             LO.getValue(2));
16822   } else {
16823     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16824     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16825                             LO.getValue(2));
16826   }
16827   SDValue Chain = HI.getValue(1);
16828
16829   if (Opcode == X86ISD::RDTSCP_DAG) {
16830     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16831
16832     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16833     // the ECX register. Add 'ecx' explicitly to the chain.
16834     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16835                                      HI.getValue(2));
16836     // Explicitly store the content of ECX at the location passed in input
16837     // to the 'rdtscp' intrinsic.
16838     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16839                          MachinePointerInfo(), false, false, 0);
16840   }
16841
16842   if (Subtarget->is64Bit()) {
16843     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16844     // the EAX register is loaded with the low-order 32 bits.
16845     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16846                               DAG.getConstant(32, DL, MVT::i8));
16847     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16848     Results.push_back(Chain);
16849     return;
16850   }
16851
16852   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16853   SDValue Ops[] = { LO, HI };
16854   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16855   Results.push_back(Pair);
16856   Results.push_back(Chain);
16857 }
16858
16859 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16860                                      SelectionDAG &DAG) {
16861   SmallVector<SDValue, 2> Results;
16862   SDLoc DL(Op);
16863   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16864                           Results);
16865   return DAG.getMergeValues(Results, DL);
16866 }
16867
16868 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16869                                     SelectionDAG &DAG) {
16870   MachineFunction &MF = DAG.getMachineFunction();
16871   const Function *Fn = MF.getFunction();
16872   SDLoc dl(Op);
16873   SDValue Chain = Op.getOperand(0);
16874
16875   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16876          "using llvm.x86.seh.restoreframe requires a frame pointer");
16877
16878   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16879   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16880
16881   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16882   unsigned FrameReg =
16883       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16884   unsigned SPReg = RegInfo->getStackRegister();
16885   unsigned SlotSize = RegInfo->getSlotSize();
16886
16887   // Get incoming EBP.
16888   SDValue IncomingEBP =
16889       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16890
16891   // SP is saved in the first field of every registration node, so load
16892   // [EBP-RegNodeSize] into SP.
16893   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16894   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16895                                DAG.getConstant(-RegNodeSize, dl, VT));
16896   SDValue NewSP =
16897       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16898                   false, VT.getScalarSizeInBits() / 8);
16899   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16900
16901   if (!RegInfo->needsStackRealignment(MF)) {
16902     // Adjust EBP to point back to the original frame position.
16903     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16904     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16905   } else {
16906     assert(RegInfo->hasBasePointer(MF) &&
16907            "functions with Win32 EH must use frame or base pointer register");
16908
16909     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16910     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16911     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16912
16913     // Reload the spilled EBP value, now that the stack and base pointers are
16914     // set up.
16915     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16916     X86FI->setHasSEHFramePtrSave(true);
16917     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16918     X86FI->setSEHFramePtrSaveIndex(FI);
16919     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16920                                 MachinePointerInfo(), false, false, false,
16921                                 VT.getScalarSizeInBits() / 8);
16922     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16923   }
16924
16925   return Chain;
16926 }
16927
16928 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16929 /// return truncate Store/MaskedStore Node
16930 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16931                                                SelectionDAG &DAG,
16932                                                MVT ElementType) {
16933   SDLoc dl(Op);
16934   SDValue Mask = Op.getOperand(4);
16935   SDValue DataToTruncate = Op.getOperand(3);
16936   SDValue Addr = Op.getOperand(2);
16937   SDValue Chain = Op.getOperand(0);
16938
16939   EVT VT  = DataToTruncate.getValueType();
16940   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16941                              ElementType, VT.getVectorNumElements());
16942
16943   if (isAllOnes(Mask)) // return just a truncate store
16944     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16945                              MachinePointerInfo(), SVT, false, false,
16946                              SVT.getScalarSizeInBits()/8);
16947
16948   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16949                                 MVT::i1, VT.getVectorNumElements());
16950   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16951                                    Mask.getValueType().getSizeInBits());
16952   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16953   // are extracted by EXTRACT_SUBVECTOR.
16954   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16955                               DAG.getBitcast(BitcastVT, Mask),
16956                               DAG.getIntPtrConstant(0, dl));
16957
16958   MachineMemOperand *MMO = DAG.getMachineFunction().
16959     getMachineMemOperand(MachinePointerInfo(),
16960                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16961                          SVT.getScalarSizeInBits()/8);
16962
16963   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16964                             VMask, SVT, MMO, true);
16965 }
16966
16967 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16968                                       SelectionDAG &DAG) {
16969   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16970
16971   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16972   if (!IntrData) {
16973     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16974       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16975     return SDValue();
16976   }
16977
16978   SDLoc dl(Op);
16979   switch(IntrData->Type) {
16980   default:
16981     llvm_unreachable("Unknown Intrinsic Type");
16982     break;
16983   case RDSEED:
16984   case RDRAND: {
16985     // Emit the node with the right value type.
16986     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16987     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16988
16989     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16990     // Otherwise return the value from Rand, which is always 0, casted to i32.
16991     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16992                       DAG.getConstant(1, dl, Op->getValueType(1)),
16993                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16994                       SDValue(Result.getNode(), 1) };
16995     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16996                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16997                                   Ops);
16998
16999     // Return { result, isValid, chain }.
17000     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17001                        SDValue(Result.getNode(), 2));
17002   }
17003   case GATHER: {
17004   //gather(v1, mask, index, base, scale);
17005     SDValue Chain = Op.getOperand(0);
17006     SDValue Src   = Op.getOperand(2);
17007     SDValue Base  = Op.getOperand(3);
17008     SDValue Index = Op.getOperand(4);
17009     SDValue Mask  = Op.getOperand(5);
17010     SDValue Scale = Op.getOperand(6);
17011     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17012                          Chain, Subtarget);
17013   }
17014   case SCATTER: {
17015   //scatter(base, mask, index, v1, scale);
17016     SDValue Chain = Op.getOperand(0);
17017     SDValue Base  = Op.getOperand(2);
17018     SDValue Mask  = Op.getOperand(3);
17019     SDValue Index = Op.getOperand(4);
17020     SDValue Src   = Op.getOperand(5);
17021     SDValue Scale = Op.getOperand(6);
17022     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17023                           Scale, Chain);
17024   }
17025   case PREFETCH: {
17026     SDValue Hint = Op.getOperand(6);
17027     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17028     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17029     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17030     SDValue Chain = Op.getOperand(0);
17031     SDValue Mask  = Op.getOperand(2);
17032     SDValue Index = Op.getOperand(3);
17033     SDValue Base  = Op.getOperand(4);
17034     SDValue Scale = Op.getOperand(5);
17035     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17036   }
17037   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17038   case RDTSC: {
17039     SmallVector<SDValue, 2> Results;
17040     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17041                             Results);
17042     return DAG.getMergeValues(Results, dl);
17043   }
17044   // Read Performance Monitoring Counters.
17045   case RDPMC: {
17046     SmallVector<SDValue, 2> Results;
17047     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17048     return DAG.getMergeValues(Results, dl);
17049   }
17050   // XTEST intrinsics.
17051   case XTEST: {
17052     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17053     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17054     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17055                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17056                                 InTrans);
17057     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17058     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17059                        Ret, SDValue(InTrans.getNode(), 1));
17060   }
17061   // ADC/ADCX/SBB
17062   case ADX: {
17063     SmallVector<SDValue, 2> Results;
17064     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17065     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17066     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17067                                 DAG.getConstant(-1, dl, MVT::i8));
17068     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17069                               Op.getOperand(4), GenCF.getValue(1));
17070     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17071                                  Op.getOperand(5), MachinePointerInfo(),
17072                                  false, false, 0);
17073     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17074                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17075                                 Res.getValue(1));
17076     Results.push_back(SetCC);
17077     Results.push_back(Store);
17078     return DAG.getMergeValues(Results, dl);
17079   }
17080   case COMPRESS_TO_MEM: {
17081     SDLoc dl(Op);
17082     SDValue Mask = Op.getOperand(4);
17083     SDValue DataToCompress = Op.getOperand(3);
17084     SDValue Addr = Op.getOperand(2);
17085     SDValue Chain = Op.getOperand(0);
17086
17087     EVT VT = DataToCompress.getValueType();
17088     if (isAllOnes(Mask)) // return just a store
17089       return DAG.getStore(Chain, dl, DataToCompress, Addr,
17090                           MachinePointerInfo(), false, false,
17091                           VT.getScalarSizeInBits()/8);
17092
17093     SDValue Compressed =
17094       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17095                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17096     return DAG.getStore(Chain, dl, Compressed, Addr,
17097                         MachinePointerInfo(), false, false,
17098                         VT.getScalarSizeInBits()/8);
17099   }
17100   case TRUNCATE_TO_MEM_VI8:
17101     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17102   case TRUNCATE_TO_MEM_VI16:
17103     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17104   case TRUNCATE_TO_MEM_VI32:
17105     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17106   case EXPAND_FROM_MEM: {
17107     SDLoc dl(Op);
17108     SDValue Mask = Op.getOperand(4);
17109     SDValue PassThru = Op.getOperand(3);
17110     SDValue Addr = Op.getOperand(2);
17111     SDValue Chain = Op.getOperand(0);
17112     EVT VT = Op.getValueType();
17113
17114     if (isAllOnes(Mask)) // return just a load
17115       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17116                          false, VT.getScalarSizeInBits()/8);
17117
17118     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17119                                        false, false, false,
17120                                        VT.getScalarSizeInBits()/8);
17121
17122     SDValue Results[] = {
17123       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17124                            Mask, PassThru, Subtarget, DAG), Chain};
17125     return DAG.getMergeValues(Results, dl);
17126   }
17127   }
17128 }
17129
17130 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17131                                            SelectionDAG &DAG) const {
17132   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17133   MFI->setReturnAddressIsTaken(true);
17134
17135   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17136     return SDValue();
17137
17138   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17139   SDLoc dl(Op);
17140   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17141
17142   if (Depth > 0) {
17143     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17144     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17145     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17146     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17147                        DAG.getNode(ISD::ADD, dl, PtrVT,
17148                                    FrameAddr, Offset),
17149                        MachinePointerInfo(), false, false, false, 0);
17150   }
17151
17152   // Just load the return address.
17153   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17154   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17155                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17156 }
17157
17158 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17159   MachineFunction &MF = DAG.getMachineFunction();
17160   MachineFrameInfo *MFI = MF.getFrameInfo();
17161   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17162   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17163   EVT VT = Op.getValueType();
17164
17165   MFI->setFrameAddressIsTaken(true);
17166
17167   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17168     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
17169     // is not possible to crawl up the stack without looking at the unwind codes
17170     // simultaneously.
17171     int FrameAddrIndex = FuncInfo->getFAIndex();
17172     if (!FrameAddrIndex) {
17173       // Set up a frame object for the return address.
17174       unsigned SlotSize = RegInfo->getSlotSize();
17175       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17176           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17177       FuncInfo->setFAIndex(FrameAddrIndex);
17178     }
17179     return DAG.getFrameIndex(FrameAddrIndex, VT);
17180   }
17181
17182   unsigned FrameReg =
17183       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17184   SDLoc dl(Op);  // FIXME probably not meaningful
17185   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17186   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17187           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17188          "Invalid Frame Register!");
17189   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17190   while (Depth--)
17191     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17192                             MachinePointerInfo(),
17193                             false, false, false, 0);
17194   return FrameAddr;
17195 }
17196
17197 // FIXME? Maybe this could be a TableGen attribute on some registers and
17198 // this table could be generated automatically from RegInfo.
17199 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17200                                               SelectionDAG &DAG) const {
17201   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17202   const MachineFunction &MF = DAG.getMachineFunction();
17203
17204   unsigned Reg = StringSwitch<unsigned>(RegName)
17205                        .Case("esp", X86::ESP)
17206                        .Case("rsp", X86::RSP)
17207                        .Case("ebp", X86::EBP)
17208                        .Case("rbp", X86::RBP)
17209                        .Default(0);
17210
17211   if (Reg == X86::EBP || Reg == X86::RBP) {
17212     if (!TFI.hasFP(MF))
17213       report_fatal_error("register " + StringRef(RegName) +
17214                          " is allocatable: function has no frame pointer");
17215 #ifndef NDEBUG
17216     else {
17217       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17218       unsigned FrameReg =
17219           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17220       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17221              "Invalid Frame Register!");
17222     }
17223 #endif
17224   }
17225
17226   if (Reg)
17227     return Reg;
17228
17229   report_fatal_error("Invalid register name global variable");
17230 }
17231
17232 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17233                                                      SelectionDAG &DAG) const {
17234   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17235   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17236 }
17237
17238 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17239   SDValue Chain     = Op.getOperand(0);
17240   SDValue Offset    = Op.getOperand(1);
17241   SDValue Handler   = Op.getOperand(2);
17242   SDLoc dl      (Op);
17243
17244   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17245   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17246   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17247   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17248           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17249          "Invalid Frame Register!");
17250   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17251   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17252
17253   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17254                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17255                                                        dl));
17256   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17257   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17258                        false, false, 0);
17259   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17260
17261   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17262                      DAG.getRegister(StoreAddrReg, PtrVT));
17263 }
17264
17265 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17266                                                SelectionDAG &DAG) const {
17267   SDLoc DL(Op);
17268   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17269                      DAG.getVTList(MVT::i32, MVT::Other),
17270                      Op.getOperand(0), Op.getOperand(1));
17271 }
17272
17273 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17274                                                 SelectionDAG &DAG) const {
17275   SDLoc DL(Op);
17276   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17277                      Op.getOperand(0), Op.getOperand(1));
17278 }
17279
17280 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17281   return Op.getOperand(0);
17282 }
17283
17284 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17285                                                 SelectionDAG &DAG) const {
17286   SDValue Root = Op.getOperand(0);
17287   SDValue Trmp = Op.getOperand(1); // trampoline
17288   SDValue FPtr = Op.getOperand(2); // nested function
17289   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17290   SDLoc dl (Op);
17291
17292   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17293   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17294
17295   if (Subtarget->is64Bit()) {
17296     SDValue OutChains[6];
17297
17298     // Large code-model.
17299     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17300     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17301
17302     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17303     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17304
17305     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17306
17307     // Load the pointer to the nested function into R11.
17308     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17309     SDValue Addr = Trmp;
17310     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17311                                 Addr, MachinePointerInfo(TrmpAddr),
17312                                 false, false, 0);
17313
17314     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17315                        DAG.getConstant(2, dl, MVT::i64));
17316     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17317                                 MachinePointerInfo(TrmpAddr, 2),
17318                                 false, false, 2);
17319
17320     // Load the 'nest' parameter value into R10.
17321     // R10 is specified in X86CallingConv.td
17322     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17323     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17324                        DAG.getConstant(10, dl, MVT::i64));
17325     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17326                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17327                                 false, false, 0);
17328
17329     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17330                        DAG.getConstant(12, dl, MVT::i64));
17331     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17332                                 MachinePointerInfo(TrmpAddr, 12),
17333                                 false, false, 2);
17334
17335     // Jump to the nested function.
17336     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17337     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17338                        DAG.getConstant(20, dl, MVT::i64));
17339     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17340                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17341                                 false, false, 0);
17342
17343     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17344     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17345                        DAG.getConstant(22, dl, MVT::i64));
17346     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17347                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17348                                 false, false, 0);
17349
17350     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17351   } else {
17352     const Function *Func =
17353       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17354     CallingConv::ID CC = Func->getCallingConv();
17355     unsigned NestReg;
17356
17357     switch (CC) {
17358     default:
17359       llvm_unreachable("Unsupported calling convention");
17360     case CallingConv::C:
17361     case CallingConv::X86_StdCall: {
17362       // Pass 'nest' parameter in ECX.
17363       // Must be kept in sync with X86CallingConv.td
17364       NestReg = X86::ECX;
17365
17366       // Check that ECX wasn't needed by an 'inreg' parameter.
17367       FunctionType *FTy = Func->getFunctionType();
17368       const AttributeSet &Attrs = Func->getAttributes();
17369
17370       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17371         unsigned InRegCount = 0;
17372         unsigned Idx = 1;
17373
17374         for (FunctionType::param_iterator I = FTy->param_begin(),
17375              E = FTy->param_end(); I != E; ++I, ++Idx)
17376           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17377             auto &DL = DAG.getDataLayout();
17378             // FIXME: should only count parameters that are lowered to integers.
17379             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17380           }
17381
17382         if (InRegCount > 2) {
17383           report_fatal_error("Nest register in use - reduce number of inreg"
17384                              " parameters!");
17385         }
17386       }
17387       break;
17388     }
17389     case CallingConv::X86_FastCall:
17390     case CallingConv::X86_ThisCall:
17391     case CallingConv::Fast:
17392       // Pass 'nest' parameter in EAX.
17393       // Must be kept in sync with X86CallingConv.td
17394       NestReg = X86::EAX;
17395       break;
17396     }
17397
17398     SDValue OutChains[4];
17399     SDValue Addr, Disp;
17400
17401     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17402                        DAG.getConstant(10, dl, MVT::i32));
17403     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17404
17405     // This is storing the opcode for MOV32ri.
17406     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17407     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17408     OutChains[0] = DAG.getStore(Root, dl,
17409                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17410                                 Trmp, MachinePointerInfo(TrmpAddr),
17411                                 false, false, 0);
17412
17413     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17414                        DAG.getConstant(1, dl, MVT::i32));
17415     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17416                                 MachinePointerInfo(TrmpAddr, 1),
17417                                 false, false, 1);
17418
17419     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17420     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17421                        DAG.getConstant(5, dl, MVT::i32));
17422     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17423                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17424                                 false, false, 1);
17425
17426     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17427                        DAG.getConstant(6, dl, MVT::i32));
17428     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17429                                 MachinePointerInfo(TrmpAddr, 6),
17430                                 false, false, 1);
17431
17432     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17433   }
17434 }
17435
17436 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17437                                             SelectionDAG &DAG) const {
17438   /*
17439    The rounding mode is in bits 11:10 of FPSR, and has the following
17440    settings:
17441      00 Round to nearest
17442      01 Round to -inf
17443      10 Round to +inf
17444      11 Round to 0
17445
17446   FLT_ROUNDS, on the other hand, expects the following:
17447     -1 Undefined
17448      0 Round to 0
17449      1 Round to nearest
17450      2 Round to +inf
17451      3 Round to -inf
17452
17453   To perform the conversion, we do:
17454     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17455   */
17456
17457   MachineFunction &MF = DAG.getMachineFunction();
17458   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17459   unsigned StackAlignment = TFI.getStackAlignment();
17460   MVT VT = Op.getSimpleValueType();
17461   SDLoc DL(Op);
17462
17463   // Save FP Control Word to stack slot
17464   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17465   SDValue StackSlot =
17466       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17467
17468   MachineMemOperand *MMO =
17469       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17470                               MachineMemOperand::MOStore, 2, 2);
17471
17472   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17473   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17474                                           DAG.getVTList(MVT::Other),
17475                                           Ops, MVT::i16, MMO);
17476
17477   // Load FP Control Word from stack slot
17478   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17479                             MachinePointerInfo(), false, false, false, 0);
17480
17481   // Transform as necessary
17482   SDValue CWD1 =
17483     DAG.getNode(ISD::SRL, DL, MVT::i16,
17484                 DAG.getNode(ISD::AND, DL, MVT::i16,
17485                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17486                 DAG.getConstant(11, DL, MVT::i8));
17487   SDValue CWD2 =
17488     DAG.getNode(ISD::SRL, DL, MVT::i16,
17489                 DAG.getNode(ISD::AND, DL, MVT::i16,
17490                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17491                 DAG.getConstant(9, DL, MVT::i8));
17492
17493   SDValue RetVal =
17494     DAG.getNode(ISD::AND, DL, MVT::i16,
17495                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17496                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17497                             DAG.getConstant(1, DL, MVT::i16)),
17498                 DAG.getConstant(3, DL, MVT::i16));
17499
17500   return DAG.getNode((VT.getSizeInBits() < 16 ?
17501                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17502 }
17503
17504 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
17505   MVT VT = Op.getSimpleValueType();
17506   EVT OpVT = VT;
17507   unsigned NumBits = VT.getSizeInBits();
17508   SDLoc dl(Op);
17509
17510   Op = Op.getOperand(0);
17511   if (VT == MVT::i8) {
17512     // Zero extend to i32 since there is not an i8 bsr.
17513     OpVT = MVT::i32;
17514     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17515   }
17516
17517   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17518   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17519   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17520
17521   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17522   SDValue Ops[] = {
17523     Op,
17524     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17525     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17526     Op.getValue(1)
17527   };
17528   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17529
17530   // Finally xor with NumBits-1.
17531   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17532                    DAG.getConstant(NumBits - 1, dl, OpVT));
17533
17534   if (VT == MVT::i8)
17535     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17536   return Op;
17537 }
17538
17539 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17540   MVT VT = Op.getSimpleValueType();
17541   EVT OpVT = VT;
17542   unsigned NumBits = VT.getSizeInBits();
17543   SDLoc dl(Op);
17544
17545   Op = Op.getOperand(0);
17546   if (VT == MVT::i8) {
17547     // Zero extend to i32 since there is not an i8 bsr.
17548     OpVT = MVT::i32;
17549     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17550   }
17551
17552   // Issue a bsr (scan bits in reverse).
17553   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17554   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17555
17556   // And xor with NumBits-1.
17557   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17558                    DAG.getConstant(NumBits - 1, dl, OpVT));
17559
17560   if (VT == MVT::i8)
17561     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17562   return Op;
17563 }
17564
17565 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17566   MVT VT = Op.getSimpleValueType();
17567   unsigned NumBits = VT.getScalarSizeInBits();
17568   SDLoc dl(Op);
17569
17570   if (VT.isVector()) {
17571     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17572
17573     SDValue N0 = Op.getOperand(0);
17574     SDValue Zero = DAG.getConstant(0, dl, VT);
17575
17576     // lsb(x) = (x & -x)
17577     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
17578                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
17579
17580     // cttz_undef(x) = (width - 1) - ctlz(lsb)
17581     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
17582         TLI.isOperationLegal(ISD::CTLZ, VT)) {
17583       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
17584       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
17585                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
17586     }
17587
17588     // cttz(x) = ctpop(lsb - 1)
17589     SDValue One = DAG.getConstant(1, dl, VT);
17590     return DAG.getNode(ISD::CTPOP, dl, VT,
17591                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
17592   }
17593
17594   assert(Op.getOpcode() == ISD::CTTZ &&
17595          "Only scalar CTTZ requires custom lowering");
17596
17597   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17598   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17599   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
17600
17601   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17602   SDValue Ops[] = {
17603     Op,
17604     DAG.getConstant(NumBits, dl, VT),
17605     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17606     Op.getValue(1)
17607   };
17608   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17609 }
17610
17611 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17612 // ones, and then concatenate the result back.
17613 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17614   MVT VT = Op.getSimpleValueType();
17615
17616   assert(VT.is256BitVector() && VT.isInteger() &&
17617          "Unsupported value type for operation");
17618
17619   unsigned NumElems = VT.getVectorNumElements();
17620   SDLoc dl(Op);
17621
17622   // Extract the LHS vectors
17623   SDValue LHS = Op.getOperand(0);
17624   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17625   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17626
17627   // Extract the RHS vectors
17628   SDValue RHS = Op.getOperand(1);
17629   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17630   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17631
17632   MVT EltVT = VT.getVectorElementType();
17633   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17634
17635   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17636                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17637                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17638 }
17639
17640 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17641   if (Op.getValueType() == MVT::i1)
17642     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17643                        Op.getOperand(0), Op.getOperand(1));
17644   assert(Op.getSimpleValueType().is256BitVector() &&
17645          Op.getSimpleValueType().isInteger() &&
17646          "Only handle AVX 256-bit vector integer operation");
17647   return Lower256IntArith(Op, DAG);
17648 }
17649
17650 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17651   if (Op.getValueType() == MVT::i1)
17652     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17653                        Op.getOperand(0), Op.getOperand(1));
17654   assert(Op.getSimpleValueType().is256BitVector() &&
17655          Op.getSimpleValueType().isInteger() &&
17656          "Only handle AVX 256-bit vector integer operation");
17657   return Lower256IntArith(Op, DAG);
17658 }
17659
17660 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17661   assert(Op.getSimpleValueType().is256BitVector() &&
17662          Op.getSimpleValueType().isInteger() &&
17663          "Only handle AVX 256-bit vector integer operation");
17664   return Lower256IntArith(Op, DAG);
17665 }
17666
17667 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17668                         SelectionDAG &DAG) {
17669   SDLoc dl(Op);
17670   MVT VT = Op.getSimpleValueType();
17671
17672   if (VT == MVT::i1)
17673     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17674
17675   // Decompose 256-bit ops into smaller 128-bit ops.
17676   if (VT.is256BitVector() && !Subtarget->hasInt256())
17677     return Lower256IntArith(Op, DAG);
17678
17679   SDValue A = Op.getOperand(0);
17680   SDValue B = Op.getOperand(1);
17681
17682   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17683   // pairs, multiply and truncate.
17684   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17685     if (Subtarget->hasInt256()) {
17686       if (VT == MVT::v32i8) {
17687         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17688         SDValue Lo = DAG.getIntPtrConstant(0, dl);
17689         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17690         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17691         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17692         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17693         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17694         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17695                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17696                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17697       }
17698
17699       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17700       return DAG.getNode(
17701           ISD::TRUNCATE, dl, VT,
17702           DAG.getNode(ISD::MUL, dl, ExVT,
17703                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17704                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17705     }
17706
17707     assert(VT == MVT::v16i8 &&
17708            "Pre-AVX2 support only supports v16i8 multiplication");
17709     MVT ExVT = MVT::v8i16;
17710
17711     // Extract the lo parts and sign extend to i16
17712     SDValue ALo, BLo;
17713     if (Subtarget->hasSSE41()) {
17714       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17715       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17716     } else {
17717       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17718                               -1, 4, -1, 5, -1, 6, -1, 7};
17719       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17720       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17721       ALo = DAG.getBitcast(ExVT, ALo);
17722       BLo = DAG.getBitcast(ExVT, BLo);
17723       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17724       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17725     }
17726
17727     // Extract the hi parts and sign extend to i16
17728     SDValue AHi, BHi;
17729     if (Subtarget->hasSSE41()) {
17730       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17731                               -1, -1, -1, -1, -1, -1, -1, -1};
17732       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17733       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17734       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17735       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17736     } else {
17737       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17738                               -1, 12, -1, 13, -1, 14, -1, 15};
17739       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17740       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17741       AHi = DAG.getBitcast(ExVT, AHi);
17742       BHi = DAG.getBitcast(ExVT, BHi);
17743       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17744       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17745     }
17746
17747     // Multiply, mask the lower 8bits of the lo/hi results and pack
17748     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17749     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17750     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17751     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17752     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17753   }
17754
17755   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17756   if (VT == MVT::v4i32) {
17757     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17758            "Should not custom lower when pmuldq is available!");
17759
17760     // Extract the odd parts.
17761     static const int UnpackMask[] = { 1, -1, 3, -1 };
17762     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17763     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17764
17765     // Multiply the even parts.
17766     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17767     // Now multiply odd parts.
17768     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17769
17770     Evens = DAG.getBitcast(VT, Evens);
17771     Odds = DAG.getBitcast(VT, Odds);
17772
17773     // Merge the two vectors back together with a shuffle. This expands into 2
17774     // shuffles.
17775     static const int ShufMask[] = { 0, 4, 2, 6 };
17776     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17777   }
17778
17779   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17780          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17781
17782   //  Ahi = psrlqi(a, 32);
17783   //  Bhi = psrlqi(b, 32);
17784   //
17785   //  AloBlo = pmuludq(a, b);
17786   //  AloBhi = pmuludq(a, Bhi);
17787   //  AhiBlo = pmuludq(Ahi, b);
17788
17789   //  AloBhi = psllqi(AloBhi, 32);
17790   //  AhiBlo = psllqi(AhiBlo, 32);
17791   //  return AloBlo + AloBhi + AhiBlo;
17792
17793   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17794   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17795
17796   SDValue AhiBlo = Ahi;
17797   SDValue AloBhi = Bhi;
17798   // Bit cast to 32-bit vectors for MULUDQ
17799   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17800                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17801   A = DAG.getBitcast(MulVT, A);
17802   B = DAG.getBitcast(MulVT, B);
17803   Ahi = DAG.getBitcast(MulVT, Ahi);
17804   Bhi = DAG.getBitcast(MulVT, Bhi);
17805
17806   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17807   // After shifting right const values the result may be all-zero.
17808   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17809     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17810     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17811   }
17812   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17813     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17814     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17815   }
17816
17817   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17818   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17819 }
17820
17821 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17822   assert(Subtarget->isTargetWin64() && "Unexpected target");
17823   EVT VT = Op.getValueType();
17824   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17825          "Unexpected return type for lowering");
17826
17827   RTLIB::Libcall LC;
17828   bool isSigned;
17829   switch (Op->getOpcode()) {
17830   default: llvm_unreachable("Unexpected request for libcall!");
17831   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17832   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17833   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17834   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17835   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17836   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17837   }
17838
17839   SDLoc dl(Op);
17840   SDValue InChain = DAG.getEntryNode();
17841
17842   TargetLowering::ArgListTy Args;
17843   TargetLowering::ArgListEntry Entry;
17844   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17845     EVT ArgVT = Op->getOperand(i).getValueType();
17846     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17847            "Unexpected argument type for lowering");
17848     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17849     Entry.Node = StackPtr;
17850     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17851                            false, false, 16);
17852     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17853     Entry.Ty = PointerType::get(ArgTy,0);
17854     Entry.isSExt = false;
17855     Entry.isZExt = false;
17856     Args.push_back(Entry);
17857   }
17858
17859   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17860                                          getPointerTy(DAG.getDataLayout()));
17861
17862   TargetLowering::CallLoweringInfo CLI(DAG);
17863   CLI.setDebugLoc(dl).setChain(InChain)
17864     .setCallee(getLibcallCallingConv(LC),
17865                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17866                Callee, std::move(Args), 0)
17867     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17868
17869   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17870   return DAG.getBitcast(VT, CallInfo.first);
17871 }
17872
17873 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17874                              SelectionDAG &DAG) {
17875   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17876   EVT VT = Op0.getValueType();
17877   SDLoc dl(Op);
17878
17879   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17880          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17881
17882   // PMULxD operations multiply each even value (starting at 0) of LHS with
17883   // the related value of RHS and produce a widen result.
17884   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17885   // => <2 x i64> <ae|cg>
17886   //
17887   // In other word, to have all the results, we need to perform two PMULxD:
17888   // 1. one with the even values.
17889   // 2. one with the odd values.
17890   // To achieve #2, with need to place the odd values at an even position.
17891   //
17892   // Place the odd value at an even position (basically, shift all values 1
17893   // step to the left):
17894   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17895   // <a|b|c|d> => <b|undef|d|undef>
17896   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17897   // <e|f|g|h> => <f|undef|h|undef>
17898   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17899
17900   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17901   // ints.
17902   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17903   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17904   unsigned Opcode =
17905       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17906   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17907   // => <2 x i64> <ae|cg>
17908   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17909   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17910   // => <2 x i64> <bf|dh>
17911   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17912
17913   // Shuffle it back into the right order.
17914   SDValue Highs, Lows;
17915   if (VT == MVT::v8i32) {
17916     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17917     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17918     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17919     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17920   } else {
17921     const int HighMask[] = {1, 5, 3, 7};
17922     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17923     const int LowMask[] = {0, 4, 2, 6};
17924     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17925   }
17926
17927   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17928   // unsigned multiply.
17929   if (IsSigned && !Subtarget->hasSSE41()) {
17930     SDValue ShAmt = DAG.getConstant(
17931         31, dl,
17932         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17933     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17934                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17935     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17936                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17937
17938     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17939     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17940   }
17941
17942   // The first result of MUL_LOHI is actually the low value, followed by the
17943   // high value.
17944   SDValue Ops[] = {Lows, Highs};
17945   return DAG.getMergeValues(Ops, dl);
17946 }
17947
17948 // Return true if the required (according to Opcode) shift-imm form is natively
17949 // supported by the Subtarget
17950 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17951                                         unsigned Opcode) {
17952   if (VT.getScalarSizeInBits() < 16)
17953     return false;
17954
17955   if (VT.is512BitVector() &&
17956       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17957     return true;
17958
17959   bool LShift = VT.is128BitVector() ||
17960     (VT.is256BitVector() && Subtarget->hasInt256());
17961
17962   bool AShift = LShift && (Subtarget->hasVLX() ||
17963     (VT != MVT::v2i64 && VT != MVT::v4i64));
17964   return (Opcode == ISD::SRA) ? AShift : LShift;
17965 }
17966
17967 // The shift amount is a variable, but it is the same for all vector lanes.
17968 // These instructions are defined together with shift-immediate.
17969 static
17970 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17971                                       unsigned Opcode) {
17972   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17973 }
17974
17975 // Return true if the required (according to Opcode) variable-shift form is
17976 // natively supported by the Subtarget
17977 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17978                                     unsigned Opcode) {
17979
17980   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17981     return false;
17982
17983   // vXi16 supported only on AVX-512, BWI
17984   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17985     return false;
17986
17987   if (VT.is512BitVector() || Subtarget->hasVLX())
17988     return true;
17989
17990   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17991   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17992   return (Opcode == ISD::SRA) ? AShift : LShift;
17993 }
17994
17995 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17996                                          const X86Subtarget *Subtarget) {
17997   MVT VT = Op.getSimpleValueType();
17998   SDLoc dl(Op);
17999   SDValue R = Op.getOperand(0);
18000   SDValue Amt = Op.getOperand(1);
18001
18002   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18003     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18004
18005   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18006     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18007     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18008     SDValue Ex = DAG.getBitcast(ExVT, R);
18009
18010     if (ShiftAmt >= 32) {
18011       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18012       SDValue Upper =
18013           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18014       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18015                                                  ShiftAmt - 32, DAG);
18016       if (VT == MVT::v2i64)
18017         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18018       if (VT == MVT::v4i64)
18019         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18020                                   {9, 1, 11, 3, 13, 5, 15, 7});
18021     } else {
18022       // SRA upper i32, SHL whole i64 and select lower i32.
18023       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18024                                                  ShiftAmt, DAG);
18025       SDValue Lower =
18026           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18027       Lower = DAG.getBitcast(ExVT, Lower);
18028       if (VT == MVT::v2i64)
18029         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18030       if (VT == MVT::v4i64)
18031         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18032                                   {8, 1, 10, 3, 12, 5, 14, 7});
18033     }
18034     return DAG.getBitcast(VT, Ex);
18035   };
18036
18037   // Optimize shl/srl/sra with constant shift amount.
18038   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18039     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18040       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18041
18042       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18043         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18044
18045       // i64 SRA needs to be performed as partial shifts.
18046       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18047           Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18048         return ArithmeticShiftRight64(ShiftAmt);
18049
18050       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
18051         unsigned NumElts = VT.getVectorNumElements();
18052         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18053
18054         // Simple i8 add case
18055         if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18056           return DAG.getNode(ISD::ADD, dl, VT, R, R);
18057
18058         // ashr(R, 7)  === cmp_slt(R, 0)
18059         if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18060           SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18061           return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18062         }
18063
18064         // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18065         if (VT == MVT::v16i8 && Subtarget->hasXOP())
18066           return SDValue();
18067
18068         if (Op.getOpcode() == ISD::SHL) {
18069           // Make a large shift.
18070           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18071                                                    R, ShiftAmt, DAG);
18072           SHL = DAG.getBitcast(VT, SHL);
18073           // Zero out the rightmost bits.
18074           SmallVector<SDValue, 32> V(
18075               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
18076           return DAG.getNode(ISD::AND, dl, VT, SHL,
18077                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18078         }
18079         if (Op.getOpcode() == ISD::SRL) {
18080           // Make a large shift.
18081           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18082                                                    R, ShiftAmt, DAG);
18083           SRL = DAG.getBitcast(VT, SRL);
18084           // Zero out the leftmost bits.
18085           SmallVector<SDValue, 32> V(
18086               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
18087           return DAG.getNode(ISD::AND, dl, VT, SRL,
18088                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18089         }
18090         if (Op.getOpcode() == ISD::SRA) {
18091           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18092           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18093           SmallVector<SDValue, 32> V(NumElts,
18094                                      DAG.getConstant(128 >> ShiftAmt, dl,
18095                                                      MVT::i8));
18096           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18097           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18098           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18099           return Res;
18100         }
18101         llvm_unreachable("Unknown shift opcode.");
18102       }
18103     }
18104   }
18105
18106   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18107   if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18108       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18109
18110     // Peek through any splat that was introduced for i64 shift vectorization.
18111     int SplatIndex = -1;
18112     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18113       if (SVN->isSplat()) {
18114         SplatIndex = SVN->getSplatIndex();
18115         Amt = Amt.getOperand(0);
18116         assert(SplatIndex < (int)VT.getVectorNumElements() &&
18117                "Splat shuffle referencing second operand");
18118       }
18119
18120     if (Amt.getOpcode() != ISD::BITCAST ||
18121         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18122       return SDValue();
18123
18124     Amt = Amt.getOperand(0);
18125     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18126                      VT.getVectorNumElements();
18127     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18128     uint64_t ShiftAmt = 0;
18129     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18130     for (unsigned i = 0; i != Ratio; ++i) {
18131       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18132       if (!C)
18133         return SDValue();
18134       // 6 == Log2(64)
18135       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18136     }
18137
18138     // Check remaining shift amounts (if not a splat).
18139     if (SplatIndex < 0) {
18140       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18141         uint64_t ShAmt = 0;
18142         for (unsigned j = 0; j != Ratio; ++j) {
18143           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18144           if (!C)
18145             return SDValue();
18146           // 6 == Log2(64)
18147           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18148         }
18149         if (ShAmt != ShiftAmt)
18150           return SDValue();
18151       }
18152     }
18153
18154     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18155       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18156
18157     if (Op.getOpcode() == ISD::SRA)
18158       return ArithmeticShiftRight64(ShiftAmt);
18159   }
18160
18161   return SDValue();
18162 }
18163
18164 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18165                                         const X86Subtarget* Subtarget) {
18166   MVT VT = Op.getSimpleValueType();
18167   SDLoc dl(Op);
18168   SDValue R = Op.getOperand(0);
18169   SDValue Amt = Op.getOperand(1);
18170
18171   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18172     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18173
18174   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18175     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18176
18177   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18178     SDValue BaseShAmt;
18179     EVT EltVT = VT.getVectorElementType();
18180
18181     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18182       // Check if this build_vector node is doing a splat.
18183       // If so, then set BaseShAmt equal to the splat value.
18184       BaseShAmt = BV->getSplatValue();
18185       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18186         BaseShAmt = SDValue();
18187     } else {
18188       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18189         Amt = Amt.getOperand(0);
18190
18191       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18192       if (SVN && SVN->isSplat()) {
18193         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18194         SDValue InVec = Amt.getOperand(0);
18195         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18196           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
18197                  "Unexpected shuffle index found!");
18198           BaseShAmt = InVec.getOperand(SplatIdx);
18199         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18200            if (ConstantSDNode *C =
18201                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18202              if (C->getZExtValue() == SplatIdx)
18203                BaseShAmt = InVec.getOperand(1);
18204            }
18205         }
18206
18207         if (!BaseShAmt)
18208           // Avoid introducing an extract element from a shuffle.
18209           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18210                                   DAG.getIntPtrConstant(SplatIdx, dl));
18211       }
18212     }
18213
18214     if (BaseShAmt.getNode()) {
18215       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18216       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18217         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18218       else if (EltVT.bitsLT(MVT::i32))
18219         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18220
18221       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18222     }
18223   }
18224
18225   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18226   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
18227       Amt.getOpcode() == ISD::BITCAST &&
18228       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18229     Amt = Amt.getOperand(0);
18230     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18231                      VT.getVectorNumElements();
18232     std::vector<SDValue> Vals(Ratio);
18233     for (unsigned i = 0; i != Ratio; ++i)
18234       Vals[i] = Amt.getOperand(i);
18235     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18236       for (unsigned j = 0; j != Ratio; ++j)
18237         if (Vals[j] != Amt.getOperand(i + j))
18238           return SDValue();
18239     }
18240
18241     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18242       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18243   }
18244   return SDValue();
18245 }
18246
18247 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18248                           SelectionDAG &DAG) {
18249   MVT VT = Op.getSimpleValueType();
18250   SDLoc dl(Op);
18251   SDValue R = Op.getOperand(0);
18252   SDValue Amt = Op.getOperand(1);
18253
18254   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18255   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18256
18257   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18258     return V;
18259
18260   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18261     return V;
18262
18263   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18264     return Op;
18265
18266   // XOP has 128-bit variable logical/arithmetic shifts.
18267   // +ve/-ve Amt = shift left/right.
18268   if (Subtarget->hasXOP() &&
18269       (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18270        VT == MVT::v8i16 || VT == MVT::v16i8)) {
18271     if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18272       SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18273       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18274     }
18275     if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18276       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18277     if (Op.getOpcode() == ISD::SRA)
18278       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18279   }
18280
18281   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18282   // shifts per-lane and then shuffle the partial results back together.
18283   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18284     // Splat the shift amounts so the scalar shifts above will catch it.
18285     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18286     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18287     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18288     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18289     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18290   }
18291
18292   // i64 vector arithmetic shift can be emulated with the transform:
18293   // M = lshr(SIGN_BIT, Amt)
18294   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18295   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18296       Op.getOpcode() == ISD::SRA) {
18297     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18298     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18299     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18300     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18301     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18302     return R;
18303   }
18304
18305   // If possible, lower this packed shift into a vector multiply instead of
18306   // expanding it into a sequence of scalar shifts.
18307   // Do this only if the vector shift count is a constant build_vector.
18308   if (Op.getOpcode() == ISD::SHL &&
18309       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18310        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18311       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18312     SmallVector<SDValue, 8> Elts;
18313     EVT SVT = VT.getScalarType();
18314     unsigned SVTBits = SVT.getSizeInBits();
18315     const APInt &One = APInt(SVTBits, 1);
18316     unsigned NumElems = VT.getVectorNumElements();
18317
18318     for (unsigned i=0; i !=NumElems; ++i) {
18319       SDValue Op = Amt->getOperand(i);
18320       if (Op->getOpcode() == ISD::UNDEF) {
18321         Elts.push_back(Op);
18322         continue;
18323       }
18324
18325       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18326       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
18327       uint64_t ShAmt = C.getZExtValue();
18328       if (ShAmt >= SVTBits) {
18329         Elts.push_back(DAG.getUNDEF(SVT));
18330         continue;
18331       }
18332       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18333     }
18334     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18335     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18336   }
18337
18338   // Lower SHL with variable shift amount.
18339   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18340     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18341
18342     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18343                      DAG.getConstant(0x3f800000U, dl, VT));
18344     Op = DAG.getBitcast(MVT::v4f32, Op);
18345     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18346     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18347   }
18348
18349   // If possible, lower this shift as a sequence of two shifts by
18350   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18351   // Example:
18352   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18353   //
18354   // Could be rewritten as:
18355   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18356   //
18357   // The advantage is that the two shifts from the example would be
18358   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18359   // the vector shift into four scalar shifts plus four pairs of vector
18360   // insert/extract.
18361   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18362       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18363     unsigned TargetOpcode = X86ISD::MOVSS;
18364     bool CanBeSimplified;
18365     // The splat value for the first packed shift (the 'X' from the example).
18366     SDValue Amt1 = Amt->getOperand(0);
18367     // The splat value for the second packed shift (the 'Y' from the example).
18368     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18369                                         Amt->getOperand(2);
18370
18371     // See if it is possible to replace this node with a sequence of
18372     // two shifts followed by a MOVSS/MOVSD
18373     if (VT == MVT::v4i32) {
18374       // Check if it is legal to use a MOVSS.
18375       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18376                         Amt2 == Amt->getOperand(3);
18377       if (!CanBeSimplified) {
18378         // Otherwise, check if we can still simplify this node using a MOVSD.
18379         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18380                           Amt->getOperand(2) == Amt->getOperand(3);
18381         TargetOpcode = X86ISD::MOVSD;
18382         Amt2 = Amt->getOperand(2);
18383       }
18384     } else {
18385       // Do similar checks for the case where the machine value type
18386       // is MVT::v8i16.
18387       CanBeSimplified = Amt1 == Amt->getOperand(1);
18388       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18389         CanBeSimplified = Amt2 == Amt->getOperand(i);
18390
18391       if (!CanBeSimplified) {
18392         TargetOpcode = X86ISD::MOVSD;
18393         CanBeSimplified = true;
18394         Amt2 = Amt->getOperand(4);
18395         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18396           CanBeSimplified = Amt1 == Amt->getOperand(i);
18397         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18398           CanBeSimplified = Amt2 == Amt->getOperand(j);
18399       }
18400     }
18401
18402     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18403         isa<ConstantSDNode>(Amt2)) {
18404       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18405       EVT CastVT = MVT::v4i32;
18406       SDValue Splat1 =
18407         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18408       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18409       SDValue Splat2 =
18410         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18411       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18412       if (TargetOpcode == X86ISD::MOVSD)
18413         CastVT = MVT::v2i64;
18414       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18415       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18416       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18417                                             BitCast1, DAG);
18418       return DAG.getBitcast(VT, Result);
18419     }
18420   }
18421
18422   // v4i32 Non Uniform Shifts.
18423   // If the shift amount is constant we can shift each lane using the SSE2
18424   // immediate shifts, else we need to zero-extend each lane to the lower i64
18425   // and shift using the SSE2 variable shifts.
18426   // The separate results can then be blended together.
18427   if (VT == MVT::v4i32) {
18428     unsigned Opc = Op.getOpcode();
18429     SDValue Amt0, Amt1, Amt2, Amt3;
18430     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18431       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18432       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18433       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18434       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18435     } else {
18436       // ISD::SHL is handled above but we include it here for completeness.
18437       switch (Opc) {
18438       default:
18439         llvm_unreachable("Unknown target vector shift node");
18440       case ISD::SHL:
18441         Opc = X86ISD::VSHL;
18442         break;
18443       case ISD::SRL:
18444         Opc = X86ISD::VSRL;
18445         break;
18446       case ISD::SRA:
18447         Opc = X86ISD::VSRA;
18448         break;
18449       }
18450       // The SSE2 shifts use the lower i64 as the same shift amount for
18451       // all lanes and the upper i64 is ignored. These shuffle masks
18452       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18453       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18454       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18455       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18456       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18457       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18458     }
18459
18460     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18461     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18462     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18463     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18464     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18465     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18466     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18467   }
18468
18469   if (VT == MVT::v16i8 ||
18470       (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
18471     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18472     unsigned ShiftOpcode = Op->getOpcode();
18473
18474     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18475       // On SSE41 targets we make use of the fact that VSELECT lowers
18476       // to PBLENDVB which selects bytes based just on the sign bit.
18477       if (Subtarget->hasSSE41()) {
18478         V0 = DAG.getBitcast(VT, V0);
18479         V1 = DAG.getBitcast(VT, V1);
18480         Sel = DAG.getBitcast(VT, Sel);
18481         return DAG.getBitcast(SelVT,
18482                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18483       }
18484       // On pre-SSE41 targets we test for the sign bit by comparing to
18485       // zero - a negative value will set all bits of the lanes to true
18486       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18487       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18488       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18489       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18490     };
18491
18492     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18493     // We can safely do this using i16 shifts as we're only interested in
18494     // the 3 lower bits of each byte.
18495     Amt = DAG.getBitcast(ExtVT, Amt);
18496     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18497     Amt = DAG.getBitcast(VT, Amt);
18498
18499     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18500       // r = VSELECT(r, shift(r, 4), a);
18501       SDValue M =
18502           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18503       R = SignBitSelect(VT, Amt, M, R);
18504
18505       // a += a
18506       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18507
18508       // r = VSELECT(r, shift(r, 2), a);
18509       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18510       R = SignBitSelect(VT, Amt, M, R);
18511
18512       // a += a
18513       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18514
18515       // return VSELECT(r, shift(r, 1), a);
18516       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18517       R = SignBitSelect(VT, Amt, M, R);
18518       return R;
18519     }
18520
18521     if (Op->getOpcode() == ISD::SRA) {
18522       // For SRA we need to unpack each byte to the higher byte of a i16 vector
18523       // so we can correctly sign extend. We don't care what happens to the
18524       // lower byte.
18525       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18526       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18527       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18528       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18529       ALo = DAG.getBitcast(ExtVT, ALo);
18530       AHi = DAG.getBitcast(ExtVT, AHi);
18531       RLo = DAG.getBitcast(ExtVT, RLo);
18532       RHi = DAG.getBitcast(ExtVT, RHi);
18533
18534       // r = VSELECT(r, shift(r, 4), a);
18535       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18536                                 DAG.getConstant(4, dl, ExtVT));
18537       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18538                                 DAG.getConstant(4, dl, ExtVT));
18539       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18540       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18541
18542       // a += a
18543       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18544       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18545
18546       // r = VSELECT(r, shift(r, 2), a);
18547       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18548                         DAG.getConstant(2, dl, ExtVT));
18549       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18550                         DAG.getConstant(2, dl, ExtVT));
18551       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18552       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18553
18554       // a += a
18555       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18556       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18557
18558       // r = VSELECT(r, shift(r, 1), a);
18559       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18560                         DAG.getConstant(1, dl, ExtVT));
18561       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18562                         DAG.getConstant(1, dl, ExtVT));
18563       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18564       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18565
18566       // Logical shift the result back to the lower byte, leaving a zero upper
18567       // byte
18568       // meaning that we can safely pack with PACKUSWB.
18569       RLo =
18570           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18571       RHi =
18572           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18573       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18574     }
18575   }
18576
18577   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18578   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18579   // solution better.
18580   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18581     MVT ExtVT = MVT::v8i32;
18582     unsigned ExtOpc =
18583         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18584     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18585     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18586     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18587                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18588   }
18589
18590   if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
18591     MVT ExtVT = MVT::v8i32;
18592     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18593     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18594     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18595     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18596     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18597     ALo = DAG.getBitcast(ExtVT, ALo);
18598     AHi = DAG.getBitcast(ExtVT, AHi);
18599     RLo = DAG.getBitcast(ExtVT, RLo);
18600     RHi = DAG.getBitcast(ExtVT, RHi);
18601     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18602     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18603     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18604     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18605     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18606   }
18607
18608   if (VT == MVT::v8i16) {
18609     unsigned ShiftOpcode = Op->getOpcode();
18610
18611     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18612       // On SSE41 targets we make use of the fact that VSELECT lowers
18613       // to PBLENDVB which selects bytes based just on the sign bit.
18614       if (Subtarget->hasSSE41()) {
18615         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18616         V0 = DAG.getBitcast(ExtVT, V0);
18617         V1 = DAG.getBitcast(ExtVT, V1);
18618         Sel = DAG.getBitcast(ExtVT, Sel);
18619         return DAG.getBitcast(
18620             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18621       }
18622       // On pre-SSE41 targets we splat the sign bit - a negative value will
18623       // set all bits of the lanes to true and VSELECT uses that in
18624       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18625       SDValue C =
18626           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18627       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18628     };
18629
18630     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18631     if (Subtarget->hasSSE41()) {
18632       // On SSE41 targets we need to replicate the shift mask in both
18633       // bytes for PBLENDVB.
18634       Amt = DAG.getNode(
18635           ISD::OR, dl, VT,
18636           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18637           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18638     } else {
18639       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18640     }
18641
18642     // r = VSELECT(r, shift(r, 8), a);
18643     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18644     R = SignBitSelect(Amt, M, R);
18645
18646     // a += a
18647     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18648
18649     // r = VSELECT(r, shift(r, 4), a);
18650     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18651     R = SignBitSelect(Amt, M, R);
18652
18653     // a += a
18654     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18655
18656     // r = VSELECT(r, shift(r, 2), a);
18657     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18658     R = SignBitSelect(Amt, M, R);
18659
18660     // a += a
18661     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18662
18663     // return VSELECT(r, shift(r, 1), a);
18664     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18665     R = SignBitSelect(Amt, M, R);
18666     return R;
18667   }
18668
18669   // Decompose 256-bit shifts into smaller 128-bit shifts.
18670   if (VT.is256BitVector()) {
18671     unsigned NumElems = VT.getVectorNumElements();
18672     MVT EltVT = VT.getVectorElementType();
18673     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18674
18675     // Extract the two vectors
18676     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18677     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18678
18679     // Recreate the shift amount vectors
18680     SDValue Amt1, Amt2;
18681     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18682       // Constant shift amount
18683       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18684       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18685       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18686
18687       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18688       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18689     } else {
18690       // Variable shift amount
18691       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18692       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18693     }
18694
18695     // Issue new vector shifts for the smaller types
18696     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18697     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18698
18699     // Concatenate the result back
18700     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18701   }
18702
18703   return SDValue();
18704 }
18705
18706 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18707   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18708   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18709   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18710   // has only one use.
18711   SDNode *N = Op.getNode();
18712   SDValue LHS = N->getOperand(0);
18713   SDValue RHS = N->getOperand(1);
18714   unsigned BaseOp = 0;
18715   unsigned Cond = 0;
18716   SDLoc DL(Op);
18717   switch (Op.getOpcode()) {
18718   default: llvm_unreachable("Unknown ovf instruction!");
18719   case ISD::SADDO:
18720     // A subtract of one will be selected as a INC. Note that INC doesn't
18721     // set CF, so we can't do this for UADDO.
18722     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18723       if (C->isOne()) {
18724         BaseOp = X86ISD::INC;
18725         Cond = X86::COND_O;
18726         break;
18727       }
18728     BaseOp = X86ISD::ADD;
18729     Cond = X86::COND_O;
18730     break;
18731   case ISD::UADDO:
18732     BaseOp = X86ISD::ADD;
18733     Cond = X86::COND_B;
18734     break;
18735   case ISD::SSUBO:
18736     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18737     // set CF, so we can't do this for USUBO.
18738     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18739       if (C->isOne()) {
18740         BaseOp = X86ISD::DEC;
18741         Cond = X86::COND_O;
18742         break;
18743       }
18744     BaseOp = X86ISD::SUB;
18745     Cond = X86::COND_O;
18746     break;
18747   case ISD::USUBO:
18748     BaseOp = X86ISD::SUB;
18749     Cond = X86::COND_B;
18750     break;
18751   case ISD::SMULO:
18752     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18753     Cond = X86::COND_O;
18754     break;
18755   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18756     if (N->getValueType(0) == MVT::i8) {
18757       BaseOp = X86ISD::UMUL8;
18758       Cond = X86::COND_O;
18759       break;
18760     }
18761     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18762                                  MVT::i32);
18763     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18764
18765     SDValue SetCC =
18766       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18767                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18768                   SDValue(Sum.getNode(), 2));
18769
18770     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18771   }
18772   }
18773
18774   // Also sets EFLAGS.
18775   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18776   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18777
18778   SDValue SetCC =
18779     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18780                 DAG.getConstant(Cond, DL, MVT::i32),
18781                 SDValue(Sum.getNode(), 1));
18782
18783   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18784 }
18785
18786 /// Returns true if the operand type is exactly twice the native width, and
18787 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18788 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18789 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18790 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18791   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18792
18793   if (OpWidth == 64)
18794     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18795   else if (OpWidth == 128)
18796     return Subtarget->hasCmpxchg16b();
18797   else
18798     return false;
18799 }
18800
18801 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18802   return needsCmpXchgNb(SI->getValueOperand()->getType());
18803 }
18804
18805 // Note: this turns large loads into lock cmpxchg8b/16b.
18806 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18807 TargetLowering::AtomicExpansionKind
18808 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18809   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18810   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
18811                                                : AtomicExpansionKind::None;
18812 }
18813
18814 TargetLowering::AtomicExpansionKind
18815 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18816   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18817   Type *MemType = AI->getType();
18818
18819   // If the operand is too big, we must see if cmpxchg8/16b is available
18820   // and default to library calls otherwise.
18821   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18822     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
18823                                    : AtomicExpansionKind::None;
18824   }
18825
18826   AtomicRMWInst::BinOp Op = AI->getOperation();
18827   switch (Op) {
18828   default:
18829     llvm_unreachable("Unknown atomic operation");
18830   case AtomicRMWInst::Xchg:
18831   case AtomicRMWInst::Add:
18832   case AtomicRMWInst::Sub:
18833     // It's better to use xadd, xsub or xchg for these in all cases.
18834     return AtomicExpansionKind::None;
18835   case AtomicRMWInst::Or:
18836   case AtomicRMWInst::And:
18837   case AtomicRMWInst::Xor:
18838     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18839     // prefix to a normal instruction for these operations.
18840     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
18841                             : AtomicExpansionKind::None;
18842   case AtomicRMWInst::Nand:
18843   case AtomicRMWInst::Max:
18844   case AtomicRMWInst::Min:
18845   case AtomicRMWInst::UMax:
18846   case AtomicRMWInst::UMin:
18847     // These always require a non-trivial set of data operations on x86. We must
18848     // use a cmpxchg loop.
18849     return AtomicExpansionKind::CmpXChg;
18850   }
18851 }
18852
18853 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18854   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18855   // no-sse2). There isn't any reason to disable it if the target processor
18856   // supports it.
18857   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18858 }
18859
18860 LoadInst *
18861 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18862   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18863   Type *MemType = AI->getType();
18864   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18865   // there is no benefit in turning such RMWs into loads, and it is actually
18866   // harmful as it introduces a mfence.
18867   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18868     return nullptr;
18869
18870   auto Builder = IRBuilder<>(AI);
18871   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18872   auto SynchScope = AI->getSynchScope();
18873   // We must restrict the ordering to avoid generating loads with Release or
18874   // ReleaseAcquire orderings.
18875   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18876   auto Ptr = AI->getPointerOperand();
18877
18878   // Before the load we need a fence. Here is an example lifted from
18879   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18880   // is required:
18881   // Thread 0:
18882   //   x.store(1, relaxed);
18883   //   r1 = y.fetch_add(0, release);
18884   // Thread 1:
18885   //   y.fetch_add(42, acquire);
18886   //   r2 = x.load(relaxed);
18887   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18888   // lowered to just a load without a fence. A mfence flushes the store buffer,
18889   // making the optimization clearly correct.
18890   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18891   // otherwise, we might be able to be more aggressive on relaxed idempotent
18892   // rmw. In practice, they do not look useful, so we don't try to be
18893   // especially clever.
18894   if (SynchScope == SingleThread)
18895     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18896     // the IR level, so we must wrap it in an intrinsic.
18897     return nullptr;
18898
18899   if (!hasMFENCE(*Subtarget))
18900     // FIXME: it might make sense to use a locked operation here but on a
18901     // different cache-line to prevent cache-line bouncing. In practice it
18902     // is probably a small win, and x86 processors without mfence are rare
18903     // enough that we do not bother.
18904     return nullptr;
18905
18906   Function *MFence =
18907       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18908   Builder.CreateCall(MFence, {});
18909
18910   // Finally we can emit the atomic load.
18911   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18912           AI->getType()->getPrimitiveSizeInBits());
18913   Loaded->setAtomic(Order, SynchScope);
18914   AI->replaceAllUsesWith(Loaded);
18915   AI->eraseFromParent();
18916   return Loaded;
18917 }
18918
18919 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18920                                  SelectionDAG &DAG) {
18921   SDLoc dl(Op);
18922   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18923     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18924   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18925     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18926
18927   // The only fence that needs an instruction is a sequentially-consistent
18928   // cross-thread fence.
18929   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18930     if (hasMFENCE(*Subtarget))
18931       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18932
18933     SDValue Chain = Op.getOperand(0);
18934     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18935     SDValue Ops[] = {
18936       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18937       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18938       DAG.getRegister(0, MVT::i32),            // Index
18939       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18940       DAG.getRegister(0, MVT::i32),            // Segment.
18941       Zero,
18942       Chain
18943     };
18944     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18945     return SDValue(Res, 0);
18946   }
18947
18948   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18949   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18950 }
18951
18952 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18953                              SelectionDAG &DAG) {
18954   MVT T = Op.getSimpleValueType();
18955   SDLoc DL(Op);
18956   unsigned Reg = 0;
18957   unsigned size = 0;
18958   switch(T.SimpleTy) {
18959   default: llvm_unreachable("Invalid value type!");
18960   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18961   case MVT::i16: Reg = X86::AX;  size = 2; break;
18962   case MVT::i32: Reg = X86::EAX; size = 4; break;
18963   case MVT::i64:
18964     assert(Subtarget->is64Bit() && "Node not type legal!");
18965     Reg = X86::RAX; size = 8;
18966     break;
18967   }
18968   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18969                                   Op.getOperand(2), SDValue());
18970   SDValue Ops[] = { cpIn.getValue(0),
18971                     Op.getOperand(1),
18972                     Op.getOperand(3),
18973                     DAG.getTargetConstant(size, DL, MVT::i8),
18974                     cpIn.getValue(1) };
18975   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18976   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18977   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18978                                            Ops, T, MMO);
18979
18980   SDValue cpOut =
18981     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18982   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18983                                       MVT::i32, cpOut.getValue(2));
18984   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18985                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18986                                 EFLAGS);
18987
18988   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18989   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18990   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18991   return SDValue();
18992 }
18993
18994 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18995                             SelectionDAG &DAG) {
18996   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18997   MVT DstVT = Op.getSimpleValueType();
18998
18999   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19000     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19001     if (DstVT != MVT::f64)
19002       // This conversion needs to be expanded.
19003       return SDValue();
19004
19005     SDValue InVec = Op->getOperand(0);
19006     SDLoc dl(Op);
19007     unsigned NumElts = SrcVT.getVectorNumElements();
19008     EVT SVT = SrcVT.getVectorElementType();
19009
19010     // Widen the vector in input in the case of MVT::v2i32.
19011     // Example: from MVT::v2i32 to MVT::v4i32.
19012     SmallVector<SDValue, 16> Elts;
19013     for (unsigned i = 0, e = NumElts; i != e; ++i)
19014       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19015                                  DAG.getIntPtrConstant(i, dl)));
19016
19017     // Explicitly mark the extra elements as Undef.
19018     Elts.append(NumElts, DAG.getUNDEF(SVT));
19019
19020     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19021     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19022     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19023     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19024                        DAG.getIntPtrConstant(0, dl));
19025   }
19026
19027   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19028          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19029   assert((DstVT == MVT::i64 ||
19030           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19031          "Unexpected custom BITCAST");
19032   // i64 <=> MMX conversions are Legal.
19033   if (SrcVT==MVT::i64 && DstVT.isVector())
19034     return Op;
19035   if (DstVT==MVT::i64 && SrcVT.isVector())
19036     return Op;
19037   // MMX <=> MMX conversions are Legal.
19038   if (SrcVT.isVector() && DstVT.isVector())
19039     return Op;
19040   // All other conversions need to be expanded.
19041   return SDValue();
19042 }
19043
19044 /// Compute the horizontal sum of bytes in V for the elements of VT.
19045 ///
19046 /// Requires V to be a byte vector and VT to be an integer vector type with
19047 /// wider elements than V's type. The width of the elements of VT determines
19048 /// how many bytes of V are summed horizontally to produce each element of the
19049 /// result.
19050 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19051                                       const X86Subtarget *Subtarget,
19052                                       SelectionDAG &DAG) {
19053   SDLoc DL(V);
19054   MVT ByteVecVT = V.getSimpleValueType();
19055   MVT EltVT = VT.getVectorElementType();
19056   int NumElts = VT.getVectorNumElements();
19057   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19058          "Expected value to have byte element type.");
19059   assert(EltVT != MVT::i8 &&
19060          "Horizontal byte sum only makes sense for wider elements!");
19061   unsigned VecSize = VT.getSizeInBits();
19062   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19063
19064   // PSADBW instruction horizontally add all bytes and leave the result in i64
19065   // chunks, thus directly computes the pop count for v2i64 and v4i64.
19066   if (EltVT == MVT::i64) {
19067     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19068     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
19069     return DAG.getBitcast(VT, V);
19070   }
19071
19072   if (EltVT == MVT::i32) {
19073     // We unpack the low half and high half into i32s interleaved with zeros so
19074     // that we can use PSADBW to horizontally sum them. The most useful part of
19075     // this is that it lines up the results of two PSADBW instructions to be
19076     // two v2i64 vectors which concatenated are the 4 population counts. We can
19077     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19078     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19079     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19080     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19081
19082     // Do the horizontal sums into two v2i64s.
19083     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19084     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
19085                       DAG.getBitcast(ByteVecVT, Low), Zeros);
19086     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
19087                        DAG.getBitcast(ByteVecVT, High), Zeros);
19088
19089     // Merge them together.
19090     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19091     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19092                     DAG.getBitcast(ShortVecVT, Low),
19093                     DAG.getBitcast(ShortVecVT, High));
19094
19095     return DAG.getBitcast(VT, V);
19096   }
19097
19098   // The only element type left is i16.
19099   assert(EltVT == MVT::i16 && "Unknown how to handle type");
19100
19101   // To obtain pop count for each i16 element starting from the pop count for
19102   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19103   // right by 8. It is important to shift as i16s as i8 vector shift isn't
19104   // directly supported.
19105   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19106   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19107   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19108   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19109                   DAG.getBitcast(ByteVecVT, V));
19110   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19111 }
19112
19113 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19114                                         const X86Subtarget *Subtarget,
19115                                         SelectionDAG &DAG) {
19116   MVT VT = Op.getSimpleValueType();
19117   MVT EltVT = VT.getVectorElementType();
19118   unsigned VecSize = VT.getSizeInBits();
19119
19120   // Implement a lookup table in register by using an algorithm based on:
19121   // http://wm.ite.pl/articles/sse-popcount.html
19122   //
19123   // The general idea is that every lower byte nibble in the input vector is an
19124   // index into a in-register pre-computed pop count table. We then split up the
19125   // input vector in two new ones: (1) a vector with only the shifted-right
19126   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19127   // masked out higher ones) for each byte. PSHUB is used separately with both
19128   // to index the in-register table. Next, both are added and the result is a
19129   // i8 vector where each element contains the pop count for input byte.
19130   //
19131   // To obtain the pop count for elements != i8, we follow up with the same
19132   // approach and use additional tricks as described below.
19133   //
19134   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19135                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19136                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19137                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19138
19139   int NumByteElts = VecSize / 8;
19140   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19141   SDValue In = DAG.getBitcast(ByteVecVT, Op);
19142   SmallVector<SDValue, 16> LUTVec;
19143   for (int i = 0; i < NumByteElts; ++i)
19144     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19145   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19146   SmallVector<SDValue, 16> Mask0F(NumByteElts,
19147                                   DAG.getConstant(0x0F, DL, MVT::i8));
19148   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19149
19150   // High nibbles
19151   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19152   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19153   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19154
19155   // Low nibbles
19156   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19157
19158   // The input vector is used as the shuffle mask that index elements into the
19159   // LUT. After counting low and high nibbles, add the vector to obtain the
19160   // final pop count per i8 element.
19161   SDValue HighPopCnt =
19162       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19163   SDValue LowPopCnt =
19164       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19165   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19166
19167   if (EltVT == MVT::i8)
19168     return PopCnt;
19169
19170   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19171 }
19172
19173 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19174                                        const X86Subtarget *Subtarget,
19175                                        SelectionDAG &DAG) {
19176   MVT VT = Op.getSimpleValueType();
19177   assert(VT.is128BitVector() &&
19178          "Only 128-bit vector bitmath lowering supported.");
19179
19180   int VecSize = VT.getSizeInBits();
19181   MVT EltVT = VT.getVectorElementType();
19182   int Len = EltVT.getSizeInBits();
19183
19184   // This is the vectorized version of the "best" algorithm from
19185   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19186   // with a minor tweak to use a series of adds + shifts instead of vector
19187   // multiplications. Implemented for all integer vector types. We only use
19188   // this when we don't have SSSE3 which allows a LUT-based lowering that is
19189   // much faster, even faster than using native popcnt instructions.
19190
19191   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19192     MVT VT = V.getSimpleValueType();
19193     SmallVector<SDValue, 32> Shifters(
19194         VT.getVectorNumElements(),
19195         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19196     return DAG.getNode(OpCode, DL, VT, V,
19197                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19198   };
19199   auto GetMask = [&](SDValue V, APInt Mask) {
19200     MVT VT = V.getSimpleValueType();
19201     SmallVector<SDValue, 32> Masks(
19202         VT.getVectorNumElements(),
19203         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19204     return DAG.getNode(ISD::AND, DL, VT, V,
19205                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19206   };
19207
19208   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19209   // x86, so set the SRL type to have elements at least i16 wide. This is
19210   // correct because all of our SRLs are followed immediately by a mask anyways
19211   // that handles any bits that sneak into the high bits of the byte elements.
19212   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19213
19214   SDValue V = Op;
19215
19216   // v = v - ((v >> 1) & 0x55555555...)
19217   SDValue Srl =
19218       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19219   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19220   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19221
19222   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19223   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19224   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19225   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19226   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19227
19228   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19229   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19230   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19231   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19232
19233   // At this point, V contains the byte-wise population count, and we are
19234   // merely doing a horizontal sum if necessary to get the wider element
19235   // counts.
19236   if (EltVT == MVT::i8)
19237     return V;
19238
19239   return LowerHorizontalByteSum(
19240       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19241       DAG);
19242 }
19243
19244 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19245                                 SelectionDAG &DAG) {
19246   MVT VT = Op.getSimpleValueType();
19247   // FIXME: Need to add AVX-512 support here!
19248   assert((VT.is256BitVector() || VT.is128BitVector()) &&
19249          "Unknown CTPOP type to handle");
19250   SDLoc DL(Op.getNode());
19251   SDValue Op0 = Op.getOperand(0);
19252
19253   if (!Subtarget->hasSSSE3()) {
19254     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19255     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19256     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19257   }
19258
19259   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19260     unsigned NumElems = VT.getVectorNumElements();
19261
19262     // Extract each 128-bit vector, compute pop count and concat the result.
19263     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19264     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19265
19266     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19267                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19268                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19269   }
19270
19271   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19272 }
19273
19274 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19275                           SelectionDAG &DAG) {
19276   assert(Op.getValueType().isVector() &&
19277          "We only do custom lowering for vector population count.");
19278   return LowerVectorCTPOP(Op, Subtarget, DAG);
19279 }
19280
19281 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19282   SDNode *Node = Op.getNode();
19283   SDLoc dl(Node);
19284   EVT T = Node->getValueType(0);
19285   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19286                               DAG.getConstant(0, dl, T), Node->getOperand(2));
19287   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19288                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19289                        Node->getOperand(0),
19290                        Node->getOperand(1), negOp,
19291                        cast<AtomicSDNode>(Node)->getMemOperand(),
19292                        cast<AtomicSDNode>(Node)->getOrdering(),
19293                        cast<AtomicSDNode>(Node)->getSynchScope());
19294 }
19295
19296 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19297   SDNode *Node = Op.getNode();
19298   SDLoc dl(Node);
19299   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19300
19301   // Convert seq_cst store -> xchg
19302   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19303   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19304   //        (The only way to get a 16-byte store is cmpxchg16b)
19305   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19306   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19307       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19308     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19309                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19310                                  Node->getOperand(0),
19311                                  Node->getOperand(1), Node->getOperand(2),
19312                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19313                                  cast<AtomicSDNode>(Node)->getOrdering(),
19314                                  cast<AtomicSDNode>(Node)->getSynchScope());
19315     return Swap.getValue(1);
19316   }
19317   // Other atomic stores have a simple pattern.
19318   return Op;
19319 }
19320
19321 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19322   EVT VT = Op.getNode()->getSimpleValueType(0);
19323
19324   // Let legalize expand this if it isn't a legal type yet.
19325   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19326     return SDValue();
19327
19328   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19329
19330   unsigned Opc;
19331   bool ExtraOp = false;
19332   switch (Op.getOpcode()) {
19333   default: llvm_unreachable("Invalid code");
19334   case ISD::ADDC: Opc = X86ISD::ADD; break;
19335   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19336   case ISD::SUBC: Opc = X86ISD::SUB; break;
19337   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19338   }
19339
19340   if (!ExtraOp)
19341     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19342                        Op.getOperand(1));
19343   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19344                      Op.getOperand(1), Op.getOperand(2));
19345 }
19346
19347 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19348                             SelectionDAG &DAG) {
19349   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19350
19351   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19352   // which returns the values as { float, float } (in XMM0) or
19353   // { double, double } (which is returned in XMM0, XMM1).
19354   SDLoc dl(Op);
19355   SDValue Arg = Op.getOperand(0);
19356   EVT ArgVT = Arg.getValueType();
19357   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19358
19359   TargetLowering::ArgListTy Args;
19360   TargetLowering::ArgListEntry Entry;
19361
19362   Entry.Node = Arg;
19363   Entry.Ty = ArgTy;
19364   Entry.isSExt = false;
19365   Entry.isZExt = false;
19366   Args.push_back(Entry);
19367
19368   bool isF64 = ArgVT == MVT::f64;
19369   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19370   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19371   // the results are returned via SRet in memory.
19372   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19373   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19374   SDValue Callee =
19375       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19376
19377   Type *RetTy = isF64
19378     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19379     : (Type*)VectorType::get(ArgTy, 4);
19380
19381   TargetLowering::CallLoweringInfo CLI(DAG);
19382   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19383     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19384
19385   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19386
19387   if (isF64)
19388     // Returned in xmm0 and xmm1.
19389     return CallResult.first;
19390
19391   // Returned in bits 0:31 and 32:64 xmm0.
19392   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19393                                CallResult.first, DAG.getIntPtrConstant(0, dl));
19394   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19395                                CallResult.first, DAG.getIntPtrConstant(1, dl));
19396   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19397   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19398 }
19399
19400 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19401                              SelectionDAG &DAG) {
19402   assert(Subtarget->hasAVX512() &&
19403          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19404
19405   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19406   EVT VT = N->getValue().getValueType();
19407   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19408   SDLoc dl(Op);
19409
19410   // X86 scatter kills mask register, so its type should be added to
19411   // the list of return values
19412   if (N->getNumValues() == 1) {
19413     SDValue Index = N->getIndex();
19414     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19415         !Index.getValueType().is512BitVector())
19416       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19417
19418     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19419     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19420                       N->getOperand(3), Index };
19421
19422     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19423     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19424     return SDValue(NewScatter.getNode(), 0);
19425   }
19426   return Op;
19427 }
19428
19429 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19430                             SelectionDAG &DAG) {
19431   assert(Subtarget->hasAVX512() &&
19432          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19433
19434   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19435   EVT VT = Op.getValueType();
19436   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19437   SDLoc dl(Op);
19438
19439   SDValue Index = N->getIndex();
19440   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19441       !Index.getValueType().is512BitVector()) {
19442     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19443     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19444                       N->getOperand(3), Index };
19445     DAG.UpdateNodeOperands(N, Ops);
19446   }
19447   return Op;
19448 }
19449
19450 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19451                                                     SelectionDAG &DAG) const {
19452   // TODO: Eventually, the lowering of these nodes should be informed by or
19453   // deferred to the GC strategy for the function in which they appear. For
19454   // now, however, they must be lowered to something. Since they are logically
19455   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19456   // require special handling for these nodes), lower them as literal NOOPs for
19457   // the time being.
19458   SmallVector<SDValue, 2> Ops;
19459
19460   Ops.push_back(Op.getOperand(0));
19461   if (Op->getGluedNode())
19462     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19463
19464   SDLoc OpDL(Op);
19465   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19466   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19467
19468   return NOOP;
19469 }
19470
19471 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19472                                                   SelectionDAG &DAG) const {
19473   // TODO: Eventually, the lowering of these nodes should be informed by or
19474   // deferred to the GC strategy for the function in which they appear. For
19475   // now, however, they must be lowered to something. Since they are logically
19476   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19477   // require special handling for these nodes), lower them as literal NOOPs for
19478   // the time being.
19479   SmallVector<SDValue, 2> Ops;
19480
19481   Ops.push_back(Op.getOperand(0));
19482   if (Op->getGluedNode())
19483     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19484
19485   SDLoc OpDL(Op);
19486   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19487   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19488
19489   return NOOP;
19490 }
19491
19492 /// LowerOperation - Provide custom lowering hooks for some operations.
19493 ///
19494 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19495   switch (Op.getOpcode()) {
19496   default: llvm_unreachable("Should not custom lower this!");
19497   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19498   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19499     return LowerCMP_SWAP(Op, Subtarget, DAG);
19500   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
19501   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19502   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19503   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19504   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19505   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
19506   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19507   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19508   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19509   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19510   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19511   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19512   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19513   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19514   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19515   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19516   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19517   case ISD::SHL_PARTS:
19518   case ISD::SRA_PARTS:
19519   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19520   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19521   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19522   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19523   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19524   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19525   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19526   case ISD::SIGN_EXTEND_VECTOR_INREG:
19527     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19528   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19529   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19530   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19531   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19532   case ISD::FABS:
19533   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19534   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19535   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19536   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19537   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19538   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19539   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19540   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19541   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19542   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19543   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19544   case ISD::INTRINSIC_VOID:
19545   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19546   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19547   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19548   case ISD::FRAME_TO_ARGS_OFFSET:
19549                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19550   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19551   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19552   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19553   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19554   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19555   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19556   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19557   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
19558   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
19559   case ISD::CTTZ:
19560   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
19561   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19562   case ISD::UMUL_LOHI:
19563   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19564   case ISD::SRA:
19565   case ISD::SRL:
19566   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19567   case ISD::SADDO:
19568   case ISD::UADDO:
19569   case ISD::SSUBO:
19570   case ISD::USUBO:
19571   case ISD::SMULO:
19572   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19573   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19574   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19575   case ISD::ADDC:
19576   case ISD::ADDE:
19577   case ISD::SUBC:
19578   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19579   case ISD::ADD:                return LowerADD(Op, DAG);
19580   case ISD::SUB:                return LowerSUB(Op, DAG);
19581   case ISD::SMAX:
19582   case ISD::SMIN:
19583   case ISD::UMAX:
19584   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
19585   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19586   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
19587   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
19588   case ISD::GC_TRANSITION_START:
19589                                 return LowerGC_TRANSITION_START(Op, DAG);
19590   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
19591   }
19592 }
19593
19594 /// ReplaceNodeResults - Replace a node with an illegal result type
19595 /// with a new node built out of custom code.
19596 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19597                                            SmallVectorImpl<SDValue>&Results,
19598                                            SelectionDAG &DAG) const {
19599   SDLoc dl(N);
19600   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19601   switch (N->getOpcode()) {
19602   default:
19603     llvm_unreachable("Do not know how to custom type legalize this operation!");
19604   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19605   case X86ISD::FMINC:
19606   case X86ISD::FMIN:
19607   case X86ISD::FMAXC:
19608   case X86ISD::FMAX: {
19609     EVT VT = N->getValueType(0);
19610     if (VT != MVT::v2f32)
19611       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
19612     SDValue UNDEF = DAG.getUNDEF(VT);
19613     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19614                               N->getOperand(0), UNDEF);
19615     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19616                               N->getOperand(1), UNDEF);
19617     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19618     return;
19619   }
19620   case ISD::SIGN_EXTEND_INREG:
19621   case ISD::ADDC:
19622   case ISD::ADDE:
19623   case ISD::SUBC:
19624   case ISD::SUBE:
19625     // We don't want to expand or promote these.
19626     return;
19627   case ISD::SDIV:
19628   case ISD::UDIV:
19629   case ISD::SREM:
19630   case ISD::UREM:
19631   case ISD::SDIVREM:
19632   case ISD::UDIVREM: {
19633     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19634     Results.push_back(V);
19635     return;
19636   }
19637   case ISD::FP_TO_SINT:
19638   case ISD::FP_TO_UINT: {
19639     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19640
19641     std::pair<SDValue,SDValue> Vals =
19642         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19643     SDValue FIST = Vals.first, StackSlot = Vals.second;
19644     if (FIST.getNode()) {
19645       EVT VT = N->getValueType(0);
19646       // Return a load from the stack slot.
19647       if (StackSlot.getNode())
19648         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19649                                       MachinePointerInfo(),
19650                                       false, false, false, 0));
19651       else
19652         Results.push_back(FIST);
19653     }
19654     return;
19655   }
19656   case ISD::UINT_TO_FP: {
19657     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19658     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19659         N->getValueType(0) != MVT::v2f32)
19660       return;
19661     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19662                                  N->getOperand(0));
19663     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19664                                      MVT::f64);
19665     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19666     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19667                              DAG.getBitcast(MVT::v2i64, VBias));
19668     Or = DAG.getBitcast(MVT::v2f64, Or);
19669     // TODO: Are there any fast-math-flags to propagate here?
19670     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19671     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19672     return;
19673   }
19674   case ISD::FP_ROUND: {
19675     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19676         return;
19677     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19678     Results.push_back(V);
19679     return;
19680   }
19681   case ISD::FP_EXTEND: {
19682     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19683     // No other ValueType for FP_EXTEND should reach this point.
19684     assert(N->getValueType(0) == MVT::v2f32 &&
19685            "Do not know how to legalize this Node");
19686     return;
19687   }
19688   case ISD::INTRINSIC_W_CHAIN: {
19689     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19690     switch (IntNo) {
19691     default : llvm_unreachable("Do not know how to custom type "
19692                                "legalize this intrinsic operation!");
19693     case Intrinsic::x86_rdtsc:
19694       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19695                                      Results);
19696     case Intrinsic::x86_rdtscp:
19697       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19698                                      Results);
19699     case Intrinsic::x86_rdpmc:
19700       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19701     }
19702   }
19703   case ISD::READCYCLECOUNTER: {
19704     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19705                                    Results);
19706   }
19707   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19708     EVT T = N->getValueType(0);
19709     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19710     bool Regs64bit = T == MVT::i128;
19711     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19712     SDValue cpInL, cpInH;
19713     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19714                         DAG.getConstant(0, dl, HalfT));
19715     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19716                         DAG.getConstant(1, dl, HalfT));
19717     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19718                              Regs64bit ? X86::RAX : X86::EAX,
19719                              cpInL, SDValue());
19720     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19721                              Regs64bit ? X86::RDX : X86::EDX,
19722                              cpInH, cpInL.getValue(1));
19723     SDValue swapInL, swapInH;
19724     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19725                           DAG.getConstant(0, dl, HalfT));
19726     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19727                           DAG.getConstant(1, dl, HalfT));
19728     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19729                                Regs64bit ? X86::RBX : X86::EBX,
19730                                swapInL, cpInH.getValue(1));
19731     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19732                                Regs64bit ? X86::RCX : X86::ECX,
19733                                swapInH, swapInL.getValue(1));
19734     SDValue Ops[] = { swapInH.getValue(0),
19735                       N->getOperand(1),
19736                       swapInH.getValue(1) };
19737     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19738     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19739     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19740                                   X86ISD::LCMPXCHG8_DAG;
19741     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19742     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19743                                         Regs64bit ? X86::RAX : X86::EAX,
19744                                         HalfT, Result.getValue(1));
19745     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19746                                         Regs64bit ? X86::RDX : X86::EDX,
19747                                         HalfT, cpOutL.getValue(2));
19748     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19749
19750     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19751                                         MVT::i32, cpOutH.getValue(2));
19752     SDValue Success =
19753         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19754                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19755     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19756
19757     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19758     Results.push_back(Success);
19759     Results.push_back(EFLAGS.getValue(1));
19760     return;
19761   }
19762   case ISD::ATOMIC_SWAP:
19763   case ISD::ATOMIC_LOAD_ADD:
19764   case ISD::ATOMIC_LOAD_SUB:
19765   case ISD::ATOMIC_LOAD_AND:
19766   case ISD::ATOMIC_LOAD_OR:
19767   case ISD::ATOMIC_LOAD_XOR:
19768   case ISD::ATOMIC_LOAD_NAND:
19769   case ISD::ATOMIC_LOAD_MIN:
19770   case ISD::ATOMIC_LOAD_MAX:
19771   case ISD::ATOMIC_LOAD_UMIN:
19772   case ISD::ATOMIC_LOAD_UMAX:
19773   case ISD::ATOMIC_LOAD: {
19774     // Delegate to generic TypeLegalization. Situations we can really handle
19775     // should have already been dealt with by AtomicExpandPass.cpp.
19776     break;
19777   }
19778   case ISD::BITCAST: {
19779     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19780     EVT DstVT = N->getValueType(0);
19781     EVT SrcVT = N->getOperand(0)->getValueType(0);
19782
19783     if (SrcVT != MVT::f64 ||
19784         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19785       return;
19786
19787     unsigned NumElts = DstVT.getVectorNumElements();
19788     EVT SVT = DstVT.getVectorElementType();
19789     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19790     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19791                                    MVT::v2f64, N->getOperand(0));
19792     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19793
19794     if (ExperimentalVectorWideningLegalization) {
19795       // If we are legalizing vectors by widening, we already have the desired
19796       // legal vector type, just return it.
19797       Results.push_back(ToVecInt);
19798       return;
19799     }
19800
19801     SmallVector<SDValue, 8> Elts;
19802     for (unsigned i = 0, e = NumElts; i != e; ++i)
19803       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19804                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19805
19806     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19807   }
19808   }
19809 }
19810
19811 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19812   switch ((X86ISD::NodeType)Opcode) {
19813   case X86ISD::FIRST_NUMBER:       break;
19814   case X86ISD::BSF:                return "X86ISD::BSF";
19815   case X86ISD::BSR:                return "X86ISD::BSR";
19816   case X86ISD::SHLD:               return "X86ISD::SHLD";
19817   case X86ISD::SHRD:               return "X86ISD::SHRD";
19818   case X86ISD::FAND:               return "X86ISD::FAND";
19819   case X86ISD::FANDN:              return "X86ISD::FANDN";
19820   case X86ISD::FOR:                return "X86ISD::FOR";
19821   case X86ISD::FXOR:               return "X86ISD::FXOR";
19822   case X86ISD::FILD:               return "X86ISD::FILD";
19823   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19824   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19825   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19826   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19827   case X86ISD::FLD:                return "X86ISD::FLD";
19828   case X86ISD::FST:                return "X86ISD::FST";
19829   case X86ISD::CALL:               return "X86ISD::CALL";
19830   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19831   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19832   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19833   case X86ISD::BT:                 return "X86ISD::BT";
19834   case X86ISD::CMP:                return "X86ISD::CMP";
19835   case X86ISD::COMI:               return "X86ISD::COMI";
19836   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19837   case X86ISD::CMPM:               return "X86ISD::CMPM";
19838   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19839   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19840   case X86ISD::SETCC:              return "X86ISD::SETCC";
19841   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19842   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19843   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19844   case X86ISD::CMOV:               return "X86ISD::CMOV";
19845   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19846   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19847   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19848   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19849   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19850   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19851   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19852   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19853   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19854   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19855   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19856   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19857   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19858   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19859   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19860   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19861   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19862   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19863   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19864   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19865   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19866   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19867   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19868   case X86ISD::HADD:               return "X86ISD::HADD";
19869   case X86ISD::HSUB:               return "X86ISD::HSUB";
19870   case X86ISD::FHADD:              return "X86ISD::FHADD";
19871   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19872   case X86ISD::ABS:                return "X86ISD::ABS";
19873   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
19874   case X86ISD::FMAX:               return "X86ISD::FMAX";
19875   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19876   case X86ISD::FMIN:               return "X86ISD::FMIN";
19877   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19878   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19879   case X86ISD::FMINC:              return "X86ISD::FMINC";
19880   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19881   case X86ISD::FRCP:               return "X86ISD::FRCP";
19882   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19883   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19884   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19885   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19886   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19887   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19888   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19889   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19890   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19891   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19892   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19893   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19894   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19895   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19896   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19897   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19898   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19899   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19900   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19901   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19902   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19903   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19904   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19905   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19906   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19907   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19908   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19909   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19910   case X86ISD::VSHL:               return "X86ISD::VSHL";
19911   case X86ISD::VSRL:               return "X86ISD::VSRL";
19912   case X86ISD::VSRA:               return "X86ISD::VSRA";
19913   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19914   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19915   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19916   case X86ISD::CMPP:               return "X86ISD::CMPP";
19917   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19918   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19919   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19920   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19921   case X86ISD::ADD:                return "X86ISD::ADD";
19922   case X86ISD::SUB:                return "X86ISD::SUB";
19923   case X86ISD::ADC:                return "X86ISD::ADC";
19924   case X86ISD::SBB:                return "X86ISD::SBB";
19925   case X86ISD::SMUL:               return "X86ISD::SMUL";
19926   case X86ISD::UMUL:               return "X86ISD::UMUL";
19927   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19928   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19929   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19930   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19931   case X86ISD::INC:                return "X86ISD::INC";
19932   case X86ISD::DEC:                return "X86ISD::DEC";
19933   case X86ISD::OR:                 return "X86ISD::OR";
19934   case X86ISD::XOR:                return "X86ISD::XOR";
19935   case X86ISD::AND:                return "X86ISD::AND";
19936   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19937   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19938   case X86ISD::PTEST:              return "X86ISD::PTEST";
19939   case X86ISD::TESTP:              return "X86ISD::TESTP";
19940   case X86ISD::TESTM:              return "X86ISD::TESTM";
19941   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19942   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19943   case X86ISD::KTEST:              return "X86ISD::KTEST";
19944   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19945   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19946   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19947   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19948   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19949   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19950   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19951   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19952   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19953   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19954   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19955   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19956   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19957   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19958   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19959   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19960   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19961   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19962   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19963   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19964   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19965   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19966   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19967   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19968   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19969   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19970   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19971   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19972   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19973   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19974   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19975   case X86ISD::VPTERNLOG:          return "X86ISD::VPTERNLOG";
19976   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19977   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19978   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19979   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19980   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19981   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
19982   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19983   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19984   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19985   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19986   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19987   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19988   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19989   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19990   case X86ISD::SAHF:               return "X86ISD::SAHF";
19991   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19992   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19993   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19994   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19995   case X86ISD::VPROT:              return "X86ISD::VPROT";
19996   case X86ISD::VPROTI:             return "X86ISD::VPROTI";
19997   case X86ISD::VPSHA:              return "X86ISD::VPSHA";
19998   case X86ISD::VPSHL:              return "X86ISD::VPSHL";
19999   case X86ISD::VPCOM:              return "X86ISD::VPCOM";
20000   case X86ISD::VPCOMU:             return "X86ISD::VPCOMU";
20001   case X86ISD::FMADD:              return "X86ISD::FMADD";
20002   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
20003   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
20004   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
20005   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
20006   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
20007   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
20008   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
20009   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
20010   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
20011   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
20012   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
20013   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
20014   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
20015   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
20016   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
20017   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
20018   case X86ISD::XTEST:              return "X86ISD::XTEST";
20019   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
20020   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
20021   case X86ISD::SELECT:             return "X86ISD::SELECT";
20022   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
20023   case X86ISD::RCP28:              return "X86ISD::RCP28";
20024   case X86ISD::EXP2:               return "X86ISD::EXP2";
20025   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
20026   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
20027   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
20028   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
20029   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
20030   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
20031   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
20032   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
20033   case X86ISD::ADDS:               return "X86ISD::ADDS";
20034   case X86ISD::SUBS:               return "X86ISD::SUBS";
20035   case X86ISD::AVG:                return "X86ISD::AVG";
20036   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
20037   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
20038   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
20039   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
20040   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
20041   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
20042   }
20043   return nullptr;
20044 }
20045
20046 // isLegalAddressingMode - Return true if the addressing mode represented
20047 // by AM is legal for this target, for a load/store of the specified type.
20048 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20049                                               const AddrMode &AM, Type *Ty,
20050                                               unsigned AS) const {
20051   // X86 supports extremely general addressing modes.
20052   CodeModel::Model M = getTargetMachine().getCodeModel();
20053   Reloc::Model R = getTargetMachine().getRelocationModel();
20054
20055   // X86 allows a sign-extended 32-bit immediate field as a displacement.
20056   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20057     return false;
20058
20059   if (AM.BaseGV) {
20060     unsigned GVFlags =
20061       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20062
20063     // If a reference to this global requires an extra load, we can't fold it.
20064     if (isGlobalStubReference(GVFlags))
20065       return false;
20066
20067     // If BaseGV requires a register for the PIC base, we cannot also have a
20068     // BaseReg specified.
20069     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20070       return false;
20071
20072     // If lower 4G is not available, then we must use rip-relative addressing.
20073     if ((M != CodeModel::Small || R != Reloc::Static) &&
20074         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20075       return false;
20076   }
20077
20078   switch (AM.Scale) {
20079   case 0:
20080   case 1:
20081   case 2:
20082   case 4:
20083   case 8:
20084     // These scales always work.
20085     break;
20086   case 3:
20087   case 5:
20088   case 9:
20089     // These scales are formed with basereg+scalereg.  Only accept if there is
20090     // no basereg yet.
20091     if (AM.HasBaseReg)
20092       return false;
20093     break;
20094   default:  // Other stuff never works.
20095     return false;
20096   }
20097
20098   return true;
20099 }
20100
20101 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20102   unsigned Bits = Ty->getScalarSizeInBits();
20103
20104   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20105   // particularly cheaper than those without.
20106   if (Bits == 8)
20107     return false;
20108
20109   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20110   // variable shifts just as cheap as scalar ones.
20111   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20112     return false;
20113
20114   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20115   // fully general vector.
20116   return true;
20117 }
20118
20119 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20120   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20121     return false;
20122   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20123   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20124   return NumBits1 > NumBits2;
20125 }
20126
20127 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20128   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20129     return false;
20130
20131   if (!isTypeLegal(EVT::getEVT(Ty1)))
20132     return false;
20133
20134   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20135
20136   // Assuming the caller doesn't have a zeroext or signext return parameter,
20137   // truncation all the way down to i1 is valid.
20138   return true;
20139 }
20140
20141 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20142   return isInt<32>(Imm);
20143 }
20144
20145 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20146   // Can also use sub to handle negated immediates.
20147   return isInt<32>(Imm);
20148 }
20149
20150 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20151   if (!VT1.isInteger() || !VT2.isInteger())
20152     return false;
20153   unsigned NumBits1 = VT1.getSizeInBits();
20154   unsigned NumBits2 = VT2.getSizeInBits();
20155   return NumBits1 > NumBits2;
20156 }
20157
20158 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20159   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20160   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20161 }
20162
20163 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20164   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20165   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20166 }
20167
20168 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20169   EVT VT1 = Val.getValueType();
20170   if (isZExtFree(VT1, VT2))
20171     return true;
20172
20173   if (Val.getOpcode() != ISD::LOAD)
20174     return false;
20175
20176   if (!VT1.isSimple() || !VT1.isInteger() ||
20177       !VT2.isSimple() || !VT2.isInteger())
20178     return false;
20179
20180   switch (VT1.getSimpleVT().SimpleTy) {
20181   default: break;
20182   case MVT::i8:
20183   case MVT::i16:
20184   case MVT::i32:
20185     // X86 has 8, 16, and 32-bit zero-extending loads.
20186     return true;
20187   }
20188
20189   return false;
20190 }
20191
20192 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
20193
20194 bool
20195 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20196   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
20197     return false;
20198
20199   VT = VT.getScalarType();
20200
20201   if (!VT.isSimple())
20202     return false;
20203
20204   switch (VT.getSimpleVT().SimpleTy) {
20205   case MVT::f32:
20206   case MVT::f64:
20207     return true;
20208   default:
20209     break;
20210   }
20211
20212   return false;
20213 }
20214
20215 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20216   // i16 instructions are longer (0x66 prefix) and potentially slower.
20217   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20218 }
20219
20220 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20221 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20222 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20223 /// are assumed to be legal.
20224 bool
20225 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20226                                       EVT VT) const {
20227   if (!VT.isSimple())
20228     return false;
20229
20230   // Not for i1 vectors
20231   if (VT.getScalarType() == MVT::i1)
20232     return false;
20233
20234   // Very little shuffling can be done for 64-bit vectors right now.
20235   if (VT.getSizeInBits() == 64)
20236     return false;
20237
20238   // We only care that the types being shuffled are legal. The lowering can
20239   // handle any possible shuffle mask that results.
20240   return isTypeLegal(VT.getSimpleVT());
20241 }
20242
20243 bool
20244 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20245                                           EVT VT) const {
20246   // Just delegate to the generic legality, clear masks aren't special.
20247   return isShuffleMaskLegal(Mask, VT);
20248 }
20249
20250 //===----------------------------------------------------------------------===//
20251 //                           X86 Scheduler Hooks
20252 //===----------------------------------------------------------------------===//
20253
20254 /// Utility function to emit xbegin specifying the start of an RTM region.
20255 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20256                                      const TargetInstrInfo *TII) {
20257   DebugLoc DL = MI->getDebugLoc();
20258
20259   const BasicBlock *BB = MBB->getBasicBlock();
20260   MachineFunction::iterator I = MBB;
20261   ++I;
20262
20263   // For the v = xbegin(), we generate
20264   //
20265   // thisMBB:
20266   //  xbegin sinkMBB
20267   //
20268   // mainMBB:
20269   //  eax = -1
20270   //
20271   // sinkMBB:
20272   //  v = eax
20273
20274   MachineBasicBlock *thisMBB = MBB;
20275   MachineFunction *MF = MBB->getParent();
20276   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20277   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20278   MF->insert(I, mainMBB);
20279   MF->insert(I, sinkMBB);
20280
20281   // Transfer the remainder of BB and its successor edges to sinkMBB.
20282   sinkMBB->splice(sinkMBB->begin(), MBB,
20283                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20284   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20285
20286   // thisMBB:
20287   //  xbegin sinkMBB
20288   //  # fallthrough to mainMBB
20289   //  # abortion to sinkMBB
20290   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20291   thisMBB->addSuccessor(mainMBB);
20292   thisMBB->addSuccessor(sinkMBB);
20293
20294   // mainMBB:
20295   //  EAX = -1
20296   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20297   mainMBB->addSuccessor(sinkMBB);
20298
20299   // sinkMBB:
20300   // EAX is live into the sinkMBB
20301   sinkMBB->addLiveIn(X86::EAX);
20302   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20303           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20304     .addReg(X86::EAX);
20305
20306   MI->eraseFromParent();
20307   return sinkMBB;
20308 }
20309
20310 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20311 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20312 // in the .td file.
20313 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20314                                        const TargetInstrInfo *TII) {
20315   unsigned Opc;
20316   switch (MI->getOpcode()) {
20317   default: llvm_unreachable("illegal opcode!");
20318   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
20319   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20320   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
20321   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20322   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
20323   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20324   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
20325   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20326   }
20327
20328   DebugLoc dl = MI->getDebugLoc();
20329   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20330
20331   unsigned NumArgs = MI->getNumOperands();
20332   for (unsigned i = 1; i < NumArgs; ++i) {
20333     MachineOperand &Op = MI->getOperand(i);
20334     if (!(Op.isReg() && Op.isImplicit()))
20335       MIB.addOperand(Op);
20336   }
20337   if (MI->hasOneMemOperand())
20338     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20339
20340   BuildMI(*BB, MI, dl,
20341     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20342     .addReg(X86::XMM0);
20343
20344   MI->eraseFromParent();
20345   return BB;
20346 }
20347
20348 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20349 // defs in an instruction pattern
20350 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20351                                        const TargetInstrInfo *TII) {
20352   unsigned Opc;
20353   switch (MI->getOpcode()) {
20354   default: llvm_unreachable("illegal opcode!");
20355   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
20356   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20357   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
20358   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20359   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
20360   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20361   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
20362   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20363   }
20364
20365   DebugLoc dl = MI->getDebugLoc();
20366   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20367
20368   unsigned NumArgs = MI->getNumOperands(); // remove the results
20369   for (unsigned i = 1; i < NumArgs; ++i) {
20370     MachineOperand &Op = MI->getOperand(i);
20371     if (!(Op.isReg() && Op.isImplicit()))
20372       MIB.addOperand(Op);
20373   }
20374   if (MI->hasOneMemOperand())
20375     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20376
20377   BuildMI(*BB, MI, dl,
20378     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20379     .addReg(X86::ECX);
20380
20381   MI->eraseFromParent();
20382   return BB;
20383 }
20384
20385 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20386                                       const X86Subtarget *Subtarget) {
20387   DebugLoc dl = MI->getDebugLoc();
20388   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20389   // Address into RAX/EAX, other two args into ECX, EDX.
20390   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20391   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20392   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20393   for (int i = 0; i < X86::AddrNumOperands; ++i)
20394     MIB.addOperand(MI->getOperand(i));
20395
20396   unsigned ValOps = X86::AddrNumOperands;
20397   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20398     .addReg(MI->getOperand(ValOps).getReg());
20399   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20400     .addReg(MI->getOperand(ValOps+1).getReg());
20401
20402   // The instruction doesn't actually take any operands though.
20403   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20404
20405   MI->eraseFromParent(); // The pseudo is gone now.
20406   return BB;
20407 }
20408
20409 MachineBasicBlock *
20410 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20411                                                  MachineBasicBlock *MBB) const {
20412   // Emit va_arg instruction on X86-64.
20413
20414   // Operands to this pseudo-instruction:
20415   // 0  ) Output        : destination address (reg)
20416   // 1-5) Input         : va_list address (addr, i64mem)
20417   // 6  ) ArgSize       : Size (in bytes) of vararg type
20418   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20419   // 8  ) Align         : Alignment of type
20420   // 9  ) EFLAGS (implicit-def)
20421
20422   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20423   static_assert(X86::AddrNumOperands == 5,
20424                 "VAARG_64 assumes 5 address operands");
20425
20426   unsigned DestReg = MI->getOperand(0).getReg();
20427   MachineOperand &Base = MI->getOperand(1);
20428   MachineOperand &Scale = MI->getOperand(2);
20429   MachineOperand &Index = MI->getOperand(3);
20430   MachineOperand &Disp = MI->getOperand(4);
20431   MachineOperand &Segment = MI->getOperand(5);
20432   unsigned ArgSize = MI->getOperand(6).getImm();
20433   unsigned ArgMode = MI->getOperand(7).getImm();
20434   unsigned Align = MI->getOperand(8).getImm();
20435
20436   // Memory Reference
20437   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20438   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20439   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20440
20441   // Machine Information
20442   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20443   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20444   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20445   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20446   DebugLoc DL = MI->getDebugLoc();
20447
20448   // struct va_list {
20449   //   i32   gp_offset
20450   //   i32   fp_offset
20451   //   i64   overflow_area (address)
20452   //   i64   reg_save_area (address)
20453   // }
20454   // sizeof(va_list) = 24
20455   // alignment(va_list) = 8
20456
20457   unsigned TotalNumIntRegs = 6;
20458   unsigned TotalNumXMMRegs = 8;
20459   bool UseGPOffset = (ArgMode == 1);
20460   bool UseFPOffset = (ArgMode == 2);
20461   unsigned MaxOffset = TotalNumIntRegs * 8 +
20462                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20463
20464   /* Align ArgSize to a multiple of 8 */
20465   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20466   bool NeedsAlign = (Align > 8);
20467
20468   MachineBasicBlock *thisMBB = MBB;
20469   MachineBasicBlock *overflowMBB;
20470   MachineBasicBlock *offsetMBB;
20471   MachineBasicBlock *endMBB;
20472
20473   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20474   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20475   unsigned OffsetReg = 0;
20476
20477   if (!UseGPOffset && !UseFPOffset) {
20478     // If we only pull from the overflow region, we don't create a branch.
20479     // We don't need to alter control flow.
20480     OffsetDestReg = 0; // unused
20481     OverflowDestReg = DestReg;
20482
20483     offsetMBB = nullptr;
20484     overflowMBB = thisMBB;
20485     endMBB = thisMBB;
20486   } else {
20487     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20488     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20489     // If not, pull from overflow_area. (branch to overflowMBB)
20490     //
20491     //       thisMBB
20492     //         |     .
20493     //         |        .
20494     //     offsetMBB   overflowMBB
20495     //         |        .
20496     //         |     .
20497     //        endMBB
20498
20499     // Registers for the PHI in endMBB
20500     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20501     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20502
20503     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20504     MachineFunction *MF = MBB->getParent();
20505     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20506     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20507     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20508
20509     MachineFunction::iterator MBBIter = MBB;
20510     ++MBBIter;
20511
20512     // Insert the new basic blocks
20513     MF->insert(MBBIter, offsetMBB);
20514     MF->insert(MBBIter, overflowMBB);
20515     MF->insert(MBBIter, endMBB);
20516
20517     // Transfer the remainder of MBB and its successor edges to endMBB.
20518     endMBB->splice(endMBB->begin(), thisMBB,
20519                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20520     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20521
20522     // Make offsetMBB and overflowMBB successors of thisMBB
20523     thisMBB->addSuccessor(offsetMBB);
20524     thisMBB->addSuccessor(overflowMBB);
20525
20526     // endMBB is a successor of both offsetMBB and overflowMBB
20527     offsetMBB->addSuccessor(endMBB);
20528     overflowMBB->addSuccessor(endMBB);
20529
20530     // Load the offset value into a register
20531     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20532     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20533       .addOperand(Base)
20534       .addOperand(Scale)
20535       .addOperand(Index)
20536       .addDisp(Disp, UseFPOffset ? 4 : 0)
20537       .addOperand(Segment)
20538       .setMemRefs(MMOBegin, MMOEnd);
20539
20540     // Check if there is enough room left to pull this argument.
20541     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20542       .addReg(OffsetReg)
20543       .addImm(MaxOffset + 8 - ArgSizeA8);
20544
20545     // Branch to "overflowMBB" if offset >= max
20546     // Fall through to "offsetMBB" otherwise
20547     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20548       .addMBB(overflowMBB);
20549   }
20550
20551   // In offsetMBB, emit code to use the reg_save_area.
20552   if (offsetMBB) {
20553     assert(OffsetReg != 0);
20554
20555     // Read the reg_save_area address.
20556     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20557     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20558       .addOperand(Base)
20559       .addOperand(Scale)
20560       .addOperand(Index)
20561       .addDisp(Disp, 16)
20562       .addOperand(Segment)
20563       .setMemRefs(MMOBegin, MMOEnd);
20564
20565     // Zero-extend the offset
20566     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20567       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20568         .addImm(0)
20569         .addReg(OffsetReg)
20570         .addImm(X86::sub_32bit);
20571
20572     // Add the offset to the reg_save_area to get the final address.
20573     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20574       .addReg(OffsetReg64)
20575       .addReg(RegSaveReg);
20576
20577     // Compute the offset for the next argument
20578     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20579     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20580       .addReg(OffsetReg)
20581       .addImm(UseFPOffset ? 16 : 8);
20582
20583     // Store it back into the va_list.
20584     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20585       .addOperand(Base)
20586       .addOperand(Scale)
20587       .addOperand(Index)
20588       .addDisp(Disp, UseFPOffset ? 4 : 0)
20589       .addOperand(Segment)
20590       .addReg(NextOffsetReg)
20591       .setMemRefs(MMOBegin, MMOEnd);
20592
20593     // Jump to endMBB
20594     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20595       .addMBB(endMBB);
20596   }
20597
20598   //
20599   // Emit code to use overflow area
20600   //
20601
20602   // Load the overflow_area address into a register.
20603   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20604   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20605     .addOperand(Base)
20606     .addOperand(Scale)
20607     .addOperand(Index)
20608     .addDisp(Disp, 8)
20609     .addOperand(Segment)
20610     .setMemRefs(MMOBegin, MMOEnd);
20611
20612   // If we need to align it, do so. Otherwise, just copy the address
20613   // to OverflowDestReg.
20614   if (NeedsAlign) {
20615     // Align the overflow address
20616     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20617     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20618
20619     // aligned_addr = (addr + (align-1)) & ~(align-1)
20620     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20621       .addReg(OverflowAddrReg)
20622       .addImm(Align-1);
20623
20624     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20625       .addReg(TmpReg)
20626       .addImm(~(uint64_t)(Align-1));
20627   } else {
20628     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20629       .addReg(OverflowAddrReg);
20630   }
20631
20632   // Compute the next overflow address after this argument.
20633   // (the overflow address should be kept 8-byte aligned)
20634   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20635   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20636     .addReg(OverflowDestReg)
20637     .addImm(ArgSizeA8);
20638
20639   // Store the new overflow address.
20640   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20641     .addOperand(Base)
20642     .addOperand(Scale)
20643     .addOperand(Index)
20644     .addDisp(Disp, 8)
20645     .addOperand(Segment)
20646     .addReg(NextAddrReg)
20647     .setMemRefs(MMOBegin, MMOEnd);
20648
20649   // If we branched, emit the PHI to the front of endMBB.
20650   if (offsetMBB) {
20651     BuildMI(*endMBB, endMBB->begin(), DL,
20652             TII->get(X86::PHI), DestReg)
20653       .addReg(OffsetDestReg).addMBB(offsetMBB)
20654       .addReg(OverflowDestReg).addMBB(overflowMBB);
20655   }
20656
20657   // Erase the pseudo instruction
20658   MI->eraseFromParent();
20659
20660   return endMBB;
20661 }
20662
20663 MachineBasicBlock *
20664 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20665                                                  MachineInstr *MI,
20666                                                  MachineBasicBlock *MBB) const {
20667   // Emit code to save XMM registers to the stack. The ABI says that the
20668   // number of registers to save is given in %al, so it's theoretically
20669   // possible to do an indirect jump trick to avoid saving all of them,
20670   // however this code takes a simpler approach and just executes all
20671   // of the stores if %al is non-zero. It's less code, and it's probably
20672   // easier on the hardware branch predictor, and stores aren't all that
20673   // expensive anyway.
20674
20675   // Create the new basic blocks. One block contains all the XMM stores,
20676   // and one block is the final destination regardless of whether any
20677   // stores were performed.
20678   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20679   MachineFunction *F = MBB->getParent();
20680   MachineFunction::iterator MBBIter = MBB;
20681   ++MBBIter;
20682   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20683   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20684   F->insert(MBBIter, XMMSaveMBB);
20685   F->insert(MBBIter, EndMBB);
20686
20687   // Transfer the remainder of MBB and its successor edges to EndMBB.
20688   EndMBB->splice(EndMBB->begin(), MBB,
20689                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20690   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20691
20692   // The original block will now fall through to the XMM save block.
20693   MBB->addSuccessor(XMMSaveMBB);
20694   // The XMMSaveMBB will fall through to the end block.
20695   XMMSaveMBB->addSuccessor(EndMBB);
20696
20697   // Now add the instructions.
20698   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20699   DebugLoc DL = MI->getDebugLoc();
20700
20701   unsigned CountReg = MI->getOperand(0).getReg();
20702   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20703   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20704
20705   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20706     // If %al is 0, branch around the XMM save block.
20707     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20708     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20709     MBB->addSuccessor(EndMBB);
20710   }
20711
20712   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20713   // that was just emitted, but clearly shouldn't be "saved".
20714   assert((MI->getNumOperands() <= 3 ||
20715           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20716           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20717          && "Expected last argument to be EFLAGS");
20718   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20719   // In the XMM save block, save all the XMM argument registers.
20720   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20721     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20722     MachineMemOperand *MMO = F->getMachineMemOperand(
20723         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20724         MachineMemOperand::MOStore,
20725         /*Size=*/16, /*Align=*/16);
20726     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20727       .addFrameIndex(RegSaveFrameIndex)
20728       .addImm(/*Scale=*/1)
20729       .addReg(/*IndexReg=*/0)
20730       .addImm(/*Disp=*/Offset)
20731       .addReg(/*Segment=*/0)
20732       .addReg(MI->getOperand(i).getReg())
20733       .addMemOperand(MMO);
20734   }
20735
20736   MI->eraseFromParent();   // The pseudo instruction is gone now.
20737
20738   return EndMBB;
20739 }
20740
20741 // The EFLAGS operand of SelectItr might be missing a kill marker
20742 // because there were multiple uses of EFLAGS, and ISel didn't know
20743 // which to mark. Figure out whether SelectItr should have had a
20744 // kill marker, and set it if it should. Returns the correct kill
20745 // marker value.
20746 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20747                                      MachineBasicBlock* BB,
20748                                      const TargetRegisterInfo* TRI) {
20749   // Scan forward through BB for a use/def of EFLAGS.
20750   MachineBasicBlock::iterator miI(std::next(SelectItr));
20751   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20752     const MachineInstr& mi = *miI;
20753     if (mi.readsRegister(X86::EFLAGS))
20754       return false;
20755     if (mi.definesRegister(X86::EFLAGS))
20756       break; // Should have kill-flag - update below.
20757   }
20758
20759   // If we hit the end of the block, check whether EFLAGS is live into a
20760   // successor.
20761   if (miI == BB->end()) {
20762     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20763                                           sEnd = BB->succ_end();
20764          sItr != sEnd; ++sItr) {
20765       MachineBasicBlock* succ = *sItr;
20766       if (succ->isLiveIn(X86::EFLAGS))
20767         return false;
20768     }
20769   }
20770
20771   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20772   // out. SelectMI should have a kill flag on EFLAGS.
20773   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20774   return true;
20775 }
20776
20777 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20778 // together with other CMOV pseudo-opcodes into a single basic-block with
20779 // conditional jump around it.
20780 static bool isCMOVPseudo(MachineInstr *MI) {
20781   switch (MI->getOpcode()) {
20782   case X86::CMOV_FR32:
20783   case X86::CMOV_FR64:
20784   case X86::CMOV_GR8:
20785   case X86::CMOV_GR16:
20786   case X86::CMOV_GR32:
20787   case X86::CMOV_RFP32:
20788   case X86::CMOV_RFP64:
20789   case X86::CMOV_RFP80:
20790   case X86::CMOV_V2F64:
20791   case X86::CMOV_V2I64:
20792   case X86::CMOV_V4F32:
20793   case X86::CMOV_V4F64:
20794   case X86::CMOV_V4I64:
20795   case X86::CMOV_V16F32:
20796   case X86::CMOV_V8F32:
20797   case X86::CMOV_V8F64:
20798   case X86::CMOV_V8I64:
20799   case X86::CMOV_V8I1:
20800   case X86::CMOV_V16I1:
20801   case X86::CMOV_V32I1:
20802   case X86::CMOV_V64I1:
20803     return true;
20804
20805   default:
20806     return false;
20807   }
20808 }
20809
20810 MachineBasicBlock *
20811 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20812                                      MachineBasicBlock *BB) const {
20813   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20814   DebugLoc DL = MI->getDebugLoc();
20815
20816   // To "insert" a SELECT_CC instruction, we actually have to insert the
20817   // diamond control-flow pattern.  The incoming instruction knows the
20818   // destination vreg to set, the condition code register to branch on, the
20819   // true/false values to select between, and a branch opcode to use.
20820   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20821   MachineFunction::iterator It = BB;
20822   ++It;
20823
20824   //  thisMBB:
20825   //  ...
20826   //   TrueVal = ...
20827   //   cmpTY ccX, r1, r2
20828   //   bCC copy1MBB
20829   //   fallthrough --> copy0MBB
20830   MachineBasicBlock *thisMBB = BB;
20831   MachineFunction *F = BB->getParent();
20832
20833   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20834   // as described above, by inserting a BB, and then making a PHI at the join
20835   // point to select the true and false operands of the CMOV in the PHI.
20836   //
20837   // The code also handles two different cases of multiple CMOV opcodes
20838   // in a row.
20839   //
20840   // Case 1:
20841   // In this case, there are multiple CMOVs in a row, all which are based on
20842   // the same condition setting (or the exact opposite condition setting).
20843   // In this case we can lower all the CMOVs using a single inserted BB, and
20844   // then make a number of PHIs at the join point to model the CMOVs. The only
20845   // trickiness here, is that in a case like:
20846   //
20847   // t2 = CMOV cond1 t1, f1
20848   // t3 = CMOV cond1 t2, f2
20849   //
20850   // when rewriting this into PHIs, we have to perform some renaming on the
20851   // temps since you cannot have a PHI operand refer to a PHI result earlier
20852   // in the same block.  The "simple" but wrong lowering would be:
20853   //
20854   // t2 = PHI t1(BB1), f1(BB2)
20855   // t3 = PHI t2(BB1), f2(BB2)
20856   //
20857   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20858   // renaming is to note that on the path through BB1, t2 is really just a
20859   // copy of t1, and do that renaming, properly generating:
20860   //
20861   // t2 = PHI t1(BB1), f1(BB2)
20862   // t3 = PHI t1(BB1), f2(BB2)
20863   //
20864   // Case 2, we lower cascaded CMOVs such as
20865   //
20866   //   (CMOV (CMOV F, T, cc1), T, cc2)
20867   //
20868   // to two successives branches.  For that, we look for another CMOV as the
20869   // following instruction.
20870   //
20871   // Without this, we would add a PHI between the two jumps, which ends up
20872   // creating a few copies all around. For instance, for
20873   //
20874   //    (sitofp (zext (fcmp une)))
20875   //
20876   // we would generate:
20877   //
20878   //         ucomiss %xmm1, %xmm0
20879   //         movss  <1.0f>, %xmm0
20880   //         movaps  %xmm0, %xmm1
20881   //         jne     .LBB5_2
20882   //         xorps   %xmm1, %xmm1
20883   // .LBB5_2:
20884   //         jp      .LBB5_4
20885   //         movaps  %xmm1, %xmm0
20886   // .LBB5_4:
20887   //         retq
20888   //
20889   // because this custom-inserter would have generated:
20890   //
20891   //   A
20892   //   | \
20893   //   |  B
20894   //   | /
20895   //   C
20896   //   | \
20897   //   |  D
20898   //   | /
20899   //   E
20900   //
20901   // A: X = ...; Y = ...
20902   // B: empty
20903   // C: Z = PHI [X, A], [Y, B]
20904   // D: empty
20905   // E: PHI [X, C], [Z, D]
20906   //
20907   // If we lower both CMOVs in a single step, we can instead generate:
20908   //
20909   //   A
20910   //   | \
20911   //   |  C
20912   //   | /|
20913   //   |/ |
20914   //   |  |
20915   //   |  D
20916   //   | /
20917   //   E
20918   //
20919   // A: X = ...; Y = ...
20920   // D: empty
20921   // E: PHI [X, A], [X, C], [Y, D]
20922   //
20923   // Which, in our sitofp/fcmp example, gives us something like:
20924   //
20925   //         ucomiss %xmm1, %xmm0
20926   //         movss  <1.0f>, %xmm0
20927   //         jne     .LBB5_4
20928   //         jp      .LBB5_4
20929   //         xorps   %xmm0, %xmm0
20930   // .LBB5_4:
20931   //         retq
20932   //
20933   MachineInstr *CascadedCMOV = nullptr;
20934   MachineInstr *LastCMOV = MI;
20935   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20936   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20937   MachineBasicBlock::iterator NextMIIt =
20938       std::next(MachineBasicBlock::iterator(MI));
20939
20940   // Check for case 1, where there are multiple CMOVs with the same condition
20941   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
20942   // number of jumps the most.
20943
20944   if (isCMOVPseudo(MI)) {
20945     // See if we have a string of CMOVS with the same condition.
20946     while (NextMIIt != BB->end() &&
20947            isCMOVPseudo(NextMIIt) &&
20948            (NextMIIt->getOperand(3).getImm() == CC ||
20949             NextMIIt->getOperand(3).getImm() == OppCC)) {
20950       LastCMOV = &*NextMIIt;
20951       ++NextMIIt;
20952     }
20953   }
20954
20955   // This checks for case 2, but only do this if we didn't already find
20956   // case 1, as indicated by LastCMOV == MI.
20957   if (LastCMOV == MI &&
20958       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20959       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20960       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20961     CascadedCMOV = &*NextMIIt;
20962   }
20963
20964   MachineBasicBlock *jcc1MBB = nullptr;
20965
20966   // If we have a cascaded CMOV, we lower it to two successive branches to
20967   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20968   if (CascadedCMOV) {
20969     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20970     F->insert(It, jcc1MBB);
20971     jcc1MBB->addLiveIn(X86::EFLAGS);
20972   }
20973
20974   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20975   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20976   F->insert(It, copy0MBB);
20977   F->insert(It, sinkMBB);
20978
20979   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20980   // live into the sink and copy blocks.
20981   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20982
20983   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20984   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20985       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20986     copy0MBB->addLiveIn(X86::EFLAGS);
20987     sinkMBB->addLiveIn(X86::EFLAGS);
20988   }
20989
20990   // Transfer the remainder of BB and its successor edges to sinkMBB.
20991   sinkMBB->splice(sinkMBB->begin(), BB,
20992                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20993   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20994
20995   // Add the true and fallthrough blocks as its successors.
20996   if (CascadedCMOV) {
20997     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20998     BB->addSuccessor(jcc1MBB);
20999
21000     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21001     // jump to the sinkMBB.
21002     jcc1MBB->addSuccessor(copy0MBB);
21003     jcc1MBB->addSuccessor(sinkMBB);
21004   } else {
21005     BB->addSuccessor(copy0MBB);
21006   }
21007
21008   // The true block target of the first (or only) branch is always sinkMBB.
21009   BB->addSuccessor(sinkMBB);
21010
21011   // Create the conditional branch instruction.
21012   unsigned Opc = X86::GetCondBranchFromCond(CC);
21013   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21014
21015   if (CascadedCMOV) {
21016     unsigned Opc2 = X86::GetCondBranchFromCond(
21017         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21018     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21019   }
21020
21021   //  copy0MBB:
21022   //   %FalseValue = ...
21023   //   # fallthrough to sinkMBB
21024   copy0MBB->addSuccessor(sinkMBB);
21025
21026   //  sinkMBB:
21027   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21028   //  ...
21029   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21030   MachineBasicBlock::iterator MIItEnd =
21031     std::next(MachineBasicBlock::iterator(LastCMOV));
21032   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21033   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21034   MachineInstrBuilder MIB;
21035
21036   // As we are creating the PHIs, we have to be careful if there is more than
21037   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
21038   // PHIs have to reference the individual true/false inputs from earlier PHIs.
21039   // That also means that PHI construction must work forward from earlier to
21040   // later, and that the code must maintain a mapping from earlier PHI's
21041   // destination registers, and the registers that went into the PHI.
21042
21043   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21044     unsigned DestReg = MIIt->getOperand(0).getReg();
21045     unsigned Op1Reg = MIIt->getOperand(1).getReg();
21046     unsigned Op2Reg = MIIt->getOperand(2).getReg();
21047
21048     // If this CMOV we are generating is the opposite condition from
21049     // the jump we generated, then we have to swap the operands for the
21050     // PHI that is going to be generated.
21051     if (MIIt->getOperand(3).getImm() == OppCC)
21052         std::swap(Op1Reg, Op2Reg);
21053
21054     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21055       Op1Reg = RegRewriteTable[Op1Reg].first;
21056
21057     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21058       Op2Reg = RegRewriteTable[Op2Reg].second;
21059
21060     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21061                   TII->get(X86::PHI), DestReg)
21062           .addReg(Op1Reg).addMBB(copy0MBB)
21063           .addReg(Op2Reg).addMBB(thisMBB);
21064
21065     // Add this PHI to the rewrite table.
21066     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21067   }
21068
21069   // If we have a cascaded CMOV, the second Jcc provides the same incoming
21070   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21071   if (CascadedCMOV) {
21072     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21073     // Copy the PHI result to the register defined by the second CMOV.
21074     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21075             DL, TII->get(TargetOpcode::COPY),
21076             CascadedCMOV->getOperand(0).getReg())
21077         .addReg(MI->getOperand(0).getReg());
21078     CascadedCMOV->eraseFromParent();
21079   }
21080
21081   // Now remove the CMOV(s).
21082   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
21083     (MIIt++)->eraseFromParent();
21084
21085   return sinkMBB;
21086 }
21087
21088 MachineBasicBlock *
21089 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
21090                                        MachineBasicBlock *BB) const {
21091   // Combine the following atomic floating-point modification pattern:
21092   //   a.store(reg OP a.load(acquire), release)
21093   // Transform them into:
21094   //   OPss (%gpr), %xmm
21095   //   movss %xmm, (%gpr)
21096   // Or sd equivalent for 64-bit operations.
21097   unsigned MOp, FOp;
21098   switch (MI->getOpcode()) {
21099   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
21100   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
21101   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
21102   }
21103   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21104   DebugLoc DL = MI->getDebugLoc();
21105   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
21106   MachineOperand MSrc = MI->getOperand(0);
21107   unsigned VSrc = MI->getOperand(5).getReg();
21108   const MachineOperand &Disp = MI->getOperand(3);
21109   MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
21110   bool hasDisp = Disp.isGlobal() || Disp.isImm();
21111   if (hasDisp && MSrc.isReg())
21112     MSrc.setIsKill(false);
21113   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
21114                                 .addOperand(/*Base=*/MSrc)
21115                                 .addImm(/*Scale=*/1)
21116                                 .addReg(/*Index=*/0)
21117                                 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21118                                 .addReg(0);
21119   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
21120                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
21121                           .addReg(VSrc)
21122                           .addOperand(/*Base=*/MSrc)
21123                           .addImm(/*Scale=*/1)
21124                           .addReg(/*Index=*/0)
21125                           .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21126                           .addReg(/*Segment=*/0);
21127   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
21128   MI->eraseFromParent(); // The pseudo instruction is gone now.
21129   return BB;
21130 }
21131
21132 MachineBasicBlock *
21133 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
21134                                         MachineBasicBlock *BB) const {
21135   MachineFunction *MF = BB->getParent();
21136   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21137   DebugLoc DL = MI->getDebugLoc();
21138   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21139
21140   assert(MF->shouldSplitStack());
21141
21142   const bool Is64Bit = Subtarget->is64Bit();
21143   const bool IsLP64 = Subtarget->isTarget64BitLP64();
21144
21145   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
21146   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
21147
21148   // BB:
21149   //  ... [Till the alloca]
21150   // If stacklet is not large enough, jump to mallocMBB
21151   //
21152   // bumpMBB:
21153   //  Allocate by subtracting from RSP
21154   //  Jump to continueMBB
21155   //
21156   // mallocMBB:
21157   //  Allocate by call to runtime
21158   //
21159   // continueMBB:
21160   //  ...
21161   //  [rest of original BB]
21162   //
21163
21164   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21165   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21166   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21167
21168   MachineRegisterInfo &MRI = MF->getRegInfo();
21169   const TargetRegisterClass *AddrRegClass =
21170       getRegClassFor(getPointerTy(MF->getDataLayout()));
21171
21172   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21173     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21174     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
21175     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
21176     sizeVReg = MI->getOperand(1).getReg(),
21177     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
21178
21179   MachineFunction::iterator MBBIter = BB;
21180   ++MBBIter;
21181
21182   MF->insert(MBBIter, bumpMBB);
21183   MF->insert(MBBIter, mallocMBB);
21184   MF->insert(MBBIter, continueMBB);
21185
21186   continueMBB->splice(continueMBB->begin(), BB,
21187                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
21188   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
21189
21190   // Add code to the main basic block to check if the stack limit has been hit,
21191   // and if so, jump to mallocMBB otherwise to bumpMBB.
21192   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
21193   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
21194     .addReg(tmpSPVReg).addReg(sizeVReg);
21195   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
21196     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
21197     .addReg(SPLimitVReg);
21198   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
21199
21200   // bumpMBB simply decreases the stack pointer, since we know the current
21201   // stacklet has enough space.
21202   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
21203     .addReg(SPLimitVReg);
21204   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
21205     .addReg(SPLimitVReg);
21206   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21207
21208   // Calls into a routine in libgcc to allocate more space from the heap.
21209   const uint32_t *RegMask =
21210       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
21211   if (IsLP64) {
21212     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
21213       .addReg(sizeVReg);
21214     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21215       .addExternalSymbol("__morestack_allocate_stack_space")
21216       .addRegMask(RegMask)
21217       .addReg(X86::RDI, RegState::Implicit)
21218       .addReg(X86::RAX, RegState::ImplicitDefine);
21219   } else if (Is64Bit) {
21220     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
21221       .addReg(sizeVReg);
21222     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21223       .addExternalSymbol("__morestack_allocate_stack_space")
21224       .addRegMask(RegMask)
21225       .addReg(X86::EDI, RegState::Implicit)
21226       .addReg(X86::EAX, RegState::ImplicitDefine);
21227   } else {
21228     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
21229       .addImm(12);
21230     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
21231     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
21232       .addExternalSymbol("__morestack_allocate_stack_space")
21233       .addRegMask(RegMask)
21234       .addReg(X86::EAX, RegState::ImplicitDefine);
21235   }
21236
21237   if (!Is64Bit)
21238     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
21239       .addImm(16);
21240
21241   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
21242     .addReg(IsLP64 ? X86::RAX : X86::EAX);
21243   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21244
21245   // Set up the CFG correctly.
21246   BB->addSuccessor(bumpMBB);
21247   BB->addSuccessor(mallocMBB);
21248   mallocMBB->addSuccessor(continueMBB);
21249   bumpMBB->addSuccessor(continueMBB);
21250
21251   // Take care of the PHI nodes.
21252   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
21253           MI->getOperand(0).getReg())
21254     .addReg(mallocPtrVReg).addMBB(mallocMBB)
21255     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
21256
21257   // Delete the original pseudo instruction.
21258   MI->eraseFromParent();
21259
21260   // And we're done.
21261   return continueMBB;
21262 }
21263
21264 MachineBasicBlock *
21265 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
21266                                         MachineBasicBlock *BB) const {
21267   DebugLoc DL = MI->getDebugLoc();
21268
21269   assert(!Subtarget->isTargetMachO());
21270
21271   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
21272                                                     DL);
21273
21274   MI->eraseFromParent();   // The pseudo instruction is gone now.
21275   return BB;
21276 }
21277
21278 MachineBasicBlock *
21279 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
21280                                       MachineBasicBlock *BB) const {
21281   // This is pretty easy.  We're taking the value that we received from
21282   // our load from the relocation, sticking it in either RDI (x86-64)
21283   // or EAX and doing an indirect call.  The return value will then
21284   // be in the normal return register.
21285   MachineFunction *F = BB->getParent();
21286   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21287   DebugLoc DL = MI->getDebugLoc();
21288
21289   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
21290   assert(MI->getOperand(3).isGlobal() && "This should be a global");
21291
21292   // Get a register mask for the lowered call.
21293   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
21294   // proper register mask.
21295   const uint32_t *RegMask =
21296       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
21297   if (Subtarget->is64Bit()) {
21298     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21299                                       TII->get(X86::MOV64rm), X86::RDI)
21300     .addReg(X86::RIP)
21301     .addImm(0).addReg(0)
21302     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21303                       MI->getOperand(3).getTargetFlags())
21304     .addReg(0);
21305     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
21306     addDirectMem(MIB, X86::RDI);
21307     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
21308   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
21309     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21310                                       TII->get(X86::MOV32rm), X86::EAX)
21311     .addReg(0)
21312     .addImm(0).addReg(0)
21313     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21314                       MI->getOperand(3).getTargetFlags())
21315     .addReg(0);
21316     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21317     addDirectMem(MIB, X86::EAX);
21318     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21319   } else {
21320     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21321                                       TII->get(X86::MOV32rm), X86::EAX)
21322     .addReg(TII->getGlobalBaseReg(F))
21323     .addImm(0).addReg(0)
21324     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21325                       MI->getOperand(3).getTargetFlags())
21326     .addReg(0);
21327     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21328     addDirectMem(MIB, X86::EAX);
21329     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21330   }
21331
21332   MI->eraseFromParent(); // The pseudo instruction is gone now.
21333   return BB;
21334 }
21335
21336 MachineBasicBlock *
21337 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21338                                     MachineBasicBlock *MBB) const {
21339   DebugLoc DL = MI->getDebugLoc();
21340   MachineFunction *MF = MBB->getParent();
21341   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21342   MachineRegisterInfo &MRI = MF->getRegInfo();
21343
21344   const BasicBlock *BB = MBB->getBasicBlock();
21345   MachineFunction::iterator I = MBB;
21346   ++I;
21347
21348   // Memory Reference
21349   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21350   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21351
21352   unsigned DstReg;
21353   unsigned MemOpndSlot = 0;
21354
21355   unsigned CurOp = 0;
21356
21357   DstReg = MI->getOperand(CurOp++).getReg();
21358   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21359   assert(RC->hasType(MVT::i32) && "Invalid destination!");
21360   unsigned mainDstReg = MRI.createVirtualRegister(RC);
21361   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21362
21363   MemOpndSlot = CurOp;
21364
21365   MVT PVT = getPointerTy(MF->getDataLayout());
21366   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21367          "Invalid Pointer Size!");
21368
21369   // For v = setjmp(buf), we generate
21370   //
21371   // thisMBB:
21372   //  buf[LabelOffset] = restoreMBB
21373   //  SjLjSetup restoreMBB
21374   //
21375   // mainMBB:
21376   //  v_main = 0
21377   //
21378   // sinkMBB:
21379   //  v = phi(main, restore)
21380   //
21381   // restoreMBB:
21382   //  if base pointer being used, load it from frame
21383   //  v_restore = 1
21384
21385   MachineBasicBlock *thisMBB = MBB;
21386   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21387   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21388   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21389   MF->insert(I, mainMBB);
21390   MF->insert(I, sinkMBB);
21391   MF->push_back(restoreMBB);
21392
21393   MachineInstrBuilder MIB;
21394
21395   // Transfer the remainder of BB and its successor edges to sinkMBB.
21396   sinkMBB->splice(sinkMBB->begin(), MBB,
21397                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21398   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21399
21400   // thisMBB:
21401   unsigned PtrStoreOpc = 0;
21402   unsigned LabelReg = 0;
21403   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21404   Reloc::Model RM = MF->getTarget().getRelocationModel();
21405   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21406                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21407
21408   // Prepare IP either in reg or imm.
21409   if (!UseImmLabel) {
21410     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21411     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21412     LabelReg = MRI.createVirtualRegister(PtrRC);
21413     if (Subtarget->is64Bit()) {
21414       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21415               .addReg(X86::RIP)
21416               .addImm(0)
21417               .addReg(0)
21418               .addMBB(restoreMBB)
21419               .addReg(0);
21420     } else {
21421       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21422       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21423               .addReg(XII->getGlobalBaseReg(MF))
21424               .addImm(0)
21425               .addReg(0)
21426               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21427               .addReg(0);
21428     }
21429   } else
21430     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21431   // Store IP
21432   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21433   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21434     if (i == X86::AddrDisp)
21435       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21436     else
21437       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21438   }
21439   if (!UseImmLabel)
21440     MIB.addReg(LabelReg);
21441   else
21442     MIB.addMBB(restoreMBB);
21443   MIB.setMemRefs(MMOBegin, MMOEnd);
21444   // Setup
21445   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21446           .addMBB(restoreMBB);
21447
21448   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21449   MIB.addRegMask(RegInfo->getNoPreservedMask());
21450   thisMBB->addSuccessor(mainMBB);
21451   thisMBB->addSuccessor(restoreMBB);
21452
21453   // mainMBB:
21454   //  EAX = 0
21455   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21456   mainMBB->addSuccessor(sinkMBB);
21457
21458   // sinkMBB:
21459   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21460           TII->get(X86::PHI), DstReg)
21461     .addReg(mainDstReg).addMBB(mainMBB)
21462     .addReg(restoreDstReg).addMBB(restoreMBB);
21463
21464   // restoreMBB:
21465   if (RegInfo->hasBasePointer(*MF)) {
21466     const bool Uses64BitFramePtr =
21467         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21468     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21469     X86FI->setRestoreBasePointer(MF);
21470     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21471     unsigned BasePtr = RegInfo->getBaseRegister();
21472     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21473     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21474                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
21475       .setMIFlag(MachineInstr::FrameSetup);
21476   }
21477   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21478   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21479   restoreMBB->addSuccessor(sinkMBB);
21480
21481   MI->eraseFromParent();
21482   return sinkMBB;
21483 }
21484
21485 MachineBasicBlock *
21486 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21487                                      MachineBasicBlock *MBB) const {
21488   DebugLoc DL = MI->getDebugLoc();
21489   MachineFunction *MF = MBB->getParent();
21490   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21491   MachineRegisterInfo &MRI = MF->getRegInfo();
21492
21493   // Memory Reference
21494   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21495   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21496
21497   MVT PVT = getPointerTy(MF->getDataLayout());
21498   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21499          "Invalid Pointer Size!");
21500
21501   const TargetRegisterClass *RC =
21502     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21503   unsigned Tmp = MRI.createVirtualRegister(RC);
21504   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21505   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21506   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21507   unsigned SP = RegInfo->getStackRegister();
21508
21509   MachineInstrBuilder MIB;
21510
21511   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21512   const int64_t SPOffset = 2 * PVT.getStoreSize();
21513
21514   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21515   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21516
21517   // Reload FP
21518   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21519   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21520     MIB.addOperand(MI->getOperand(i));
21521   MIB.setMemRefs(MMOBegin, MMOEnd);
21522   // Reload IP
21523   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21524   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21525     if (i == X86::AddrDisp)
21526       MIB.addDisp(MI->getOperand(i), LabelOffset);
21527     else
21528       MIB.addOperand(MI->getOperand(i));
21529   }
21530   MIB.setMemRefs(MMOBegin, MMOEnd);
21531   // Reload SP
21532   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21533   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21534     if (i == X86::AddrDisp)
21535       MIB.addDisp(MI->getOperand(i), SPOffset);
21536     else
21537       MIB.addOperand(MI->getOperand(i));
21538   }
21539   MIB.setMemRefs(MMOBegin, MMOEnd);
21540   // Jump
21541   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21542
21543   MI->eraseFromParent();
21544   return MBB;
21545 }
21546
21547 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21548 // accumulator loops. Writing back to the accumulator allows the coalescer
21549 // to remove extra copies in the loop.
21550 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
21551 MachineBasicBlock *
21552 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21553                                  MachineBasicBlock *MBB) const {
21554   MachineOperand &AddendOp = MI->getOperand(3);
21555
21556   // Bail out early if the addend isn't a register - we can't switch these.
21557   if (!AddendOp.isReg())
21558     return MBB;
21559
21560   MachineFunction &MF = *MBB->getParent();
21561   MachineRegisterInfo &MRI = MF.getRegInfo();
21562
21563   // Check whether the addend is defined by a PHI:
21564   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21565   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21566   if (!AddendDef.isPHI())
21567     return MBB;
21568
21569   // Look for the following pattern:
21570   // loop:
21571   //   %addend = phi [%entry, 0], [%loop, %result]
21572   //   ...
21573   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21574
21575   // Replace with:
21576   //   loop:
21577   //   %addend = phi [%entry, 0], [%loop, %result]
21578   //   ...
21579   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21580
21581   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21582     assert(AddendDef.getOperand(i).isReg());
21583     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21584     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21585     if (&PHISrcInst == MI) {
21586       // Found a matching instruction.
21587       unsigned NewFMAOpc = 0;
21588       switch (MI->getOpcode()) {
21589         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21590         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21591         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21592         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21593         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21594         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21595         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21596         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21597         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21598         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21599         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21600         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21601         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21602         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21603         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21604         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21605         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21606         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21607         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21608         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21609
21610         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21611         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21612         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21613         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21614         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21615         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21616         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21617         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21618         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21619         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21620         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21621         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21622         default: llvm_unreachable("Unrecognized FMA variant.");
21623       }
21624
21625       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21626       MachineInstrBuilder MIB =
21627         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21628         .addOperand(MI->getOperand(0))
21629         .addOperand(MI->getOperand(3))
21630         .addOperand(MI->getOperand(2))
21631         .addOperand(MI->getOperand(1));
21632       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21633       MI->eraseFromParent();
21634     }
21635   }
21636
21637   return MBB;
21638 }
21639
21640 MachineBasicBlock *
21641 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21642                                                MachineBasicBlock *BB) const {
21643   switch (MI->getOpcode()) {
21644   default: llvm_unreachable("Unexpected instr type to insert");
21645   case X86::TAILJMPd64:
21646   case X86::TAILJMPr64:
21647   case X86::TAILJMPm64:
21648   case X86::TAILJMPd64_REX:
21649   case X86::TAILJMPr64_REX:
21650   case X86::TAILJMPm64_REX:
21651     llvm_unreachable("TAILJMP64 would not be touched here.");
21652   case X86::TCRETURNdi64:
21653   case X86::TCRETURNri64:
21654   case X86::TCRETURNmi64:
21655     return BB;
21656   case X86::WIN_ALLOCA:
21657     return EmitLoweredWinAlloca(MI, BB);
21658   case X86::SEG_ALLOCA_32:
21659   case X86::SEG_ALLOCA_64:
21660     return EmitLoweredSegAlloca(MI, BB);
21661   case X86::TLSCall_32:
21662   case X86::TLSCall_64:
21663     return EmitLoweredTLSCall(MI, BB);
21664   case X86::CMOV_FR32:
21665   case X86::CMOV_FR64:
21666   case X86::CMOV_GR8:
21667   case X86::CMOV_GR16:
21668   case X86::CMOV_GR32:
21669   case X86::CMOV_RFP32:
21670   case X86::CMOV_RFP64:
21671   case X86::CMOV_RFP80:
21672   case X86::CMOV_V2F64:
21673   case X86::CMOV_V2I64:
21674   case X86::CMOV_V4F32:
21675   case X86::CMOV_V4F64:
21676   case X86::CMOV_V4I64:
21677   case X86::CMOV_V16F32:
21678   case X86::CMOV_V8F32:
21679   case X86::CMOV_V8F64:
21680   case X86::CMOV_V8I64:
21681   case X86::CMOV_V8I1:
21682   case X86::CMOV_V16I1:
21683   case X86::CMOV_V32I1:
21684   case X86::CMOV_V64I1:
21685     return EmitLoweredSelect(MI, BB);
21686
21687   case X86::RELEASE_FADD32mr:
21688   case X86::RELEASE_FADD64mr:
21689     return EmitLoweredAtomicFP(MI, BB);
21690
21691   case X86::FP32_TO_INT16_IN_MEM:
21692   case X86::FP32_TO_INT32_IN_MEM:
21693   case X86::FP32_TO_INT64_IN_MEM:
21694   case X86::FP64_TO_INT16_IN_MEM:
21695   case X86::FP64_TO_INT32_IN_MEM:
21696   case X86::FP64_TO_INT64_IN_MEM:
21697   case X86::FP80_TO_INT16_IN_MEM:
21698   case X86::FP80_TO_INT32_IN_MEM:
21699   case X86::FP80_TO_INT64_IN_MEM: {
21700     MachineFunction *F = BB->getParent();
21701     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21702     DebugLoc DL = MI->getDebugLoc();
21703
21704     // Change the floating point control register to use "round towards zero"
21705     // mode when truncating to an integer value.
21706     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21707     addFrameReference(BuildMI(*BB, MI, DL,
21708                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21709
21710     // Load the old value of the high byte of the control word...
21711     unsigned OldCW =
21712       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21713     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21714                       CWFrameIdx);
21715
21716     // Set the high part to be round to zero...
21717     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21718       .addImm(0xC7F);
21719
21720     // Reload the modified control word now...
21721     addFrameReference(BuildMI(*BB, MI, DL,
21722                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21723
21724     // Restore the memory image of control word to original value
21725     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21726       .addReg(OldCW);
21727
21728     // Get the X86 opcode to use.
21729     unsigned Opc;
21730     switch (MI->getOpcode()) {
21731     default: llvm_unreachable("illegal opcode!");
21732     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21733     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21734     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21735     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21736     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21737     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21738     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21739     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21740     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21741     }
21742
21743     X86AddressMode AM;
21744     MachineOperand &Op = MI->getOperand(0);
21745     if (Op.isReg()) {
21746       AM.BaseType = X86AddressMode::RegBase;
21747       AM.Base.Reg = Op.getReg();
21748     } else {
21749       AM.BaseType = X86AddressMode::FrameIndexBase;
21750       AM.Base.FrameIndex = Op.getIndex();
21751     }
21752     Op = MI->getOperand(1);
21753     if (Op.isImm())
21754       AM.Scale = Op.getImm();
21755     Op = MI->getOperand(2);
21756     if (Op.isImm())
21757       AM.IndexReg = Op.getImm();
21758     Op = MI->getOperand(3);
21759     if (Op.isGlobal()) {
21760       AM.GV = Op.getGlobal();
21761     } else {
21762       AM.Disp = Op.getImm();
21763     }
21764     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21765                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21766
21767     // Reload the original control word now.
21768     addFrameReference(BuildMI(*BB, MI, DL,
21769                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21770
21771     MI->eraseFromParent();   // The pseudo instruction is gone now.
21772     return BB;
21773   }
21774     // String/text processing lowering.
21775   case X86::PCMPISTRM128REG:
21776   case X86::VPCMPISTRM128REG:
21777   case X86::PCMPISTRM128MEM:
21778   case X86::VPCMPISTRM128MEM:
21779   case X86::PCMPESTRM128REG:
21780   case X86::VPCMPESTRM128REG:
21781   case X86::PCMPESTRM128MEM:
21782   case X86::VPCMPESTRM128MEM:
21783     assert(Subtarget->hasSSE42() &&
21784            "Target must have SSE4.2 or AVX features enabled");
21785     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21786
21787   // String/text processing lowering.
21788   case X86::PCMPISTRIREG:
21789   case X86::VPCMPISTRIREG:
21790   case X86::PCMPISTRIMEM:
21791   case X86::VPCMPISTRIMEM:
21792   case X86::PCMPESTRIREG:
21793   case X86::VPCMPESTRIREG:
21794   case X86::PCMPESTRIMEM:
21795   case X86::VPCMPESTRIMEM:
21796     assert(Subtarget->hasSSE42() &&
21797            "Target must have SSE4.2 or AVX features enabled");
21798     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21799
21800   // Thread synchronization.
21801   case X86::MONITOR:
21802     return EmitMonitor(MI, BB, Subtarget);
21803
21804   // xbegin
21805   case X86::XBEGIN:
21806     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21807
21808   case X86::VASTART_SAVE_XMM_REGS:
21809     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21810
21811   case X86::VAARG_64:
21812     return EmitVAARG64WithCustomInserter(MI, BB);
21813
21814   case X86::EH_SjLj_SetJmp32:
21815   case X86::EH_SjLj_SetJmp64:
21816     return emitEHSjLjSetJmp(MI, BB);
21817
21818   case X86::EH_SjLj_LongJmp32:
21819   case X86::EH_SjLj_LongJmp64:
21820     return emitEHSjLjLongJmp(MI, BB);
21821
21822   case TargetOpcode::STATEPOINT:
21823     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21824     // this point in the process.  We diverge later.
21825     return emitPatchPoint(MI, BB);
21826
21827   case TargetOpcode::STACKMAP:
21828   case TargetOpcode::PATCHPOINT:
21829     return emitPatchPoint(MI, BB);
21830
21831   case X86::VFMADDPDr213r:
21832   case X86::VFMADDPSr213r:
21833   case X86::VFMADDSDr213r:
21834   case X86::VFMADDSSr213r:
21835   case X86::VFMSUBPDr213r:
21836   case X86::VFMSUBPSr213r:
21837   case X86::VFMSUBSDr213r:
21838   case X86::VFMSUBSSr213r:
21839   case X86::VFNMADDPDr213r:
21840   case X86::VFNMADDPSr213r:
21841   case X86::VFNMADDSDr213r:
21842   case X86::VFNMADDSSr213r:
21843   case X86::VFNMSUBPDr213r:
21844   case X86::VFNMSUBPSr213r:
21845   case X86::VFNMSUBSDr213r:
21846   case X86::VFNMSUBSSr213r:
21847   case X86::VFMADDSUBPDr213r:
21848   case X86::VFMADDSUBPSr213r:
21849   case X86::VFMSUBADDPDr213r:
21850   case X86::VFMSUBADDPSr213r:
21851   case X86::VFMADDPDr213rY:
21852   case X86::VFMADDPSr213rY:
21853   case X86::VFMSUBPDr213rY:
21854   case X86::VFMSUBPSr213rY:
21855   case X86::VFNMADDPDr213rY:
21856   case X86::VFNMADDPSr213rY:
21857   case X86::VFNMSUBPDr213rY:
21858   case X86::VFNMSUBPSr213rY:
21859   case X86::VFMADDSUBPDr213rY:
21860   case X86::VFMADDSUBPSr213rY:
21861   case X86::VFMSUBADDPDr213rY:
21862   case X86::VFMSUBADDPSr213rY:
21863     return emitFMA3Instr(MI, BB);
21864   }
21865 }
21866
21867 //===----------------------------------------------------------------------===//
21868 //                           X86 Optimization Hooks
21869 //===----------------------------------------------------------------------===//
21870
21871 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21872                                                       APInt &KnownZero,
21873                                                       APInt &KnownOne,
21874                                                       const SelectionDAG &DAG,
21875                                                       unsigned Depth) const {
21876   unsigned BitWidth = KnownZero.getBitWidth();
21877   unsigned Opc = Op.getOpcode();
21878   assert((Opc >= ISD::BUILTIN_OP_END ||
21879           Opc == ISD::INTRINSIC_WO_CHAIN ||
21880           Opc == ISD::INTRINSIC_W_CHAIN ||
21881           Opc == ISD::INTRINSIC_VOID) &&
21882          "Should use MaskedValueIsZero if you don't know whether Op"
21883          " is a target node!");
21884
21885   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21886   switch (Opc) {
21887   default: break;
21888   case X86ISD::ADD:
21889   case X86ISD::SUB:
21890   case X86ISD::ADC:
21891   case X86ISD::SBB:
21892   case X86ISD::SMUL:
21893   case X86ISD::UMUL:
21894   case X86ISD::INC:
21895   case X86ISD::DEC:
21896   case X86ISD::OR:
21897   case X86ISD::XOR:
21898   case X86ISD::AND:
21899     // These nodes' second result is a boolean.
21900     if (Op.getResNo() == 0)
21901       break;
21902     // Fallthrough
21903   case X86ISD::SETCC:
21904     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21905     break;
21906   case ISD::INTRINSIC_WO_CHAIN: {
21907     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21908     unsigned NumLoBits = 0;
21909     switch (IntId) {
21910     default: break;
21911     case Intrinsic::x86_sse_movmsk_ps:
21912     case Intrinsic::x86_avx_movmsk_ps_256:
21913     case Intrinsic::x86_sse2_movmsk_pd:
21914     case Intrinsic::x86_avx_movmsk_pd_256:
21915     case Intrinsic::x86_mmx_pmovmskb:
21916     case Intrinsic::x86_sse2_pmovmskb_128:
21917     case Intrinsic::x86_avx2_pmovmskb: {
21918       // High bits of movmskp{s|d}, pmovmskb are known zero.
21919       switch (IntId) {
21920         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21921         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21922         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21923         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21924         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21925         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21926         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21927         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21928       }
21929       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21930       break;
21931     }
21932     }
21933     break;
21934   }
21935   }
21936 }
21937
21938 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21939   SDValue Op,
21940   const SelectionDAG &,
21941   unsigned Depth) const {
21942   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21943   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21944     return Op.getValueType().getScalarType().getSizeInBits();
21945
21946   // Fallback case.
21947   return 1;
21948 }
21949
21950 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21951 /// node is a GlobalAddress + offset.
21952 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21953                                        const GlobalValue* &GA,
21954                                        int64_t &Offset) const {
21955   if (N->getOpcode() == X86ISD::Wrapper) {
21956     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21957       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21958       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21959       return true;
21960     }
21961   }
21962   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21963 }
21964
21965 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21966 /// same as extracting the high 128-bit part of 256-bit vector and then
21967 /// inserting the result into the low part of a new 256-bit vector
21968 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21969   EVT VT = SVOp->getValueType(0);
21970   unsigned NumElems = VT.getVectorNumElements();
21971
21972   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21973   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21974     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21975         SVOp->getMaskElt(j) >= 0)
21976       return false;
21977
21978   return true;
21979 }
21980
21981 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21982 /// same as extracting the low 128-bit part of 256-bit vector and then
21983 /// inserting the result into the high part of a new 256-bit vector
21984 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21985   EVT VT = SVOp->getValueType(0);
21986   unsigned NumElems = VT.getVectorNumElements();
21987
21988   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21989   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21990     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21991         SVOp->getMaskElt(j) >= 0)
21992       return false;
21993
21994   return true;
21995 }
21996
21997 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21998 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21999                                         TargetLowering::DAGCombinerInfo &DCI,
22000                                         const X86Subtarget* Subtarget) {
22001   SDLoc dl(N);
22002   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22003   SDValue V1 = SVOp->getOperand(0);
22004   SDValue V2 = SVOp->getOperand(1);
22005   EVT VT = SVOp->getValueType(0);
22006   unsigned NumElems = VT.getVectorNumElements();
22007
22008   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22009       V2.getOpcode() == ISD::CONCAT_VECTORS) {
22010     //
22011     //                   0,0,0,...
22012     //                      |
22013     //    V      UNDEF    BUILD_VECTOR    UNDEF
22014     //     \      /           \           /
22015     //  CONCAT_VECTOR         CONCAT_VECTOR
22016     //         \                  /
22017     //          \                /
22018     //          RESULT: V + zero extended
22019     //
22020     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22021         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22022         V1.getOperand(1).getOpcode() != ISD::UNDEF)
22023       return SDValue();
22024
22025     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
22026       return SDValue();
22027
22028     // To match the shuffle mask, the first half of the mask should
22029     // be exactly the first vector, and all the rest a splat with the
22030     // first element of the second one.
22031     for (unsigned i = 0; i != NumElems/2; ++i)
22032       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
22033           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
22034         return SDValue();
22035
22036     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
22037     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
22038       if (Ld->hasNUsesOfValue(1, 0)) {
22039         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
22040         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
22041         SDValue ResNode =
22042           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
22043                                   Ld->getMemoryVT(),
22044                                   Ld->getPointerInfo(),
22045                                   Ld->getAlignment(),
22046                                   false/*isVolatile*/, true/*ReadMem*/,
22047                                   false/*WriteMem*/);
22048
22049         // Make sure the newly-created LOAD is in the same position as Ld in
22050         // terms of dependency. We create a TokenFactor for Ld and ResNode,
22051         // and update uses of Ld's output chain to use the TokenFactor.
22052         if (Ld->hasAnyUseOfValue(1)) {
22053           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22054                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
22055           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
22056           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
22057                                  SDValue(ResNode.getNode(), 1));
22058         }
22059
22060         return DAG.getBitcast(VT, ResNode);
22061       }
22062     }
22063
22064     // Emit a zeroed vector and insert the desired subvector on its
22065     // first half.
22066     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
22067     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
22068     return DCI.CombineTo(N, InsV);
22069   }
22070
22071   //===--------------------------------------------------------------------===//
22072   // Combine some shuffles into subvector extracts and inserts:
22073   //
22074
22075   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22076   if (isShuffleHigh128VectorInsertLow(SVOp)) {
22077     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
22078     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
22079     return DCI.CombineTo(N, InsV);
22080   }
22081
22082   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22083   if (isShuffleLow128VectorInsertHigh(SVOp)) {
22084     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
22085     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
22086     return DCI.CombineTo(N, InsV);
22087   }
22088
22089   return SDValue();
22090 }
22091
22092 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
22093 /// possible.
22094 ///
22095 /// This is the leaf of the recursive combinine below. When we have found some
22096 /// chain of single-use x86 shuffle instructions and accumulated the combined
22097 /// shuffle mask represented by them, this will try to pattern match that mask
22098 /// into either a single instruction if there is a special purpose instruction
22099 /// for this operation, or into a PSHUFB instruction which is a fully general
22100 /// instruction but should only be used to replace chains over a certain depth.
22101 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
22102                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
22103                                    TargetLowering::DAGCombinerInfo &DCI,
22104                                    const X86Subtarget *Subtarget) {
22105   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
22106
22107   // Find the operand that enters the chain. Note that multiple uses are OK
22108   // here, we're not going to remove the operand we find.
22109   SDValue Input = Op.getOperand(0);
22110   while (Input.getOpcode() == ISD::BITCAST)
22111     Input = Input.getOperand(0);
22112
22113   MVT VT = Input.getSimpleValueType();
22114   MVT RootVT = Root.getSimpleValueType();
22115   SDLoc DL(Root);
22116
22117   if (Mask.size() == 1) {
22118     int Index = Mask[0];
22119     assert((Index >= 0 || Index == SM_SentinelUndef ||
22120             Index == SM_SentinelZero) &&
22121            "Invalid shuffle index found!");
22122
22123     // We may end up with an accumulated mask of size 1 as a result of
22124     // widening of shuffle operands (see function canWidenShuffleElements).
22125     // If the only shuffle index is equal to SM_SentinelZero then propagate
22126     // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
22127     // mask, and therefore the entire chain of shuffles can be folded away.
22128     if (Index == SM_SentinelZero)
22129       DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
22130     else
22131       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
22132                     /*AddTo*/ true);
22133     return true;
22134   }
22135
22136   // Use the float domain if the operand type is a floating point type.
22137   bool FloatDomain = VT.isFloatingPoint();
22138
22139   // For floating point shuffles, we don't have free copies in the shuffle
22140   // instructions or the ability to load as part of the instruction, so
22141   // canonicalize their shuffles to UNPCK or MOV variants.
22142   //
22143   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
22144   // vectors because it can have a load folded into it that UNPCK cannot. This
22145   // doesn't preclude something switching to the shorter encoding post-RA.
22146   //
22147   // FIXME: Should teach these routines about AVX vector widths.
22148   if (FloatDomain && VT.getSizeInBits() == 128) {
22149     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
22150       bool Lo = Mask.equals({0, 0});
22151       unsigned Shuffle;
22152       MVT ShuffleVT;
22153       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
22154       // is no slower than UNPCKLPD but has the option to fold the input operand
22155       // into even an unaligned memory load.
22156       if (Lo && Subtarget->hasSSE3()) {
22157         Shuffle = X86ISD::MOVDDUP;
22158         ShuffleVT = MVT::v2f64;
22159       } else {
22160         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
22161         // than the UNPCK variants.
22162         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
22163         ShuffleVT = MVT::v4f32;
22164       }
22165       if (Depth == 1 && Root->getOpcode() == Shuffle)
22166         return false; // Nothing to do!
22167       Op = DAG.getBitcast(ShuffleVT, Input);
22168       DCI.AddToWorklist(Op.getNode());
22169       if (Shuffle == X86ISD::MOVDDUP)
22170         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22171       else
22172         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22173       DCI.AddToWorklist(Op.getNode());
22174       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22175                     /*AddTo*/ true);
22176       return true;
22177     }
22178     if (Subtarget->hasSSE3() &&
22179         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
22180       bool Lo = Mask.equals({0, 0, 2, 2});
22181       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
22182       MVT ShuffleVT = MVT::v4f32;
22183       if (Depth == 1 && Root->getOpcode() == Shuffle)
22184         return false; // Nothing to do!
22185       Op = DAG.getBitcast(ShuffleVT, Input);
22186       DCI.AddToWorklist(Op.getNode());
22187       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22188       DCI.AddToWorklist(Op.getNode());
22189       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22190                     /*AddTo*/ true);
22191       return true;
22192     }
22193     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
22194       bool Lo = Mask.equals({0, 0, 1, 1});
22195       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22196       MVT ShuffleVT = MVT::v4f32;
22197       if (Depth == 1 && Root->getOpcode() == Shuffle)
22198         return false; // Nothing to do!
22199       Op = DAG.getBitcast(ShuffleVT, Input);
22200       DCI.AddToWorklist(Op.getNode());
22201       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22202       DCI.AddToWorklist(Op.getNode());
22203       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22204                     /*AddTo*/ true);
22205       return true;
22206     }
22207   }
22208
22209   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
22210   // variants as none of these have single-instruction variants that are
22211   // superior to the UNPCK formulation.
22212   if (!FloatDomain && VT.getSizeInBits() == 128 &&
22213       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22214        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
22215        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
22216        Mask.equals(
22217            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
22218     bool Lo = Mask[0] == 0;
22219     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22220     if (Depth == 1 && Root->getOpcode() == Shuffle)
22221       return false; // Nothing to do!
22222     MVT ShuffleVT;
22223     switch (Mask.size()) {
22224     case 8:
22225       ShuffleVT = MVT::v8i16;
22226       break;
22227     case 16:
22228       ShuffleVT = MVT::v16i8;
22229       break;
22230     default:
22231       llvm_unreachable("Impossible mask size!");
22232     };
22233     Op = DAG.getBitcast(ShuffleVT, Input);
22234     DCI.AddToWorklist(Op.getNode());
22235     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22236     DCI.AddToWorklist(Op.getNode());
22237     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22238                   /*AddTo*/ true);
22239     return true;
22240   }
22241
22242   // Don't try to re-form single instruction chains under any circumstances now
22243   // that we've done encoding canonicalization for them.
22244   if (Depth < 2)
22245     return false;
22246
22247   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
22248   // can replace them with a single PSHUFB instruction profitably. Intel's
22249   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
22250   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
22251   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
22252     SmallVector<SDValue, 16> PSHUFBMask;
22253     int NumBytes = VT.getSizeInBits() / 8;
22254     int Ratio = NumBytes / Mask.size();
22255     for (int i = 0; i < NumBytes; ++i) {
22256       if (Mask[i / Ratio] == SM_SentinelUndef) {
22257         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
22258         continue;
22259       }
22260       int M = Mask[i / Ratio] != SM_SentinelZero
22261                   ? Ratio * Mask[i / Ratio] + i % Ratio
22262                   : 255;
22263       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
22264     }
22265     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
22266     Op = DAG.getBitcast(ByteVT, Input);
22267     DCI.AddToWorklist(Op.getNode());
22268     SDValue PSHUFBMaskOp =
22269         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
22270     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
22271     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
22272     DCI.AddToWorklist(Op.getNode());
22273     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22274                   /*AddTo*/ true);
22275     return true;
22276   }
22277
22278   // Failed to find any combines.
22279   return false;
22280 }
22281
22282 /// \brief Fully generic combining of x86 shuffle instructions.
22283 ///
22284 /// This should be the last combine run over the x86 shuffle instructions. Once
22285 /// they have been fully optimized, this will recursively consider all chains
22286 /// of single-use shuffle instructions, build a generic model of the cumulative
22287 /// shuffle operation, and check for simpler instructions which implement this
22288 /// operation. We use this primarily for two purposes:
22289 ///
22290 /// 1) Collapse generic shuffles to specialized single instructions when
22291 ///    equivalent. In most cases, this is just an encoding size win, but
22292 ///    sometimes we will collapse multiple generic shuffles into a single
22293 ///    special-purpose shuffle.
22294 /// 2) Look for sequences of shuffle instructions with 3 or more total
22295 ///    instructions, and replace them with the slightly more expensive SSSE3
22296 ///    PSHUFB instruction if available. We do this as the last combining step
22297 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
22298 ///    a suitable short sequence of other instructions. The PHUFB will either
22299 ///    use a register or have to read from memory and so is slightly (but only
22300 ///    slightly) more expensive than the other shuffle instructions.
22301 ///
22302 /// Because this is inherently a quadratic operation (for each shuffle in
22303 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
22304 /// This should never be an issue in practice as the shuffle lowering doesn't
22305 /// produce sequences of more than 8 instructions.
22306 ///
22307 /// FIXME: We will currently miss some cases where the redundant shuffling
22308 /// would simplify under the threshold for PSHUFB formation because of
22309 /// combine-ordering. To fix this, we should do the redundant instruction
22310 /// combining in this recursive walk.
22311 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
22312                                           ArrayRef<int> RootMask,
22313                                           int Depth, bool HasPSHUFB,
22314                                           SelectionDAG &DAG,
22315                                           TargetLowering::DAGCombinerInfo &DCI,
22316                                           const X86Subtarget *Subtarget) {
22317   // Bound the depth of our recursive combine because this is ultimately
22318   // quadratic in nature.
22319   if (Depth > 8)
22320     return false;
22321
22322   // Directly rip through bitcasts to find the underlying operand.
22323   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
22324     Op = Op.getOperand(0);
22325
22326   MVT VT = Op.getSimpleValueType();
22327   if (!VT.isVector())
22328     return false; // Bail if we hit a non-vector.
22329
22330   assert(Root.getSimpleValueType().isVector() &&
22331          "Shuffles operate on vector types!");
22332   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
22333          "Can only combine shuffles of the same vector register size.");
22334
22335   if (!isTargetShuffle(Op.getOpcode()))
22336     return false;
22337   SmallVector<int, 16> OpMask;
22338   bool IsUnary;
22339   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
22340   // We only can combine unary shuffles which we can decode the mask for.
22341   if (!HaveMask || !IsUnary)
22342     return false;
22343
22344   assert(VT.getVectorNumElements() == OpMask.size() &&
22345          "Different mask size from vector size!");
22346   assert(((RootMask.size() > OpMask.size() &&
22347            RootMask.size() % OpMask.size() == 0) ||
22348           (OpMask.size() > RootMask.size() &&
22349            OpMask.size() % RootMask.size() == 0) ||
22350           OpMask.size() == RootMask.size()) &&
22351          "The smaller number of elements must divide the larger.");
22352   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22353   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22354   assert(((RootRatio == 1 && OpRatio == 1) ||
22355           (RootRatio == 1) != (OpRatio == 1)) &&
22356          "Must not have a ratio for both incoming and op masks!");
22357
22358   SmallVector<int, 16> Mask;
22359   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22360
22361   // Merge this shuffle operation's mask into our accumulated mask. Note that
22362   // this shuffle's mask will be the first applied to the input, followed by the
22363   // root mask to get us all the way to the root value arrangement. The reason
22364   // for this order is that we are recursing up the operation chain.
22365   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22366     int RootIdx = i / RootRatio;
22367     if (RootMask[RootIdx] < 0) {
22368       // This is a zero or undef lane, we're done.
22369       Mask.push_back(RootMask[RootIdx]);
22370       continue;
22371     }
22372
22373     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22374     int OpIdx = RootMaskedIdx / OpRatio;
22375     if (OpMask[OpIdx] < 0) {
22376       // The incoming lanes are zero or undef, it doesn't matter which ones we
22377       // are using.
22378       Mask.push_back(OpMask[OpIdx]);
22379       continue;
22380     }
22381
22382     // Ok, we have non-zero lanes, map them through.
22383     Mask.push_back(OpMask[OpIdx] * OpRatio +
22384                    RootMaskedIdx % OpRatio);
22385   }
22386
22387   // See if we can recurse into the operand to combine more things.
22388   switch (Op.getOpcode()) {
22389   case X86ISD::PSHUFB:
22390     HasPSHUFB = true;
22391   case X86ISD::PSHUFD:
22392   case X86ISD::PSHUFHW:
22393   case X86ISD::PSHUFLW:
22394     if (Op.getOperand(0).hasOneUse() &&
22395         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22396                                       HasPSHUFB, DAG, DCI, Subtarget))
22397       return true;
22398     break;
22399
22400   case X86ISD::UNPCKL:
22401   case X86ISD::UNPCKH:
22402     assert(Op.getOperand(0) == Op.getOperand(1) &&
22403            "We only combine unary shuffles!");
22404     // We can't check for single use, we have to check that this shuffle is the
22405     // only user.
22406     if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22407         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22408                                       HasPSHUFB, DAG, DCI, Subtarget))
22409       return true;
22410     break;
22411   }
22412
22413   // Minor canonicalization of the accumulated shuffle mask to make it easier
22414   // to match below. All this does is detect masks with squential pairs of
22415   // elements, and shrink them to the half-width mask. It does this in a loop
22416   // so it will reduce the size of the mask to the minimal width mask which
22417   // performs an equivalent shuffle.
22418   SmallVector<int, 16> WidenedMask;
22419   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22420     Mask = std::move(WidenedMask);
22421     WidenedMask.clear();
22422   }
22423
22424   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22425                                 Subtarget);
22426 }
22427
22428 /// \brief Get the PSHUF-style mask from PSHUF node.
22429 ///
22430 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22431 /// PSHUF-style masks that can be reused with such instructions.
22432 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22433   MVT VT = N.getSimpleValueType();
22434   SmallVector<int, 4> Mask;
22435   bool IsUnary;
22436   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22437   (void)HaveMask;
22438   assert(HaveMask);
22439
22440   // If we have more than 128-bits, only the low 128-bits of shuffle mask
22441   // matter. Check that the upper masks are repeats and remove them.
22442   if (VT.getSizeInBits() > 128) {
22443     int LaneElts = 128 / VT.getScalarSizeInBits();
22444 #ifndef NDEBUG
22445     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22446       for (int j = 0; j < LaneElts; ++j)
22447         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22448                "Mask doesn't repeat in high 128-bit lanes!");
22449 #endif
22450     Mask.resize(LaneElts);
22451   }
22452
22453   switch (N.getOpcode()) {
22454   case X86ISD::PSHUFD:
22455     return Mask;
22456   case X86ISD::PSHUFLW:
22457     Mask.resize(4);
22458     return Mask;
22459   case X86ISD::PSHUFHW:
22460     Mask.erase(Mask.begin(), Mask.begin() + 4);
22461     for (int &M : Mask)
22462       M -= 4;
22463     return Mask;
22464   default:
22465     llvm_unreachable("No valid shuffle instruction found!");
22466   }
22467 }
22468
22469 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22470 ///
22471 /// We walk up the chain and look for a combinable shuffle, skipping over
22472 /// shuffles that we could hoist this shuffle's transformation past without
22473 /// altering anything.
22474 static SDValue
22475 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22476                              SelectionDAG &DAG,
22477                              TargetLowering::DAGCombinerInfo &DCI) {
22478   assert(N.getOpcode() == X86ISD::PSHUFD &&
22479          "Called with something other than an x86 128-bit half shuffle!");
22480   SDLoc DL(N);
22481
22482   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22483   // of the shuffles in the chain so that we can form a fresh chain to replace
22484   // this one.
22485   SmallVector<SDValue, 8> Chain;
22486   SDValue V = N.getOperand(0);
22487   for (; V.hasOneUse(); V = V.getOperand(0)) {
22488     switch (V.getOpcode()) {
22489     default:
22490       return SDValue(); // Nothing combined!
22491
22492     case ISD::BITCAST:
22493       // Skip bitcasts as we always know the type for the target specific
22494       // instructions.
22495       continue;
22496
22497     case X86ISD::PSHUFD:
22498       // Found another dword shuffle.
22499       break;
22500
22501     case X86ISD::PSHUFLW:
22502       // Check that the low words (being shuffled) are the identity in the
22503       // dword shuffle, and the high words are self-contained.
22504       if (Mask[0] != 0 || Mask[1] != 1 ||
22505           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22506         return SDValue();
22507
22508       Chain.push_back(V);
22509       continue;
22510
22511     case X86ISD::PSHUFHW:
22512       // Check that the high words (being shuffled) are the identity in the
22513       // dword shuffle, and the low words are self-contained.
22514       if (Mask[2] != 2 || Mask[3] != 3 ||
22515           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22516         return SDValue();
22517
22518       Chain.push_back(V);
22519       continue;
22520
22521     case X86ISD::UNPCKL:
22522     case X86ISD::UNPCKH:
22523       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22524       // shuffle into a preceding word shuffle.
22525       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
22526           V.getSimpleValueType().getScalarType() != MVT::i16)
22527         return SDValue();
22528
22529       // Search for a half-shuffle which we can combine with.
22530       unsigned CombineOp =
22531           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22532       if (V.getOperand(0) != V.getOperand(1) ||
22533           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22534         return SDValue();
22535       Chain.push_back(V);
22536       V = V.getOperand(0);
22537       do {
22538         switch (V.getOpcode()) {
22539         default:
22540           return SDValue(); // Nothing to combine.
22541
22542         case X86ISD::PSHUFLW:
22543         case X86ISD::PSHUFHW:
22544           if (V.getOpcode() == CombineOp)
22545             break;
22546
22547           Chain.push_back(V);
22548
22549           // Fallthrough!
22550         case ISD::BITCAST:
22551           V = V.getOperand(0);
22552           continue;
22553         }
22554         break;
22555       } while (V.hasOneUse());
22556       break;
22557     }
22558     // Break out of the loop if we break out of the switch.
22559     break;
22560   }
22561
22562   if (!V.hasOneUse())
22563     // We fell out of the loop without finding a viable combining instruction.
22564     return SDValue();
22565
22566   // Merge this node's mask and our incoming mask.
22567   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22568   for (int &M : Mask)
22569     M = VMask[M];
22570   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22571                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22572
22573   // Rebuild the chain around this new shuffle.
22574   while (!Chain.empty()) {
22575     SDValue W = Chain.pop_back_val();
22576
22577     if (V.getValueType() != W.getOperand(0).getValueType())
22578       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
22579
22580     switch (W.getOpcode()) {
22581     default:
22582       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22583
22584     case X86ISD::UNPCKL:
22585     case X86ISD::UNPCKH:
22586       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22587       break;
22588
22589     case X86ISD::PSHUFD:
22590     case X86ISD::PSHUFLW:
22591     case X86ISD::PSHUFHW:
22592       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22593       break;
22594     }
22595   }
22596   if (V.getValueType() != N.getValueType())
22597     V = DAG.getBitcast(N.getValueType(), V);
22598
22599   // Return the new chain to replace N.
22600   return V;
22601 }
22602
22603 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
22604 /// pshufhw.
22605 ///
22606 /// We walk up the chain, skipping shuffles of the other half and looking
22607 /// through shuffles which switch halves trying to find a shuffle of the same
22608 /// pair of dwords.
22609 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22610                                         SelectionDAG &DAG,
22611                                         TargetLowering::DAGCombinerInfo &DCI) {
22612   assert(
22613       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22614       "Called with something other than an x86 128-bit half shuffle!");
22615   SDLoc DL(N);
22616   unsigned CombineOpcode = N.getOpcode();
22617
22618   // Walk up a single-use chain looking for a combinable shuffle.
22619   SDValue V = N.getOperand(0);
22620   for (; V.hasOneUse(); V = V.getOperand(0)) {
22621     switch (V.getOpcode()) {
22622     default:
22623       return false; // Nothing combined!
22624
22625     case ISD::BITCAST:
22626       // Skip bitcasts as we always know the type for the target specific
22627       // instructions.
22628       continue;
22629
22630     case X86ISD::PSHUFLW:
22631     case X86ISD::PSHUFHW:
22632       if (V.getOpcode() == CombineOpcode)
22633         break;
22634
22635       // Other-half shuffles are no-ops.
22636       continue;
22637     }
22638     // Break out of the loop if we break out of the switch.
22639     break;
22640   }
22641
22642   if (!V.hasOneUse())
22643     // We fell out of the loop without finding a viable combining instruction.
22644     return false;
22645
22646   // Combine away the bottom node as its shuffle will be accumulated into
22647   // a preceding shuffle.
22648   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22649
22650   // Record the old value.
22651   SDValue Old = V;
22652
22653   // Merge this node's mask and our incoming mask (adjusted to account for all
22654   // the pshufd instructions encountered).
22655   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22656   for (int &M : Mask)
22657     M = VMask[M];
22658   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22659                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22660
22661   // Check that the shuffles didn't cancel each other out. If not, we need to
22662   // combine to the new one.
22663   if (Old != V)
22664     // Replace the combinable shuffle with the combined one, updating all users
22665     // so that we re-evaluate the chain here.
22666     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22667
22668   return true;
22669 }
22670
22671 /// \brief Try to combine x86 target specific shuffles.
22672 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22673                                            TargetLowering::DAGCombinerInfo &DCI,
22674                                            const X86Subtarget *Subtarget) {
22675   SDLoc DL(N);
22676   MVT VT = N.getSimpleValueType();
22677   SmallVector<int, 4> Mask;
22678
22679   switch (N.getOpcode()) {
22680   case X86ISD::PSHUFD:
22681   case X86ISD::PSHUFLW:
22682   case X86ISD::PSHUFHW:
22683     Mask = getPSHUFShuffleMask(N);
22684     assert(Mask.size() == 4);
22685     break;
22686   default:
22687     return SDValue();
22688   }
22689
22690   // Nuke no-op shuffles that show up after combining.
22691   if (isNoopShuffleMask(Mask))
22692     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22693
22694   // Look for simplifications involving one or two shuffle instructions.
22695   SDValue V = N.getOperand(0);
22696   switch (N.getOpcode()) {
22697   default:
22698     break;
22699   case X86ISD::PSHUFLW:
22700   case X86ISD::PSHUFHW:
22701     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22702
22703     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22704       return SDValue(); // We combined away this shuffle, so we're done.
22705
22706     // See if this reduces to a PSHUFD which is no more expensive and can
22707     // combine with more operations. Note that it has to at least flip the
22708     // dwords as otherwise it would have been removed as a no-op.
22709     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22710       int DMask[] = {0, 1, 2, 3};
22711       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22712       DMask[DOffset + 0] = DOffset + 1;
22713       DMask[DOffset + 1] = DOffset + 0;
22714       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22715       V = DAG.getBitcast(DVT, V);
22716       DCI.AddToWorklist(V.getNode());
22717       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22718                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22719       DCI.AddToWorklist(V.getNode());
22720       return DAG.getBitcast(VT, V);
22721     }
22722
22723     // Look for shuffle patterns which can be implemented as a single unpack.
22724     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22725     // only works when we have a PSHUFD followed by two half-shuffles.
22726     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22727         (V.getOpcode() == X86ISD::PSHUFLW ||
22728          V.getOpcode() == X86ISD::PSHUFHW) &&
22729         V.getOpcode() != N.getOpcode() &&
22730         V.hasOneUse()) {
22731       SDValue D = V.getOperand(0);
22732       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22733         D = D.getOperand(0);
22734       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22735         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22736         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22737         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22738         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22739         int WordMask[8];
22740         for (int i = 0; i < 4; ++i) {
22741           WordMask[i + NOffset] = Mask[i] + NOffset;
22742           WordMask[i + VOffset] = VMask[i] + VOffset;
22743         }
22744         // Map the word mask through the DWord mask.
22745         int MappedMask[8];
22746         for (int i = 0; i < 8; ++i)
22747           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22748         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22749             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22750           // We can replace all three shuffles with an unpack.
22751           V = DAG.getBitcast(VT, D.getOperand(0));
22752           DCI.AddToWorklist(V.getNode());
22753           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22754                                                 : X86ISD::UNPCKH,
22755                              DL, VT, V, V);
22756         }
22757       }
22758     }
22759
22760     break;
22761
22762   case X86ISD::PSHUFD:
22763     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22764       return NewN;
22765
22766     break;
22767   }
22768
22769   return SDValue();
22770 }
22771
22772 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22773 ///
22774 /// We combine this directly on the abstract vector shuffle nodes so it is
22775 /// easier to generically match. We also insert dummy vector shuffle nodes for
22776 /// the operands which explicitly discard the lanes which are unused by this
22777 /// operation to try to flow through the rest of the combiner the fact that
22778 /// they're unused.
22779 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22780   SDLoc DL(N);
22781   EVT VT = N->getValueType(0);
22782
22783   // We only handle target-independent shuffles.
22784   // FIXME: It would be easy and harmless to use the target shuffle mask
22785   // extraction tool to support more.
22786   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22787     return SDValue();
22788
22789   auto *SVN = cast<ShuffleVectorSDNode>(N);
22790   ArrayRef<int> Mask = SVN->getMask();
22791   SDValue V1 = N->getOperand(0);
22792   SDValue V2 = N->getOperand(1);
22793
22794   // We require the first shuffle operand to be the SUB node, and the second to
22795   // be the ADD node.
22796   // FIXME: We should support the commuted patterns.
22797   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22798     return SDValue();
22799
22800   // If there are other uses of these operations we can't fold them.
22801   if (!V1->hasOneUse() || !V2->hasOneUse())
22802     return SDValue();
22803
22804   // Ensure that both operations have the same operands. Note that we can
22805   // commute the FADD operands.
22806   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22807   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22808       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22809     return SDValue();
22810
22811   // We're looking for blends between FADD and FSUB nodes. We insist on these
22812   // nodes being lined up in a specific expected pattern.
22813   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22814         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22815         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22816     return SDValue();
22817
22818   // Only specific types are legal at this point, assert so we notice if and
22819   // when these change.
22820   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22821           VT == MVT::v4f64) &&
22822          "Unknown vector type encountered!");
22823
22824   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22825 }
22826
22827 /// PerformShuffleCombine - Performs several different shuffle combines.
22828 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22829                                      TargetLowering::DAGCombinerInfo &DCI,
22830                                      const X86Subtarget *Subtarget) {
22831   SDLoc dl(N);
22832   SDValue N0 = N->getOperand(0);
22833   SDValue N1 = N->getOperand(1);
22834   EVT VT = N->getValueType(0);
22835
22836   // Don't create instructions with illegal types after legalize types has run.
22837   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22838   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22839     return SDValue();
22840
22841   // If we have legalized the vector types, look for blends of FADD and FSUB
22842   // nodes that we can fuse into an ADDSUB node.
22843   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22844     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22845       return AddSub;
22846
22847   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22848   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22849       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22850     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22851
22852   // During Type Legalization, when promoting illegal vector types,
22853   // the backend might introduce new shuffle dag nodes and bitcasts.
22854   //
22855   // This code performs the following transformation:
22856   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22857   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22858   //
22859   // We do this only if both the bitcast and the BINOP dag nodes have
22860   // one use. Also, perform this transformation only if the new binary
22861   // operation is legal. This is to avoid introducing dag nodes that
22862   // potentially need to be further expanded (or custom lowered) into a
22863   // less optimal sequence of dag nodes.
22864   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22865       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22866       N0.getOpcode() == ISD::BITCAST) {
22867     SDValue BC0 = N0.getOperand(0);
22868     EVT SVT = BC0.getValueType();
22869     unsigned Opcode = BC0.getOpcode();
22870     unsigned NumElts = VT.getVectorNumElements();
22871
22872     if (BC0.hasOneUse() && SVT.isVector() &&
22873         SVT.getVectorNumElements() * 2 == NumElts &&
22874         TLI.isOperationLegal(Opcode, VT)) {
22875       bool CanFold = false;
22876       switch (Opcode) {
22877       default : break;
22878       case ISD::ADD :
22879       case ISD::FADD :
22880       case ISD::SUB :
22881       case ISD::FSUB :
22882       case ISD::MUL :
22883       case ISD::FMUL :
22884         CanFold = true;
22885       }
22886
22887       unsigned SVTNumElts = SVT.getVectorNumElements();
22888       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22889       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22890         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22891       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22892         CanFold = SVOp->getMaskElt(i) < 0;
22893
22894       if (CanFold) {
22895         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22896         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22897         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22898         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22899       }
22900     }
22901   }
22902
22903   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22904   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22905   // consecutive, non-overlapping, and in the right order.
22906   SmallVector<SDValue, 16> Elts;
22907   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22908     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22909
22910   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22911     return LD;
22912
22913   if (isTargetShuffle(N->getOpcode())) {
22914     SDValue Shuffle =
22915         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22916     if (Shuffle.getNode())
22917       return Shuffle;
22918
22919     // Try recursively combining arbitrary sequences of x86 shuffle
22920     // instructions into higher-order shuffles. We do this after combining
22921     // specific PSHUF instruction sequences into their minimal form so that we
22922     // can evaluate how many specialized shuffle instructions are involved in
22923     // a particular chain.
22924     SmallVector<int, 1> NonceMask; // Just a placeholder.
22925     NonceMask.push_back(0);
22926     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22927                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22928                                       DCI, Subtarget))
22929       return SDValue(); // This routine will use CombineTo to replace N.
22930   }
22931
22932   return SDValue();
22933 }
22934
22935 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22936 /// specific shuffle of a load can be folded into a single element load.
22937 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22938 /// shuffles have been custom lowered so we need to handle those here.
22939 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22940                                          TargetLowering::DAGCombinerInfo &DCI) {
22941   if (DCI.isBeforeLegalizeOps())
22942     return SDValue();
22943
22944   SDValue InVec = N->getOperand(0);
22945   SDValue EltNo = N->getOperand(1);
22946
22947   if (!isa<ConstantSDNode>(EltNo))
22948     return SDValue();
22949
22950   EVT OriginalVT = InVec.getValueType();
22951
22952   if (InVec.getOpcode() == ISD::BITCAST) {
22953     // Don't duplicate a load with other uses.
22954     if (!InVec.hasOneUse())
22955       return SDValue();
22956     EVT BCVT = InVec.getOperand(0).getValueType();
22957     if (!BCVT.isVector() ||
22958         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22959       return SDValue();
22960     InVec = InVec.getOperand(0);
22961   }
22962
22963   EVT CurrentVT = InVec.getValueType();
22964
22965   if (!isTargetShuffle(InVec.getOpcode()))
22966     return SDValue();
22967
22968   // Don't duplicate a load with other uses.
22969   if (!InVec.hasOneUse())
22970     return SDValue();
22971
22972   SmallVector<int, 16> ShuffleMask;
22973   bool UnaryShuffle;
22974   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22975                             ShuffleMask, UnaryShuffle))
22976     return SDValue();
22977
22978   // Select the input vector, guarding against out of range extract vector.
22979   unsigned NumElems = CurrentVT.getVectorNumElements();
22980   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22981   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22982   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22983                                          : InVec.getOperand(1);
22984
22985   // If inputs to shuffle are the same for both ops, then allow 2 uses
22986   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22987                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22988
22989   if (LdNode.getOpcode() == ISD::BITCAST) {
22990     // Don't duplicate a load with other uses.
22991     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22992       return SDValue();
22993
22994     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22995     LdNode = LdNode.getOperand(0);
22996   }
22997
22998   if (!ISD::isNormalLoad(LdNode.getNode()))
22999     return SDValue();
23000
23001   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
23002
23003   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
23004     return SDValue();
23005
23006   EVT EltVT = N->getValueType(0);
23007   // If there's a bitcast before the shuffle, check if the load type and
23008   // alignment is valid.
23009   unsigned Align = LN0->getAlignment();
23010   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23011   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
23012       EltVT.getTypeForEVT(*DAG.getContext()));
23013
23014   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
23015     return SDValue();
23016
23017   // All checks match so transform back to vector_shuffle so that DAG combiner
23018   // can finish the job
23019   SDLoc dl(N);
23020
23021   // Create shuffle node taking into account the case that its a unary shuffle
23022   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
23023                                    : InVec.getOperand(1);
23024   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
23025                                  InVec.getOperand(0), Shuffle,
23026                                  &ShuffleMask[0]);
23027   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
23028   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
23029                      EltNo);
23030 }
23031
23032 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
23033 /// special and don't usually play with other vector types, it's better to
23034 /// handle them early to be sure we emit efficient code by avoiding
23035 /// store-load conversions.
23036 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
23037   if (N->getValueType(0) != MVT::x86mmx ||
23038       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
23039       N->getOperand(0)->getValueType(0) != MVT::v2i32)
23040     return SDValue();
23041
23042   SDValue V = N->getOperand(0);
23043   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
23044   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
23045     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
23046                        N->getValueType(0), V.getOperand(0));
23047
23048   return SDValue();
23049 }
23050
23051 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
23052 /// generation and convert it from being a bunch of shuffles and extracts
23053 /// into a somewhat faster sequence. For i686, the best sequence is apparently
23054 /// storing the value and loading scalars back, while for x64 we should
23055 /// use 64-bit extracts and shifts.
23056 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
23057                                          TargetLowering::DAGCombinerInfo &DCI) {
23058   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
23059     return NewOp;
23060
23061   SDValue InputVector = N->getOperand(0);
23062   SDLoc dl(InputVector);
23063   // Detect mmx to i32 conversion through a v2i32 elt extract.
23064   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
23065       N->getValueType(0) == MVT::i32 &&
23066       InputVector.getValueType() == MVT::v2i32) {
23067
23068     // The bitcast source is a direct mmx result.
23069     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
23070     if (MMXSrc.getValueType() == MVT::x86mmx)
23071       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23072                          N->getValueType(0),
23073                          InputVector.getNode()->getOperand(0));
23074
23075     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
23076     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
23077         MMXSrc.getValueType() == MVT::i64) {
23078       SDValue MMXSrcOp = MMXSrc.getOperand(0);
23079       if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
23080           MMXSrcOp.getValueType() == MVT::v1i64 &&
23081           MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
23082         return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23083                            N->getValueType(0), MMXSrcOp.getOperand(0));
23084     }
23085   }
23086
23087   EVT VT = N->getValueType(0);
23088
23089   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
23090       InputVector.getOpcode() == ISD::BITCAST &&
23091       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
23092     uint64_t ExtractedElt =
23093         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
23094     uint64_t InputValue =
23095         cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
23096     uint64_t Res = (InputValue >> ExtractedElt) & 1;
23097     return DAG.getConstant(Res, dl, MVT::i1);
23098   }
23099   // Only operate on vectors of 4 elements, where the alternative shuffling
23100   // gets to be more expensive.
23101   if (InputVector.getValueType() != MVT::v4i32)
23102     return SDValue();
23103
23104   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
23105   // single use which is a sign-extend or zero-extend, and all elements are
23106   // used.
23107   SmallVector<SDNode *, 4> Uses;
23108   unsigned ExtractedElements = 0;
23109   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
23110        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
23111     if (UI.getUse().getResNo() != InputVector.getResNo())
23112       return SDValue();
23113
23114     SDNode *Extract = *UI;
23115     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
23116       return SDValue();
23117
23118     if (Extract->getValueType(0) != MVT::i32)
23119       return SDValue();
23120     if (!Extract->hasOneUse())
23121       return SDValue();
23122     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
23123         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
23124       return SDValue();
23125     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
23126       return SDValue();
23127
23128     // Record which element was extracted.
23129     ExtractedElements |=
23130       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
23131
23132     Uses.push_back(Extract);
23133   }
23134
23135   // If not all the elements were used, this may not be worthwhile.
23136   if (ExtractedElements != 15)
23137     return SDValue();
23138
23139   // Ok, we've now decided to do the transformation.
23140   // If 64-bit shifts are legal, use the extract-shift sequence,
23141   // otherwise bounce the vector off the cache.
23142   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23143   SDValue Vals[4];
23144
23145   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
23146     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
23147     auto &DL = DAG.getDataLayout();
23148     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
23149     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23150       DAG.getConstant(0, dl, VecIdxTy));
23151     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23152       DAG.getConstant(1, dl, VecIdxTy));
23153
23154     SDValue ShAmt = DAG.getConstant(
23155         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
23156     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
23157     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23158       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
23159     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
23160     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23161       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
23162   } else {
23163     // Store the value to a temporary stack slot.
23164     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
23165     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
23166       MachinePointerInfo(), false, false, 0);
23167
23168     EVT ElementType = InputVector.getValueType().getVectorElementType();
23169     unsigned EltSize = ElementType.getSizeInBits() / 8;
23170
23171     // Replace each use (extract) with a load of the appropriate element.
23172     for (unsigned i = 0; i < 4; ++i) {
23173       uint64_t Offset = EltSize * i;
23174       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
23175       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
23176
23177       SDValue ScalarAddr =
23178           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
23179
23180       // Load the scalar.
23181       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
23182                             ScalarAddr, MachinePointerInfo(),
23183                             false, false, false, 0);
23184
23185     }
23186   }
23187
23188   // Replace the extracts
23189   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
23190     UE = Uses.end(); UI != UE; ++UI) {
23191     SDNode *Extract = *UI;
23192
23193     SDValue Idx = Extract->getOperand(1);
23194     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
23195     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
23196   }
23197
23198   // The replacement was made in place; don't return anything.
23199   return SDValue();
23200 }
23201
23202 static SDValue
23203 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
23204                                       const X86Subtarget *Subtarget) {
23205   SDLoc dl(N);
23206   SDValue Cond = N->getOperand(0);
23207   SDValue LHS = N->getOperand(1);
23208   SDValue RHS = N->getOperand(2);
23209
23210   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
23211     SDValue CondSrc = Cond->getOperand(0);
23212     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
23213       Cond = CondSrc->getOperand(0);
23214   }
23215
23216   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
23217     return SDValue();
23218
23219   // A vselect where all conditions and data are constants can be optimized into
23220   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
23221   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
23222       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
23223     return SDValue();
23224
23225   unsigned MaskValue = 0;
23226   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
23227     return SDValue();
23228
23229   MVT VT = N->getSimpleValueType(0);
23230   unsigned NumElems = VT.getVectorNumElements();
23231   SmallVector<int, 8> ShuffleMask(NumElems, -1);
23232   for (unsigned i = 0; i < NumElems; ++i) {
23233     // Be sure we emit undef where we can.
23234     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
23235       ShuffleMask[i] = -1;
23236     else
23237       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
23238   }
23239
23240   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23241   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
23242     return SDValue();
23243   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
23244 }
23245
23246 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
23247 /// nodes.
23248 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
23249                                     TargetLowering::DAGCombinerInfo &DCI,
23250                                     const X86Subtarget *Subtarget) {
23251   SDLoc DL(N);
23252   SDValue Cond = N->getOperand(0);
23253   // Get the LHS/RHS of the select.
23254   SDValue LHS = N->getOperand(1);
23255   SDValue RHS = N->getOperand(2);
23256   EVT VT = LHS.getValueType();
23257   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23258
23259   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
23260   // instructions match the semantics of the common C idiom x<y?x:y but not
23261   // x<=y?x:y, because of how they handle negative zero (which can be
23262   // ignored in unsafe-math mode).
23263   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
23264   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
23265       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
23266       (Subtarget->hasSSE2() ||
23267        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
23268     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23269
23270     unsigned Opcode = 0;
23271     // Check for x CC y ? x : y.
23272     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23273         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23274       switch (CC) {
23275       default: break;
23276       case ISD::SETULT:
23277         // Converting this to a min would handle NaNs incorrectly, and swapping
23278         // the operands would cause it to handle comparisons between positive
23279         // and negative zero incorrectly.
23280         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23281           if (!DAG.getTarget().Options.UnsafeFPMath &&
23282               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23283             break;
23284           std::swap(LHS, RHS);
23285         }
23286         Opcode = X86ISD::FMIN;
23287         break;
23288       case ISD::SETOLE:
23289         // Converting this to a min would handle comparisons between positive
23290         // and negative zero incorrectly.
23291         if (!DAG.getTarget().Options.UnsafeFPMath &&
23292             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23293           break;
23294         Opcode = X86ISD::FMIN;
23295         break;
23296       case ISD::SETULE:
23297         // Converting this to a min would handle both negative zeros and NaNs
23298         // incorrectly, but we can swap the operands to fix both.
23299         std::swap(LHS, RHS);
23300       case ISD::SETOLT:
23301       case ISD::SETLT:
23302       case ISD::SETLE:
23303         Opcode = X86ISD::FMIN;
23304         break;
23305
23306       case ISD::SETOGE:
23307         // Converting this to a max would handle comparisons between positive
23308         // and negative zero incorrectly.
23309         if (!DAG.getTarget().Options.UnsafeFPMath &&
23310             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23311           break;
23312         Opcode = X86ISD::FMAX;
23313         break;
23314       case ISD::SETUGT:
23315         // Converting this to a max would handle NaNs incorrectly, and swapping
23316         // the operands would cause it to handle comparisons between positive
23317         // and negative zero incorrectly.
23318         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23319           if (!DAG.getTarget().Options.UnsafeFPMath &&
23320               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23321             break;
23322           std::swap(LHS, RHS);
23323         }
23324         Opcode = X86ISD::FMAX;
23325         break;
23326       case ISD::SETUGE:
23327         // Converting this to a max would handle both negative zeros and NaNs
23328         // incorrectly, but we can swap the operands to fix both.
23329         std::swap(LHS, RHS);
23330       case ISD::SETOGT:
23331       case ISD::SETGT:
23332       case ISD::SETGE:
23333         Opcode = X86ISD::FMAX;
23334         break;
23335       }
23336     // Check for x CC y ? y : x -- a min/max with reversed arms.
23337     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
23338                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
23339       switch (CC) {
23340       default: break;
23341       case ISD::SETOGE:
23342         // Converting this to a min would handle comparisons between positive
23343         // and negative zero incorrectly, and swapping the operands would
23344         // cause it to handle NaNs incorrectly.
23345         if (!DAG.getTarget().Options.UnsafeFPMath &&
23346             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
23347           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23348             break;
23349           std::swap(LHS, RHS);
23350         }
23351         Opcode = X86ISD::FMIN;
23352         break;
23353       case ISD::SETUGT:
23354         // Converting this to a min would handle NaNs incorrectly.
23355         if (!DAG.getTarget().Options.UnsafeFPMath &&
23356             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23357           break;
23358         Opcode = X86ISD::FMIN;
23359         break;
23360       case ISD::SETUGE:
23361         // Converting this to a min would handle both negative zeros and NaNs
23362         // incorrectly, but we can swap the operands to fix both.
23363         std::swap(LHS, RHS);
23364       case ISD::SETOGT:
23365       case ISD::SETGT:
23366       case ISD::SETGE:
23367         Opcode = X86ISD::FMIN;
23368         break;
23369
23370       case ISD::SETULT:
23371         // Converting this to a max would handle NaNs incorrectly.
23372         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23373           break;
23374         Opcode = X86ISD::FMAX;
23375         break;
23376       case ISD::SETOLE:
23377         // Converting this to a max would handle comparisons between positive
23378         // and negative zero incorrectly, and swapping the operands would
23379         // cause it to handle NaNs incorrectly.
23380         if (!DAG.getTarget().Options.UnsafeFPMath &&
23381             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23382           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23383             break;
23384           std::swap(LHS, RHS);
23385         }
23386         Opcode = X86ISD::FMAX;
23387         break;
23388       case ISD::SETULE:
23389         // Converting this to a max would handle both negative zeros and NaNs
23390         // incorrectly, but we can swap the operands to fix both.
23391         std::swap(LHS, RHS);
23392       case ISD::SETOLT:
23393       case ISD::SETLT:
23394       case ISD::SETLE:
23395         Opcode = X86ISD::FMAX;
23396         break;
23397       }
23398     }
23399
23400     if (Opcode)
23401       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23402   }
23403
23404   EVT CondVT = Cond.getValueType();
23405   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23406       CondVT.getVectorElementType() == MVT::i1) {
23407     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23408     // lowering on KNL. In this case we convert it to
23409     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23410     // The same situation for all 128 and 256-bit vectors of i8 and i16.
23411     // Since SKX these selects have a proper lowering.
23412     EVT OpVT = LHS.getValueType();
23413     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23414         (OpVT.getVectorElementType() == MVT::i8 ||
23415          OpVT.getVectorElementType() == MVT::i16) &&
23416         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23417       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23418       DCI.AddToWorklist(Cond.getNode());
23419       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23420     }
23421   }
23422   // If this is a select between two integer constants, try to do some
23423   // optimizations.
23424   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23425     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23426       // Don't do this for crazy integer types.
23427       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23428         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23429         // so that TrueC (the true value) is larger than FalseC.
23430         bool NeedsCondInvert = false;
23431
23432         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23433             // Efficiently invertible.
23434             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
23435              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
23436               isa<ConstantSDNode>(Cond.getOperand(1))))) {
23437           NeedsCondInvert = true;
23438           std::swap(TrueC, FalseC);
23439         }
23440
23441         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
23442         if (FalseC->getAPIntValue() == 0 &&
23443             TrueC->getAPIntValue().isPowerOf2()) {
23444           if (NeedsCondInvert) // Invert the condition if needed.
23445             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23446                                DAG.getConstant(1, DL, Cond.getValueType()));
23447
23448           // Zero extend the condition if needed.
23449           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23450
23451           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23452           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23453                              DAG.getConstant(ShAmt, DL, MVT::i8));
23454         }
23455
23456         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23457         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23458           if (NeedsCondInvert) // Invert the condition if needed.
23459             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23460                                DAG.getConstant(1, DL, Cond.getValueType()));
23461
23462           // Zero extend the condition if needed.
23463           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23464                              FalseC->getValueType(0), Cond);
23465           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23466                              SDValue(FalseC, 0));
23467         }
23468
23469         // Optimize cases that will turn into an LEA instruction.  This requires
23470         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23471         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23472           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23473           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23474
23475           bool isFastMultiplier = false;
23476           if (Diff < 10) {
23477             switch ((unsigned char)Diff) {
23478               default: break;
23479               case 1:  // result = add base, cond
23480               case 2:  // result = lea base(    , cond*2)
23481               case 3:  // result = lea base(cond, cond*2)
23482               case 4:  // result = lea base(    , cond*4)
23483               case 5:  // result = lea base(cond, cond*4)
23484               case 8:  // result = lea base(    , cond*8)
23485               case 9:  // result = lea base(cond, cond*8)
23486                 isFastMultiplier = true;
23487                 break;
23488             }
23489           }
23490
23491           if (isFastMultiplier) {
23492             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23493             if (NeedsCondInvert) // Invert the condition if needed.
23494               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23495                                  DAG.getConstant(1, DL, Cond.getValueType()));
23496
23497             // Zero extend the condition if needed.
23498             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23499                                Cond);
23500             // Scale the condition by the difference.
23501             if (Diff != 1)
23502               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23503                                  DAG.getConstant(Diff, DL,
23504                                                  Cond.getValueType()));
23505
23506             // Add the base if non-zero.
23507             if (FalseC->getAPIntValue() != 0)
23508               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23509                                  SDValue(FalseC, 0));
23510             return Cond;
23511           }
23512         }
23513       }
23514   }
23515
23516   // Canonicalize max and min:
23517   // (x > y) ? x : y -> (x >= y) ? x : y
23518   // (x < y) ? x : y -> (x <= y) ? x : y
23519   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23520   // the need for an extra compare
23521   // against zero. e.g.
23522   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23523   // subl   %esi, %edi
23524   // testl  %edi, %edi
23525   // movl   $0, %eax
23526   // cmovgl %edi, %eax
23527   // =>
23528   // xorl   %eax, %eax
23529   // subl   %esi, $edi
23530   // cmovsl %eax, %edi
23531   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23532       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23533       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23534     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23535     switch (CC) {
23536     default: break;
23537     case ISD::SETLT:
23538     case ISD::SETGT: {
23539       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23540       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23541                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23542       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23543     }
23544     }
23545   }
23546
23547   // Early exit check
23548   if (!TLI.isTypeLegal(VT))
23549     return SDValue();
23550
23551   // Match VSELECTs into subs with unsigned saturation.
23552   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23553       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23554       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23555        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23556     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23557
23558     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23559     // left side invert the predicate to simplify logic below.
23560     SDValue Other;
23561     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23562       Other = RHS;
23563       CC = ISD::getSetCCInverse(CC, true);
23564     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23565       Other = LHS;
23566     }
23567
23568     if (Other.getNode() && Other->getNumOperands() == 2 &&
23569         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23570       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23571       SDValue CondRHS = Cond->getOperand(1);
23572
23573       // Look for a general sub with unsigned saturation first.
23574       // x >= y ? x-y : 0 --> subus x, y
23575       // x >  y ? x-y : 0 --> subus x, y
23576       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23577           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23578         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23579
23580       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23581         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23582           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23583             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23584               // If the RHS is a constant we have to reverse the const
23585               // canonicalization.
23586               // x > C-1 ? x+-C : 0 --> subus x, C
23587               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23588                   CondRHSConst->getAPIntValue() ==
23589                       (-OpRHSConst->getAPIntValue() - 1))
23590                 return DAG.getNode(
23591                     X86ISD::SUBUS, DL, VT, OpLHS,
23592                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
23593
23594           // Another special case: If C was a sign bit, the sub has been
23595           // canonicalized into a xor.
23596           // FIXME: Would it be better to use computeKnownBits to determine
23597           //        whether it's safe to decanonicalize the xor?
23598           // x s< 0 ? x^C : 0 --> subus x, C
23599           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23600               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23601               OpRHSConst->getAPIntValue().isSignBit())
23602             // Note that we have to rebuild the RHS constant here to ensure we
23603             // don't rely on particular values of undef lanes.
23604             return DAG.getNode(
23605                 X86ISD::SUBUS, DL, VT, OpLHS,
23606                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
23607         }
23608     }
23609   }
23610
23611   // Simplify vector selection if condition value type matches vselect
23612   // operand type
23613   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23614     assert(Cond.getValueType().isVector() &&
23615            "vector select expects a vector selector!");
23616
23617     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23618     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23619
23620     // Try invert the condition if true value is not all 1s and false value
23621     // is not all 0s.
23622     if (!TValIsAllOnes && !FValIsAllZeros &&
23623         // Check if the selector will be produced by CMPP*/PCMP*
23624         Cond.getOpcode() == ISD::SETCC &&
23625         // Check if SETCC has already been promoted
23626         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23627             CondVT) {
23628       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23629       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23630
23631       if (TValIsAllZeros || FValIsAllOnes) {
23632         SDValue CC = Cond.getOperand(2);
23633         ISD::CondCode NewCC =
23634           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23635                                Cond.getOperand(0).getValueType().isInteger());
23636         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23637         std::swap(LHS, RHS);
23638         TValIsAllOnes = FValIsAllOnes;
23639         FValIsAllZeros = TValIsAllZeros;
23640       }
23641     }
23642
23643     if (TValIsAllOnes || FValIsAllZeros) {
23644       SDValue Ret;
23645
23646       if (TValIsAllOnes && FValIsAllZeros)
23647         Ret = Cond;
23648       else if (TValIsAllOnes)
23649         Ret =
23650             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23651       else if (FValIsAllZeros)
23652         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23653                           DAG.getBitcast(CondVT, LHS));
23654
23655       return DAG.getBitcast(VT, Ret);
23656     }
23657   }
23658
23659   // We should generate an X86ISD::BLENDI from a vselect if its argument
23660   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23661   // constants. This specific pattern gets generated when we split a
23662   // selector for a 512 bit vector in a machine without AVX512 (but with
23663   // 256-bit vectors), during legalization:
23664   //
23665   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23666   //
23667   // Iff we find this pattern and the build_vectors are built from
23668   // constants, we translate the vselect into a shuffle_vector that we
23669   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23670   if ((N->getOpcode() == ISD::VSELECT ||
23671        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23672       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23673     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23674     if (Shuffle.getNode())
23675       return Shuffle;
23676   }
23677
23678   // If this is a *dynamic* select (non-constant condition) and we can match
23679   // this node with one of the variable blend instructions, restructure the
23680   // condition so that the blends can use the high bit of each element and use
23681   // SimplifyDemandedBits to simplify the condition operand.
23682   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23683       !DCI.isBeforeLegalize() &&
23684       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23685     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23686
23687     // Don't optimize vector selects that map to mask-registers.
23688     if (BitWidth == 1)
23689       return SDValue();
23690
23691     // We can only handle the cases where VSELECT is directly legal on the
23692     // subtarget. We custom lower VSELECT nodes with constant conditions and
23693     // this makes it hard to see whether a dynamic VSELECT will correctly
23694     // lower, so we both check the operation's status and explicitly handle the
23695     // cases where a *dynamic* blend will fail even though a constant-condition
23696     // blend could be custom lowered.
23697     // FIXME: We should find a better way to handle this class of problems.
23698     // Potentially, we should combine constant-condition vselect nodes
23699     // pre-legalization into shuffles and not mark as many types as custom
23700     // lowered.
23701     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23702       return SDValue();
23703     // FIXME: We don't support i16-element blends currently. We could and
23704     // should support them by making *all* the bits in the condition be set
23705     // rather than just the high bit and using an i8-element blend.
23706     if (VT.getScalarType() == MVT::i16)
23707       return SDValue();
23708     // Dynamic blending was only available from SSE4.1 onward.
23709     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23710       return SDValue();
23711     // Byte blends are only available in AVX2
23712     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23713         !Subtarget->hasAVX2())
23714       return SDValue();
23715
23716     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23717     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23718
23719     APInt KnownZero, KnownOne;
23720     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23721                                           DCI.isBeforeLegalizeOps());
23722     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23723         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23724                                  TLO)) {
23725       // If we changed the computation somewhere in the DAG, this change
23726       // will affect all users of Cond.
23727       // Make sure it is fine and update all the nodes so that we do not
23728       // use the generic VSELECT anymore. Otherwise, we may perform
23729       // wrong optimizations as we messed up with the actual expectation
23730       // for the vector boolean values.
23731       if (Cond != TLO.Old) {
23732         // Check all uses of that condition operand to check whether it will be
23733         // consumed by non-BLEND instructions, which may depend on all bits are
23734         // set properly.
23735         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23736              I != E; ++I)
23737           if (I->getOpcode() != ISD::VSELECT)
23738             // TODO: Add other opcodes eventually lowered into BLEND.
23739             return SDValue();
23740
23741         // Update all the users of the condition, before committing the change,
23742         // so that the VSELECT optimizations that expect the correct vector
23743         // boolean value will not be triggered.
23744         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23745              I != E; ++I)
23746           DAG.ReplaceAllUsesOfValueWith(
23747               SDValue(*I, 0),
23748               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23749                           Cond, I->getOperand(1), I->getOperand(2)));
23750         DCI.CommitTargetLoweringOpt(TLO);
23751         return SDValue();
23752       }
23753       // At this point, only Cond is changed. Change the condition
23754       // just for N to keep the opportunity to optimize all other
23755       // users their own way.
23756       DAG.ReplaceAllUsesOfValueWith(
23757           SDValue(N, 0),
23758           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23759                       TLO.New, N->getOperand(1), N->getOperand(2)));
23760       return SDValue();
23761     }
23762   }
23763
23764   return SDValue();
23765 }
23766
23767 // Check whether a boolean test is testing a boolean value generated by
23768 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23769 // code.
23770 //
23771 // Simplify the following patterns:
23772 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23773 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23774 // to (Op EFLAGS Cond)
23775 //
23776 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23777 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23778 // to (Op EFLAGS !Cond)
23779 //
23780 // where Op could be BRCOND or CMOV.
23781 //
23782 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23783   // Quit if not CMP and SUB with its value result used.
23784   if (Cmp.getOpcode() != X86ISD::CMP &&
23785       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23786       return SDValue();
23787
23788   // Quit if not used as a boolean value.
23789   if (CC != X86::COND_E && CC != X86::COND_NE)
23790     return SDValue();
23791
23792   // Check CMP operands. One of them should be 0 or 1 and the other should be
23793   // an SetCC or extended from it.
23794   SDValue Op1 = Cmp.getOperand(0);
23795   SDValue Op2 = Cmp.getOperand(1);
23796
23797   SDValue SetCC;
23798   const ConstantSDNode* C = nullptr;
23799   bool needOppositeCond = (CC == X86::COND_E);
23800   bool checkAgainstTrue = false; // Is it a comparison against 1?
23801
23802   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23803     SetCC = Op2;
23804   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23805     SetCC = Op1;
23806   else // Quit if all operands are not constants.
23807     return SDValue();
23808
23809   if (C->getZExtValue() == 1) {
23810     needOppositeCond = !needOppositeCond;
23811     checkAgainstTrue = true;
23812   } else if (C->getZExtValue() != 0)
23813     // Quit if the constant is neither 0 or 1.
23814     return SDValue();
23815
23816   bool truncatedToBoolWithAnd = false;
23817   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23818   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23819          SetCC.getOpcode() == ISD::TRUNCATE ||
23820          SetCC.getOpcode() == ISD::AND) {
23821     if (SetCC.getOpcode() == ISD::AND) {
23822       int OpIdx = -1;
23823       ConstantSDNode *CS;
23824       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23825           CS->getZExtValue() == 1)
23826         OpIdx = 1;
23827       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23828           CS->getZExtValue() == 1)
23829         OpIdx = 0;
23830       if (OpIdx == -1)
23831         break;
23832       SetCC = SetCC.getOperand(OpIdx);
23833       truncatedToBoolWithAnd = true;
23834     } else
23835       SetCC = SetCC.getOperand(0);
23836   }
23837
23838   switch (SetCC.getOpcode()) {
23839   case X86ISD::SETCC_CARRY:
23840     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23841     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23842     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23843     // truncated to i1 using 'and'.
23844     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23845       break;
23846     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23847            "Invalid use of SETCC_CARRY!");
23848     // FALL THROUGH
23849   case X86ISD::SETCC:
23850     // Set the condition code or opposite one if necessary.
23851     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23852     if (needOppositeCond)
23853       CC = X86::GetOppositeBranchCondition(CC);
23854     return SetCC.getOperand(1);
23855   case X86ISD::CMOV: {
23856     // Check whether false/true value has canonical one, i.e. 0 or 1.
23857     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23858     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23859     // Quit if true value is not a constant.
23860     if (!TVal)
23861       return SDValue();
23862     // Quit if false value is not a constant.
23863     if (!FVal) {
23864       SDValue Op = SetCC.getOperand(0);
23865       // Skip 'zext' or 'trunc' node.
23866       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23867           Op.getOpcode() == ISD::TRUNCATE)
23868         Op = Op.getOperand(0);
23869       // A special case for rdrand/rdseed, where 0 is set if false cond is
23870       // found.
23871       if ((Op.getOpcode() != X86ISD::RDRAND &&
23872            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23873         return SDValue();
23874     }
23875     // Quit if false value is not the constant 0 or 1.
23876     bool FValIsFalse = true;
23877     if (FVal && FVal->getZExtValue() != 0) {
23878       if (FVal->getZExtValue() != 1)
23879         return SDValue();
23880       // If FVal is 1, opposite cond is needed.
23881       needOppositeCond = !needOppositeCond;
23882       FValIsFalse = false;
23883     }
23884     // Quit if TVal is not the constant opposite of FVal.
23885     if (FValIsFalse && TVal->getZExtValue() != 1)
23886       return SDValue();
23887     if (!FValIsFalse && TVal->getZExtValue() != 0)
23888       return SDValue();
23889     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23890     if (needOppositeCond)
23891       CC = X86::GetOppositeBranchCondition(CC);
23892     return SetCC.getOperand(3);
23893   }
23894   }
23895
23896   return SDValue();
23897 }
23898
23899 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23900 /// Match:
23901 ///   (X86or (X86setcc) (X86setcc))
23902 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
23903 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23904                                            X86::CondCode &CC1, SDValue &Flags,
23905                                            bool &isAnd) {
23906   if (Cond->getOpcode() == X86ISD::CMP) {
23907     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23908     if (!CondOp1C || !CondOp1C->isNullValue())
23909       return false;
23910
23911     Cond = Cond->getOperand(0);
23912   }
23913
23914   isAnd = false;
23915
23916   SDValue SetCC0, SetCC1;
23917   switch (Cond->getOpcode()) {
23918   default: return false;
23919   case ISD::AND:
23920   case X86ISD::AND:
23921     isAnd = true;
23922     // fallthru
23923   case ISD::OR:
23924   case X86ISD::OR:
23925     SetCC0 = Cond->getOperand(0);
23926     SetCC1 = Cond->getOperand(1);
23927     break;
23928   };
23929
23930   // Make sure we have SETCC nodes, using the same flags value.
23931   if (SetCC0.getOpcode() != X86ISD::SETCC ||
23932       SetCC1.getOpcode() != X86ISD::SETCC ||
23933       SetCC0->getOperand(1) != SetCC1->getOperand(1))
23934     return false;
23935
23936   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23937   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23938   Flags = SetCC0->getOperand(1);
23939   return true;
23940 }
23941
23942 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23943 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23944                                   TargetLowering::DAGCombinerInfo &DCI,
23945                                   const X86Subtarget *Subtarget) {
23946   SDLoc DL(N);
23947
23948   // If the flag operand isn't dead, don't touch this CMOV.
23949   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23950     return SDValue();
23951
23952   SDValue FalseOp = N->getOperand(0);
23953   SDValue TrueOp = N->getOperand(1);
23954   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23955   SDValue Cond = N->getOperand(3);
23956
23957   if (CC == X86::COND_E || CC == X86::COND_NE) {
23958     switch (Cond.getOpcode()) {
23959     default: break;
23960     case X86ISD::BSR:
23961     case X86ISD::BSF:
23962       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23963       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23964         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23965     }
23966   }
23967
23968   SDValue Flags;
23969
23970   Flags = checkBoolTestSetCCCombine(Cond, CC);
23971   if (Flags.getNode() &&
23972       // Extra check as FCMOV only supports a subset of X86 cond.
23973       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23974     SDValue Ops[] = { FalseOp, TrueOp,
23975                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23976     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23977   }
23978
23979   // If this is a select between two integer constants, try to do some
23980   // optimizations.  Note that the operands are ordered the opposite of SELECT
23981   // operands.
23982   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23983     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23984       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23985       // larger than FalseC (the false value).
23986       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23987         CC = X86::GetOppositeBranchCondition(CC);
23988         std::swap(TrueC, FalseC);
23989         std::swap(TrueOp, FalseOp);
23990       }
23991
23992       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23993       // This is efficient for any integer data type (including i8/i16) and
23994       // shift amount.
23995       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23996         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23997                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23998
23999         // Zero extend the condition if needed.
24000         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
24001
24002         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24003         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
24004                            DAG.getConstant(ShAmt, DL, MVT::i8));
24005         if (N->getNumValues() == 2)  // Dead flag value?
24006           return DCI.CombineTo(N, Cond, SDValue());
24007         return Cond;
24008       }
24009
24010       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
24011       // for any integer data type, including i8/i16.
24012       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24013         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24014                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24015
24016         // Zero extend the condition if needed.
24017         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24018                            FalseC->getValueType(0), Cond);
24019         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24020                            SDValue(FalseC, 0));
24021
24022         if (N->getNumValues() == 2)  // Dead flag value?
24023           return DCI.CombineTo(N, Cond, SDValue());
24024         return Cond;
24025       }
24026
24027       // Optimize cases that will turn into an LEA instruction.  This requires
24028       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24029       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24030         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24031         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24032
24033         bool isFastMultiplier = false;
24034         if (Diff < 10) {
24035           switch ((unsigned char)Diff) {
24036           default: break;
24037           case 1:  // result = add base, cond
24038           case 2:  // result = lea base(    , cond*2)
24039           case 3:  // result = lea base(cond, cond*2)
24040           case 4:  // result = lea base(    , cond*4)
24041           case 5:  // result = lea base(cond, cond*4)
24042           case 8:  // result = lea base(    , cond*8)
24043           case 9:  // result = lea base(cond, cond*8)
24044             isFastMultiplier = true;
24045             break;
24046           }
24047         }
24048
24049         if (isFastMultiplier) {
24050           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24051           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24052                              DAG.getConstant(CC, DL, MVT::i8), Cond);
24053           // Zero extend the condition if needed.
24054           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24055                              Cond);
24056           // Scale the condition by the difference.
24057           if (Diff != 1)
24058             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24059                                DAG.getConstant(Diff, DL, Cond.getValueType()));
24060
24061           // Add the base if non-zero.
24062           if (FalseC->getAPIntValue() != 0)
24063             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24064                                SDValue(FalseC, 0));
24065           if (N->getNumValues() == 2)  // Dead flag value?
24066             return DCI.CombineTo(N, Cond, SDValue());
24067           return Cond;
24068         }
24069       }
24070     }
24071   }
24072
24073   // Handle these cases:
24074   //   (select (x != c), e, c) -> select (x != c), e, x),
24075   //   (select (x == c), c, e) -> select (x == c), x, e)
24076   // where the c is an integer constant, and the "select" is the combination
24077   // of CMOV and CMP.
24078   //
24079   // The rationale for this change is that the conditional-move from a constant
24080   // needs two instructions, however, conditional-move from a register needs
24081   // only one instruction.
24082   //
24083   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
24084   //  some instruction-combining opportunities. This opt needs to be
24085   //  postponed as late as possible.
24086   //
24087   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
24088     // the DCI.xxxx conditions are provided to postpone the optimization as
24089     // late as possible.
24090
24091     ConstantSDNode *CmpAgainst = nullptr;
24092     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
24093         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
24094         !isa<ConstantSDNode>(Cond.getOperand(0))) {
24095
24096       if (CC == X86::COND_NE &&
24097           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
24098         CC = X86::GetOppositeBranchCondition(CC);
24099         std::swap(TrueOp, FalseOp);
24100       }
24101
24102       if (CC == X86::COND_E &&
24103           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
24104         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
24105                           DAG.getConstant(CC, DL, MVT::i8), Cond };
24106         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
24107       }
24108     }
24109   }
24110
24111   // Fold and/or of setcc's to double CMOV:
24112   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
24113   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
24114   //
24115   // This combine lets us generate:
24116   //   cmovcc1 (jcc1 if we don't have CMOV)
24117   //   cmovcc2 (same)
24118   // instead of:
24119   //   setcc1
24120   //   setcc2
24121   //   and/or
24122   //   cmovne (jne if we don't have CMOV)
24123   // When we can't use the CMOV instruction, it might increase branch
24124   // mispredicts.
24125   // When we can use CMOV, or when there is no mispredict, this improves
24126   // throughput and reduces register pressure.
24127   //
24128   if (CC == X86::COND_NE) {
24129     SDValue Flags;
24130     X86::CondCode CC0, CC1;
24131     bool isAndSetCC;
24132     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
24133       if (isAndSetCC) {
24134         std::swap(FalseOp, TrueOp);
24135         CC0 = X86::GetOppositeBranchCondition(CC0);
24136         CC1 = X86::GetOppositeBranchCondition(CC1);
24137       }
24138
24139       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
24140         Flags};
24141       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
24142       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
24143       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24144       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
24145       return CMOV;
24146     }
24147   }
24148
24149   return SDValue();
24150 }
24151
24152 /// PerformMulCombine - Optimize a single multiply with constant into two
24153 /// in order to implement it with two cheaper instructions, e.g.
24154 /// LEA + SHL, LEA + LEA.
24155 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
24156                                  TargetLowering::DAGCombinerInfo &DCI) {
24157   // An imul is usually smaller than the alternative sequence.
24158   if (DAG.getMachineFunction().getFunction()->optForMinSize())
24159     return SDValue();
24160
24161   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
24162     return SDValue();
24163
24164   EVT VT = N->getValueType(0);
24165   if (VT != MVT::i64 && VT != MVT::i32)
24166     return SDValue();
24167
24168   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
24169   if (!C)
24170     return SDValue();
24171   uint64_t MulAmt = C->getZExtValue();
24172   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
24173     return SDValue();
24174
24175   uint64_t MulAmt1 = 0;
24176   uint64_t MulAmt2 = 0;
24177   if ((MulAmt % 9) == 0) {
24178     MulAmt1 = 9;
24179     MulAmt2 = MulAmt / 9;
24180   } else if ((MulAmt % 5) == 0) {
24181     MulAmt1 = 5;
24182     MulAmt2 = MulAmt / 5;
24183   } else if ((MulAmt % 3) == 0) {
24184     MulAmt1 = 3;
24185     MulAmt2 = MulAmt / 3;
24186   }
24187   if (MulAmt2 &&
24188       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
24189     SDLoc DL(N);
24190
24191     if (isPowerOf2_64(MulAmt2) &&
24192         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
24193       // If second multiplifer is pow2, issue it first. We want the multiply by
24194       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
24195       // is an add.
24196       std::swap(MulAmt1, MulAmt2);
24197
24198     SDValue NewMul;
24199     if (isPowerOf2_64(MulAmt1))
24200       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
24201                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
24202     else
24203       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
24204                            DAG.getConstant(MulAmt1, DL, VT));
24205
24206     if (isPowerOf2_64(MulAmt2))
24207       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
24208                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
24209     else
24210       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
24211                            DAG.getConstant(MulAmt2, DL, VT));
24212
24213     // Do not add new nodes to DAG combiner worklist.
24214     DCI.CombineTo(N, NewMul, false);
24215   }
24216   return SDValue();
24217 }
24218
24219 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
24220   SDValue N0 = N->getOperand(0);
24221   SDValue N1 = N->getOperand(1);
24222   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
24223   EVT VT = N0.getValueType();
24224
24225   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
24226   // since the result of setcc_c is all zero's or all ones.
24227   if (VT.isInteger() && !VT.isVector() &&
24228       N1C && N0.getOpcode() == ISD::AND &&
24229       N0.getOperand(1).getOpcode() == ISD::Constant) {
24230     SDValue N00 = N0.getOperand(0);
24231     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
24232     APInt ShAmt = N1C->getAPIntValue();
24233     Mask = Mask.shl(ShAmt);
24234     bool MaskOK = false;
24235     // We can handle cases concerning bit-widening nodes containing setcc_c if
24236     // we carefully interrogate the mask to make sure we are semantics
24237     // preserving.
24238     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
24239     // of the underlying setcc_c operation if the setcc_c was zero extended.
24240     // Consider the following example:
24241     //   zext(setcc_c)                 -> i32 0x0000FFFF
24242     //   c1                            -> i32 0x0000FFFF
24243     //   c2                            -> i32 0x00000001
24244     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
24245     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
24246     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24247       MaskOK = true;
24248     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
24249                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24250       MaskOK = true;
24251     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
24252                 N00.getOpcode() == ISD::ANY_EXTEND) &&
24253                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24254       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
24255     }
24256     if (MaskOK && Mask != 0) {
24257       SDLoc DL(N);
24258       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
24259     }
24260   }
24261
24262   // Hardware support for vector shifts is sparse which makes us scalarize the
24263   // vector operations in many cases. Also, on sandybridge ADD is faster than
24264   // shl.
24265   // (shl V, 1) -> add V,V
24266   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
24267     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
24268       assert(N0.getValueType().isVector() && "Invalid vector shift type");
24269       // We shift all of the values by one. In many cases we do not have
24270       // hardware support for this operation. This is better expressed as an ADD
24271       // of two values.
24272       if (N1SplatC->getAPIntValue() == 1)
24273         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
24274     }
24275
24276   return SDValue();
24277 }
24278
24279 /// \brief Returns a vector of 0s if the node in input is a vector logical
24280 /// shift by a constant amount which is known to be bigger than or equal
24281 /// to the vector element size in bits.
24282 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
24283                                       const X86Subtarget *Subtarget) {
24284   EVT VT = N->getValueType(0);
24285
24286   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
24287       (!Subtarget->hasInt256() ||
24288        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
24289     return SDValue();
24290
24291   SDValue Amt = N->getOperand(1);
24292   SDLoc DL(N);
24293   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
24294     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
24295       APInt ShiftAmt = AmtSplat->getAPIntValue();
24296       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
24297
24298       // SSE2/AVX2 logical shifts always return a vector of 0s
24299       // if the shift amount is bigger than or equal to
24300       // the element size. The constant shift amount will be
24301       // encoded as a 8-bit immediate.
24302       if (ShiftAmt.trunc(8).uge(MaxAmount))
24303         return getZeroVector(VT, Subtarget, DAG, DL);
24304     }
24305
24306   return SDValue();
24307 }
24308
24309 /// PerformShiftCombine - Combine shifts.
24310 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
24311                                    TargetLowering::DAGCombinerInfo &DCI,
24312                                    const X86Subtarget *Subtarget) {
24313   if (N->getOpcode() == ISD::SHL)
24314     if (SDValue V = PerformSHLCombine(N, DAG))
24315       return V;
24316
24317   // Try to fold this logical shift into a zero vector.
24318   if (N->getOpcode() != ISD::SRA)
24319     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
24320       return V;
24321
24322   return SDValue();
24323 }
24324
24325 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
24326 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
24327 // and friends.  Likewise for OR -> CMPNEQSS.
24328 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
24329                             TargetLowering::DAGCombinerInfo &DCI,
24330                             const X86Subtarget *Subtarget) {
24331   unsigned opcode;
24332
24333   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
24334   // we're requiring SSE2 for both.
24335   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
24336     SDValue N0 = N->getOperand(0);
24337     SDValue N1 = N->getOperand(1);
24338     SDValue CMP0 = N0->getOperand(1);
24339     SDValue CMP1 = N1->getOperand(1);
24340     SDLoc DL(N);
24341
24342     // The SETCCs should both refer to the same CMP.
24343     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
24344       return SDValue();
24345
24346     SDValue CMP00 = CMP0->getOperand(0);
24347     SDValue CMP01 = CMP0->getOperand(1);
24348     EVT     VT    = CMP00.getValueType();
24349
24350     if (VT == MVT::f32 || VT == MVT::f64) {
24351       bool ExpectingFlags = false;
24352       // Check for any users that want flags:
24353       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
24354            !ExpectingFlags && UI != UE; ++UI)
24355         switch (UI->getOpcode()) {
24356         default:
24357         case ISD::BR_CC:
24358         case ISD::BRCOND:
24359         case ISD::SELECT:
24360           ExpectingFlags = true;
24361           break;
24362         case ISD::CopyToReg:
24363         case ISD::SIGN_EXTEND:
24364         case ISD::ZERO_EXTEND:
24365         case ISD::ANY_EXTEND:
24366           break;
24367         }
24368
24369       if (!ExpectingFlags) {
24370         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24371         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24372
24373         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24374           X86::CondCode tmp = cc0;
24375           cc0 = cc1;
24376           cc1 = tmp;
24377         }
24378
24379         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
24380             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24381           // FIXME: need symbolic constants for these magic numbers.
24382           // See X86ATTInstPrinter.cpp:printSSECC().
24383           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24384           if (Subtarget->hasAVX512()) {
24385             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24386                                          CMP01,
24387                                          DAG.getConstant(x86cc, DL, MVT::i8));
24388             if (N->getValueType(0) != MVT::i1)
24389               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24390                                  FSetCC);
24391             return FSetCC;
24392           }
24393           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24394                                               CMP00.getValueType(), CMP00, CMP01,
24395                                               DAG.getConstant(x86cc, DL,
24396                                                               MVT::i8));
24397
24398           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24399           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24400
24401           if (is64BitFP && !Subtarget->is64Bit()) {
24402             // On a 32-bit target, we cannot bitcast the 64-bit float to a
24403             // 64-bit integer, since that's not a legal type. Since
24404             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24405             // bits, but can do this little dance to extract the lowest 32 bits
24406             // and work with those going forward.
24407             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24408                                            OnesOrZeroesF);
24409             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
24410             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24411                                         Vector32, DAG.getIntPtrConstant(0, DL));
24412             IntVT = MVT::i32;
24413           }
24414
24415           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
24416           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24417                                       DAG.getConstant(1, DL, IntVT));
24418           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
24419                                               ANDed);
24420           return OneBitOfTruth;
24421         }
24422       }
24423     }
24424   }
24425   return SDValue();
24426 }
24427
24428 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24429 /// so it can be folded inside ANDNP.
24430 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24431   EVT VT = N->getValueType(0);
24432
24433   // Match direct AllOnes for 128 and 256-bit vectors
24434   if (ISD::isBuildVectorAllOnes(N))
24435     return true;
24436
24437   // Look through a bit convert.
24438   if (N->getOpcode() == ISD::BITCAST)
24439     N = N->getOperand(0).getNode();
24440
24441   // Sometimes the operand may come from a insert_subvector building a 256-bit
24442   // allones vector
24443   if (VT.is256BitVector() &&
24444       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24445     SDValue V1 = N->getOperand(0);
24446     SDValue V2 = N->getOperand(1);
24447
24448     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24449         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24450         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24451         ISD::isBuildVectorAllOnes(V2.getNode()))
24452       return true;
24453   }
24454
24455   return false;
24456 }
24457
24458 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24459 // register. In most cases we actually compare or select YMM-sized registers
24460 // and mixing the two types creates horrible code. This method optimizes
24461 // some of the transition sequences.
24462 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24463                                  TargetLowering::DAGCombinerInfo &DCI,
24464                                  const X86Subtarget *Subtarget) {
24465   EVT VT = N->getValueType(0);
24466   if (!VT.is256BitVector())
24467     return SDValue();
24468
24469   assert((N->getOpcode() == ISD::ANY_EXTEND ||
24470           N->getOpcode() == ISD::ZERO_EXTEND ||
24471           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24472
24473   SDValue Narrow = N->getOperand(0);
24474   EVT NarrowVT = Narrow->getValueType(0);
24475   if (!NarrowVT.is128BitVector())
24476     return SDValue();
24477
24478   if (Narrow->getOpcode() != ISD::XOR &&
24479       Narrow->getOpcode() != ISD::AND &&
24480       Narrow->getOpcode() != ISD::OR)
24481     return SDValue();
24482
24483   SDValue N0  = Narrow->getOperand(0);
24484   SDValue N1  = Narrow->getOperand(1);
24485   SDLoc DL(Narrow);
24486
24487   // The Left side has to be a trunc.
24488   if (N0.getOpcode() != ISD::TRUNCATE)
24489     return SDValue();
24490
24491   // The type of the truncated inputs.
24492   EVT WideVT = N0->getOperand(0)->getValueType(0);
24493   if (WideVT != VT)
24494     return SDValue();
24495
24496   // The right side has to be a 'trunc' or a constant vector.
24497   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24498   ConstantSDNode *RHSConstSplat = nullptr;
24499   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24500     RHSConstSplat = RHSBV->getConstantSplatNode();
24501   if (!RHSTrunc && !RHSConstSplat)
24502     return SDValue();
24503
24504   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24505
24506   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24507     return SDValue();
24508
24509   // Set N0 and N1 to hold the inputs to the new wide operation.
24510   N0 = N0->getOperand(0);
24511   if (RHSConstSplat) {
24512     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24513                      SDValue(RHSConstSplat, 0));
24514     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24515     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24516   } else if (RHSTrunc) {
24517     N1 = N1->getOperand(0);
24518   }
24519
24520   // Generate the wide operation.
24521   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24522   unsigned Opcode = N->getOpcode();
24523   switch (Opcode) {
24524   case ISD::ANY_EXTEND:
24525     return Op;
24526   case ISD::ZERO_EXTEND: {
24527     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24528     APInt Mask = APInt::getAllOnesValue(InBits);
24529     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24530     return DAG.getNode(ISD::AND, DL, VT,
24531                        Op, DAG.getConstant(Mask, DL, VT));
24532   }
24533   case ISD::SIGN_EXTEND:
24534     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24535                        Op, DAG.getValueType(NarrowVT));
24536   default:
24537     llvm_unreachable("Unexpected opcode");
24538   }
24539 }
24540
24541 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
24542                                  TargetLowering::DAGCombinerInfo &DCI,
24543                                  const X86Subtarget *Subtarget) {
24544   SDValue N0 = N->getOperand(0);
24545   SDValue N1 = N->getOperand(1);
24546   SDLoc DL(N);
24547
24548   // A vector zext_in_reg may be represented as a shuffle,
24549   // feeding into a bitcast (this represents anyext) feeding into
24550   // an and with a mask.
24551   // We'd like to try to combine that into a shuffle with zero
24552   // plus a bitcast, removing the and.
24553   if (N0.getOpcode() != ISD::BITCAST ||
24554       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
24555     return SDValue();
24556
24557   // The other side of the AND should be a splat of 2^C, where C
24558   // is the number of bits in the source type.
24559   if (N1.getOpcode() == ISD::BITCAST)
24560     N1 = N1.getOperand(0);
24561   if (N1.getOpcode() != ISD::BUILD_VECTOR)
24562     return SDValue();
24563   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
24564
24565   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
24566   EVT SrcType = Shuffle->getValueType(0);
24567
24568   // We expect a single-source shuffle
24569   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
24570     return SDValue();
24571
24572   unsigned SrcSize = SrcType.getScalarSizeInBits();
24573
24574   APInt SplatValue, SplatUndef;
24575   unsigned SplatBitSize;
24576   bool HasAnyUndefs;
24577   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
24578                                 SplatBitSize, HasAnyUndefs))
24579     return SDValue();
24580
24581   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
24582   // Make sure the splat matches the mask we expect
24583   if (SplatBitSize > ResSize ||
24584       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
24585     return SDValue();
24586
24587   // Make sure the input and output size make sense
24588   if (SrcSize >= ResSize || ResSize % SrcSize)
24589     return SDValue();
24590
24591   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
24592   // The number of u's between each two values depends on the ratio between
24593   // the source and dest type.
24594   unsigned ZextRatio = ResSize / SrcSize;
24595   bool IsZext = true;
24596   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
24597     if (i % ZextRatio) {
24598       if (Shuffle->getMaskElt(i) > 0) {
24599         // Expected undef
24600         IsZext = false;
24601         break;
24602       }
24603     } else {
24604       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
24605         // Expected element number
24606         IsZext = false;
24607         break;
24608       }
24609     }
24610   }
24611
24612   if (!IsZext)
24613     return SDValue();
24614
24615   // Ok, perform the transformation - replace the shuffle with
24616   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24617   // (instead of undef) where the k elements come from the zero vector.
24618   SmallVector<int, 8> Mask;
24619   unsigned NumElems = SrcType.getVectorNumElements();
24620   for (unsigned i = 0; i < NumElems; ++i)
24621     if (i % ZextRatio)
24622       Mask.push_back(NumElems);
24623     else
24624       Mask.push_back(i / ZextRatio);
24625
24626   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24627     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24628   return DAG.getBitcast(N0.getValueType(), NewShuffle);
24629 }
24630
24631 /// If both input operands of a logic op are being cast from floating point
24632 /// types, try to convert this into a floating point logic node to avoid
24633 /// unnecessary moves from SSE to integer registers.
24634 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
24635                                         const X86Subtarget *Subtarget) {
24636   unsigned FPOpcode = ISD::DELETED_NODE;
24637   if (N->getOpcode() == ISD::AND)
24638     FPOpcode = X86ISD::FAND;
24639   else if (N->getOpcode() == ISD::OR)
24640     FPOpcode = X86ISD::FOR;
24641   else if (N->getOpcode() == ISD::XOR)
24642     FPOpcode = X86ISD::FXOR;
24643
24644   assert(FPOpcode != ISD::DELETED_NODE &&
24645          "Unexpected input node for FP logic conversion");
24646
24647   EVT VT = N->getValueType(0);
24648   SDValue N0 = N->getOperand(0);
24649   SDValue N1 = N->getOperand(1);
24650   SDLoc DL(N);
24651   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
24652       ((Subtarget->hasSSE1() && VT == MVT::i32) ||
24653        (Subtarget->hasSSE2() && VT == MVT::i64))) {
24654     SDValue N00 = N0.getOperand(0);
24655     SDValue N10 = N1.getOperand(0);
24656     EVT N00Type = N00.getValueType();
24657     EVT N10Type = N10.getValueType();
24658     if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
24659       SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
24660       return DAG.getBitcast(VT, FPLogic);
24661     }
24662   }
24663   return SDValue();
24664 }
24665
24666 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24667                                  TargetLowering::DAGCombinerInfo &DCI,
24668                                  const X86Subtarget *Subtarget) {
24669   if (DCI.isBeforeLegalizeOps())
24670     return SDValue();
24671
24672   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24673     return Zext;
24674
24675   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24676     return R;
24677
24678   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
24679     return FPLogic;
24680
24681   EVT VT = N->getValueType(0);
24682   SDValue N0 = N->getOperand(0);
24683   SDValue N1 = N->getOperand(1);
24684   SDLoc DL(N);
24685
24686   // Create BEXTR instructions
24687   // BEXTR is ((X >> imm) & (2**size-1))
24688   if (VT == MVT::i32 || VT == MVT::i64) {
24689     // Check for BEXTR.
24690     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24691         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24692       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24693       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24694       if (MaskNode && ShiftNode) {
24695         uint64_t Mask = MaskNode->getZExtValue();
24696         uint64_t Shift = ShiftNode->getZExtValue();
24697         if (isMask_64(Mask)) {
24698           uint64_t MaskSize = countPopulation(Mask);
24699           if (Shift + MaskSize <= VT.getSizeInBits())
24700             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24701                                DAG.getConstant(Shift | (MaskSize << 8), DL,
24702                                                VT));
24703         }
24704       }
24705     } // BEXTR
24706
24707     return SDValue();
24708   }
24709
24710   // Want to form ANDNP nodes:
24711   // 1) In the hopes of then easily combining them with OR and AND nodes
24712   //    to form PBLEND/PSIGN.
24713   // 2) To match ANDN packed intrinsics
24714   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24715     return SDValue();
24716
24717   // Check LHS for vnot
24718   if (N0.getOpcode() == ISD::XOR &&
24719       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24720       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24721     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24722
24723   // Check RHS for vnot
24724   if (N1.getOpcode() == ISD::XOR &&
24725       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24726       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24727     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24728
24729   return SDValue();
24730 }
24731
24732 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24733                                 TargetLowering::DAGCombinerInfo &DCI,
24734                                 const X86Subtarget *Subtarget) {
24735   if (DCI.isBeforeLegalizeOps())
24736     return SDValue();
24737
24738   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24739     return R;
24740
24741   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
24742     return FPLogic;
24743
24744   SDValue N0 = N->getOperand(0);
24745   SDValue N1 = N->getOperand(1);
24746   EVT VT = N->getValueType(0);
24747
24748   // look for psign/blend
24749   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24750     if (!Subtarget->hasSSSE3() ||
24751         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24752       return SDValue();
24753
24754     // Canonicalize pandn to RHS
24755     if (N0.getOpcode() == X86ISD::ANDNP)
24756       std::swap(N0, N1);
24757     // or (and (m, y), (pandn m, x))
24758     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24759       SDValue Mask = N1.getOperand(0);
24760       SDValue X    = N1.getOperand(1);
24761       SDValue Y;
24762       if (N0.getOperand(0) == Mask)
24763         Y = N0.getOperand(1);
24764       if (N0.getOperand(1) == Mask)
24765         Y = N0.getOperand(0);
24766
24767       // Check to see if the mask appeared in both the AND and ANDNP and
24768       if (!Y.getNode())
24769         return SDValue();
24770
24771       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24772       // Look through mask bitcast.
24773       if (Mask.getOpcode() == ISD::BITCAST)
24774         Mask = Mask.getOperand(0);
24775       if (X.getOpcode() == ISD::BITCAST)
24776         X = X.getOperand(0);
24777       if (Y.getOpcode() == ISD::BITCAST)
24778         Y = Y.getOperand(0);
24779
24780       EVT MaskVT = Mask.getValueType();
24781
24782       // Validate that the Mask operand is a vector sra node.
24783       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24784       // there is no psrai.b
24785       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24786       unsigned SraAmt = ~0;
24787       if (Mask.getOpcode() == ISD::SRA) {
24788         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24789           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24790             SraAmt = AmtConst->getZExtValue();
24791       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24792         SDValue SraC = Mask.getOperand(1);
24793         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24794       }
24795       if ((SraAmt + 1) != EltBits)
24796         return SDValue();
24797
24798       SDLoc DL(N);
24799
24800       // Now we know we at least have a plendvb with the mask val.  See if
24801       // we can form a psignb/w/d.
24802       // psign = x.type == y.type == mask.type && y = sub(0, x);
24803       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24804           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24805           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24806         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24807                "Unsupported VT for PSIGN");
24808         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24809         return DAG.getBitcast(VT, Mask);
24810       }
24811       // PBLENDVB only available on SSE 4.1
24812       if (!Subtarget->hasSSE41())
24813         return SDValue();
24814
24815       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24816
24817       X = DAG.getBitcast(BlendVT, X);
24818       Y = DAG.getBitcast(BlendVT, Y);
24819       Mask = DAG.getBitcast(BlendVT, Mask);
24820       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24821       return DAG.getBitcast(VT, Mask);
24822     }
24823   }
24824
24825   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24826     return SDValue();
24827
24828   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24829   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24830
24831   // SHLD/SHRD instructions have lower register pressure, but on some
24832   // platforms they have higher latency than the equivalent
24833   // series of shifts/or that would otherwise be generated.
24834   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24835   // have higher latencies and we are not optimizing for size.
24836   if (!OptForSize && Subtarget->isSHLDSlow())
24837     return SDValue();
24838
24839   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24840     std::swap(N0, N1);
24841   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24842     return SDValue();
24843   if (!N0.hasOneUse() || !N1.hasOneUse())
24844     return SDValue();
24845
24846   SDValue ShAmt0 = N0.getOperand(1);
24847   if (ShAmt0.getValueType() != MVT::i8)
24848     return SDValue();
24849   SDValue ShAmt1 = N1.getOperand(1);
24850   if (ShAmt1.getValueType() != MVT::i8)
24851     return SDValue();
24852   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24853     ShAmt0 = ShAmt0.getOperand(0);
24854   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24855     ShAmt1 = ShAmt1.getOperand(0);
24856
24857   SDLoc DL(N);
24858   unsigned Opc = X86ISD::SHLD;
24859   SDValue Op0 = N0.getOperand(0);
24860   SDValue Op1 = N1.getOperand(0);
24861   if (ShAmt0.getOpcode() == ISD::SUB) {
24862     Opc = X86ISD::SHRD;
24863     std::swap(Op0, Op1);
24864     std::swap(ShAmt0, ShAmt1);
24865   }
24866
24867   unsigned Bits = VT.getSizeInBits();
24868   if (ShAmt1.getOpcode() == ISD::SUB) {
24869     SDValue Sum = ShAmt1.getOperand(0);
24870     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24871       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24872       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24873         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24874       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24875         return DAG.getNode(Opc, DL, VT,
24876                            Op0, Op1,
24877                            DAG.getNode(ISD::TRUNCATE, DL,
24878                                        MVT::i8, ShAmt0));
24879     }
24880   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24881     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24882     if (ShAmt0C &&
24883         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24884       return DAG.getNode(Opc, DL, VT,
24885                          N0.getOperand(0), N1.getOperand(0),
24886                          DAG.getNode(ISD::TRUNCATE, DL,
24887                                        MVT::i8, ShAmt0));
24888   }
24889
24890   return SDValue();
24891 }
24892
24893 // Generate NEG and CMOV for integer abs.
24894 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24895   EVT VT = N->getValueType(0);
24896
24897   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24898   // 8-bit integer abs to NEG and CMOV.
24899   if (VT.isInteger() && VT.getSizeInBits() == 8)
24900     return SDValue();
24901
24902   SDValue N0 = N->getOperand(0);
24903   SDValue N1 = N->getOperand(1);
24904   SDLoc DL(N);
24905
24906   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24907   // and change it to SUB and CMOV.
24908   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24909       N0.getOpcode() == ISD::ADD &&
24910       N0.getOperand(1) == N1 &&
24911       N1.getOpcode() == ISD::SRA &&
24912       N1.getOperand(0) == N0.getOperand(0))
24913     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24914       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24915         // Generate SUB & CMOV.
24916         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24917                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24918
24919         SDValue Ops[] = { N0.getOperand(0), Neg,
24920                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24921                           SDValue(Neg.getNode(), 1) };
24922         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24923       }
24924   return SDValue();
24925 }
24926
24927 // Try to turn tests against the signbit in the form of:
24928 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24929 // into:
24930 //   SETGT(X, -1)
24931 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24932   // This is only worth doing if the output type is i8.
24933   if (N->getValueType(0) != MVT::i8)
24934     return SDValue();
24935
24936   SDValue N0 = N->getOperand(0);
24937   SDValue N1 = N->getOperand(1);
24938
24939   // We should be performing an xor against a truncated shift.
24940   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24941     return SDValue();
24942
24943   // Make sure we are performing an xor against one.
24944   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24945     return SDValue();
24946
24947   // SetCC on x86 zero extends so only act on this if it's a logical shift.
24948   SDValue Shift = N0.getOperand(0);
24949   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24950     return SDValue();
24951
24952   // Make sure we are truncating from one of i16, i32 or i64.
24953   EVT ShiftTy = Shift.getValueType();
24954   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24955     return SDValue();
24956
24957   // Make sure the shift amount extracts the sign bit.
24958   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24959       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24960     return SDValue();
24961
24962   // Create a greater-than comparison against -1.
24963   // N.B. Using SETGE against 0 works but we want a canonical looking
24964   // comparison, using SETGT matches up with what TranslateX86CC.
24965   SDLoc DL(N);
24966   SDValue ShiftOp = Shift.getOperand(0);
24967   EVT ShiftOpTy = ShiftOp.getValueType();
24968   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24969                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24970   return Cond;
24971 }
24972
24973 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24974                                  TargetLowering::DAGCombinerInfo &DCI,
24975                                  const X86Subtarget *Subtarget) {
24976   if (DCI.isBeforeLegalizeOps())
24977     return SDValue();
24978
24979   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24980     return RV;
24981
24982   if (Subtarget->hasCMov())
24983     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24984       return RV;
24985
24986   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
24987     return FPLogic;
24988
24989   return SDValue();
24990 }
24991
24992 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24993 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24994                                   TargetLowering::DAGCombinerInfo &DCI,
24995                                   const X86Subtarget *Subtarget) {
24996   LoadSDNode *Ld = cast<LoadSDNode>(N);
24997   EVT RegVT = Ld->getValueType(0);
24998   EVT MemVT = Ld->getMemoryVT();
24999   SDLoc dl(Ld);
25000   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25001
25002   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
25003   // into two 16-byte operations.
25004   ISD::LoadExtType Ext = Ld->getExtensionType();
25005   bool Fast;
25006   unsigned AddressSpace = Ld->getAddressSpace();
25007   unsigned Alignment = Ld->getAlignment();
25008   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
25009       Ext == ISD::NON_EXTLOAD &&
25010       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
25011                              AddressSpace, Alignment, &Fast) && !Fast) {
25012     unsigned NumElems = RegVT.getVectorNumElements();
25013     if (NumElems < 2)
25014       return SDValue();
25015
25016     SDValue Ptr = Ld->getBasePtr();
25017     SDValue Increment =
25018         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25019
25020     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
25021                                   NumElems/2);
25022     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25023                                 Ld->getPointerInfo(), Ld->isVolatile(),
25024                                 Ld->isNonTemporal(), Ld->isInvariant(),
25025                                 Alignment);
25026     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25027     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25028                                 Ld->getPointerInfo(), Ld->isVolatile(),
25029                                 Ld->isNonTemporal(), Ld->isInvariant(),
25030                                 std::min(16U, Alignment));
25031     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
25032                              Load1.getValue(1),
25033                              Load2.getValue(1));
25034
25035     SDValue NewVec = DAG.getUNDEF(RegVT);
25036     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
25037     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
25038     return DCI.CombineTo(N, NewVec, TF, true);
25039   }
25040
25041   return SDValue();
25042 }
25043
25044 /// PerformMLOADCombine - Resolve extending loads
25045 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
25046                                    TargetLowering::DAGCombinerInfo &DCI,
25047                                    const X86Subtarget *Subtarget) {
25048   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
25049   if (Mld->getExtensionType() != ISD::SEXTLOAD)
25050     return SDValue();
25051
25052   EVT VT = Mld->getValueType(0);
25053   unsigned NumElems = VT.getVectorNumElements();
25054   EVT LdVT = Mld->getMemoryVT();
25055   SDLoc dl(Mld);
25056
25057   assert(LdVT != VT && "Cannot extend to the same type");
25058   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
25059   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
25060   // From, To sizes and ElemCount must be pow of two
25061   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25062     "Unexpected size for extending masked load");
25063
25064   unsigned SizeRatio  = ToSz / FromSz;
25065   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
25066
25067   // Create a type on which we perform the shuffle
25068   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25069           LdVT.getScalarType(), NumElems*SizeRatio);
25070   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25071
25072   // Convert Src0 value
25073   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
25074   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
25075     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25076     for (unsigned i = 0; i != NumElems; ++i)
25077       ShuffleVec[i] = i * SizeRatio;
25078
25079     // Can't shuffle using an illegal type.
25080     assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25081            "WideVecVT should be legal");
25082     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
25083                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
25084   }
25085   // Prepare the new mask
25086   SDValue NewMask;
25087   SDValue Mask = Mld->getMask();
25088   if (Mask.getValueType() == VT) {
25089     // Mask and original value have the same type
25090     NewMask = DAG.getBitcast(WideVecVT, Mask);
25091     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25092     for (unsigned i = 0; i != NumElems; ++i)
25093       ShuffleVec[i] = i * SizeRatio;
25094     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25095       ShuffleVec[i] = NumElems*SizeRatio;
25096     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25097                                    DAG.getConstant(0, dl, WideVecVT),
25098                                    &ShuffleVec[0]);
25099   }
25100   else {
25101     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25102     unsigned WidenNumElts = NumElems*SizeRatio;
25103     unsigned MaskNumElts = VT.getVectorNumElements();
25104     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
25105                                      WidenNumElts);
25106
25107     unsigned NumConcat = WidenNumElts / MaskNumElts;
25108     SmallVector<SDValue, 16> Ops(NumConcat);
25109     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25110     Ops[0] = Mask;
25111     for (unsigned i = 1; i != NumConcat; ++i)
25112       Ops[i] = ZeroVal;
25113
25114     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25115   }
25116
25117   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
25118                                      Mld->getBasePtr(), NewMask, WideSrc0,
25119                                      Mld->getMemoryVT(), Mld->getMemOperand(),
25120                                      ISD::NON_EXTLOAD);
25121   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
25122   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
25123 }
25124 /// PerformMSTORECombine - Resolve truncating stores
25125 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
25126                                     const X86Subtarget *Subtarget) {
25127   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
25128   if (!Mst->isTruncatingStore())
25129     return SDValue();
25130
25131   EVT VT = Mst->getValue().getValueType();
25132   unsigned NumElems = VT.getVectorNumElements();
25133   EVT StVT = Mst->getMemoryVT();
25134   SDLoc dl(Mst);
25135
25136   assert(StVT != VT && "Cannot truncate to the same type");
25137   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25138   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25139
25140   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25141
25142   // The truncating store is legal in some cases. For example
25143   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25144   // are designated for truncate store.
25145   // In this case we don't need any further transformations.
25146   if (TLI.isTruncStoreLegal(VT, StVT))
25147     return SDValue();
25148
25149   // From, To sizes and ElemCount must be pow of two
25150   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25151     "Unexpected size for truncating masked store");
25152   // We are going to use the original vector elt for storing.
25153   // Accumulated smaller vector elements must be a multiple of the store size.
25154   assert (((NumElems * FromSz) % ToSz) == 0 &&
25155           "Unexpected ratio for truncating masked store");
25156
25157   unsigned SizeRatio  = FromSz / ToSz;
25158   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25159
25160   // Create a type on which we perform the shuffle
25161   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25162           StVT.getScalarType(), NumElems*SizeRatio);
25163
25164   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25165
25166   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
25167   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25168   for (unsigned i = 0; i != NumElems; ++i)
25169     ShuffleVec[i] = i * SizeRatio;
25170
25171   // Can't shuffle using an illegal type.
25172   assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25173          "WideVecVT should be legal");
25174
25175   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25176                                         DAG.getUNDEF(WideVecVT),
25177                                         &ShuffleVec[0]);
25178
25179   SDValue NewMask;
25180   SDValue Mask = Mst->getMask();
25181   if (Mask.getValueType() == VT) {
25182     // Mask and original value have the same type
25183     NewMask = DAG.getBitcast(WideVecVT, Mask);
25184     for (unsigned i = 0; i != NumElems; ++i)
25185       ShuffleVec[i] = i * SizeRatio;
25186     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25187       ShuffleVec[i] = NumElems*SizeRatio;
25188     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25189                                    DAG.getConstant(0, dl, WideVecVT),
25190                                    &ShuffleVec[0]);
25191   }
25192   else {
25193     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25194     unsigned WidenNumElts = NumElems*SizeRatio;
25195     unsigned MaskNumElts = VT.getVectorNumElements();
25196     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
25197                                      WidenNumElts);
25198
25199     unsigned NumConcat = WidenNumElts / MaskNumElts;
25200     SmallVector<SDValue, 16> Ops(NumConcat);
25201     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25202     Ops[0] = Mask;
25203     for (unsigned i = 1; i != NumConcat; ++i)
25204       Ops[i] = ZeroVal;
25205
25206     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25207   }
25208
25209   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
25210                             NewMask, StVT, Mst->getMemOperand(), false);
25211 }
25212 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
25213 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
25214                                    const X86Subtarget *Subtarget) {
25215   StoreSDNode *St = cast<StoreSDNode>(N);
25216   EVT VT = St->getValue().getValueType();
25217   EVT StVT = St->getMemoryVT();
25218   SDLoc dl(St);
25219   SDValue StoredVal = St->getOperand(1);
25220   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25221
25222   // If we are saving a concatenation of two XMM registers and 32-byte stores
25223   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
25224   bool Fast;
25225   unsigned AddressSpace = St->getAddressSpace();
25226   unsigned Alignment = St->getAlignment();
25227   if (VT.is256BitVector() && StVT == VT &&
25228       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
25229                              AddressSpace, Alignment, &Fast) && !Fast) {
25230     unsigned NumElems = VT.getVectorNumElements();
25231     if (NumElems < 2)
25232       return SDValue();
25233
25234     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
25235     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
25236
25237     SDValue Stride =
25238         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25239     SDValue Ptr0 = St->getBasePtr();
25240     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
25241
25242     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
25243                                 St->getPointerInfo(), St->isVolatile(),
25244                                 St->isNonTemporal(), Alignment);
25245     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
25246                                 St->getPointerInfo(), St->isVolatile(),
25247                                 St->isNonTemporal(),
25248                                 std::min(16U, Alignment));
25249     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
25250   }
25251
25252   // Optimize trunc store (of multiple scalars) to shuffle and store.
25253   // First, pack all of the elements in one place. Next, store to memory
25254   // in fewer chunks.
25255   if (St->isTruncatingStore() && VT.isVector()) {
25256     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25257     unsigned NumElems = VT.getVectorNumElements();
25258     assert(StVT != VT && "Cannot truncate to the same type");
25259     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25260     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25261
25262     // The truncating store is legal in some cases. For example
25263     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25264     // are designated for truncate store.
25265     // In this case we don't need any further transformations.
25266     if (TLI.isTruncStoreLegal(VT, StVT))
25267       return SDValue();
25268
25269     // From, To sizes and ElemCount must be pow of two
25270     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
25271     // We are going to use the original vector elt for storing.
25272     // Accumulated smaller vector elements must be a multiple of the store size.
25273     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
25274
25275     unsigned SizeRatio  = FromSz / ToSz;
25276
25277     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25278
25279     // Create a type on which we perform the shuffle
25280     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25281             StVT.getScalarType(), NumElems*SizeRatio);
25282
25283     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25284
25285     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
25286     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
25287     for (unsigned i = 0; i != NumElems; ++i)
25288       ShuffleVec[i] = i * SizeRatio;
25289
25290     // Can't shuffle using an illegal type.
25291     if (!TLI.isTypeLegal(WideVecVT))
25292       return SDValue();
25293
25294     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25295                                          DAG.getUNDEF(WideVecVT),
25296                                          &ShuffleVec[0]);
25297     // At this point all of the data is stored at the bottom of the
25298     // register. We now need to save it to mem.
25299
25300     // Find the largest store unit
25301     MVT StoreType = MVT::i8;
25302     for (MVT Tp : MVT::integer_valuetypes()) {
25303       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
25304         StoreType = Tp;
25305     }
25306
25307     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
25308     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
25309         (64 <= NumElems * ToSz))
25310       StoreType = MVT::f64;
25311
25312     // Bitcast the original vector into a vector of store-size units
25313     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
25314             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
25315     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
25316     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
25317     SmallVector<SDValue, 8> Chains;
25318     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
25319                                         TLI.getPointerTy(DAG.getDataLayout()));
25320     SDValue Ptr = St->getBasePtr();
25321
25322     // Perform one or more big stores into memory.
25323     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
25324       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
25325                                    StoreType, ShuffWide,
25326                                    DAG.getIntPtrConstant(i, dl));
25327       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
25328                                 St->getPointerInfo(), St->isVolatile(),
25329                                 St->isNonTemporal(), St->getAlignment());
25330       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25331       Chains.push_back(Ch);
25332     }
25333
25334     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
25335   }
25336
25337   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
25338   // the FP state in cases where an emms may be missing.
25339   // A preferable solution to the general problem is to figure out the right
25340   // places to insert EMMS.  This qualifies as a quick hack.
25341
25342   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
25343   if (VT.getSizeInBits() != 64)
25344     return SDValue();
25345
25346   const Function *F = DAG.getMachineFunction().getFunction();
25347   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
25348   bool F64IsLegal =
25349       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
25350   if ((VT.isVector() ||
25351        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
25352       isa<LoadSDNode>(St->getValue()) &&
25353       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
25354       St->getChain().hasOneUse() && !St->isVolatile()) {
25355     SDNode* LdVal = St->getValue().getNode();
25356     LoadSDNode *Ld = nullptr;
25357     int TokenFactorIndex = -1;
25358     SmallVector<SDValue, 8> Ops;
25359     SDNode* ChainVal = St->getChain().getNode();
25360     // Must be a store of a load.  We currently handle two cases:  the load
25361     // is a direct child, and it's under an intervening TokenFactor.  It is
25362     // possible to dig deeper under nested TokenFactors.
25363     if (ChainVal == LdVal)
25364       Ld = cast<LoadSDNode>(St->getChain());
25365     else if (St->getValue().hasOneUse() &&
25366              ChainVal->getOpcode() == ISD::TokenFactor) {
25367       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
25368         if (ChainVal->getOperand(i).getNode() == LdVal) {
25369           TokenFactorIndex = i;
25370           Ld = cast<LoadSDNode>(St->getValue());
25371         } else
25372           Ops.push_back(ChainVal->getOperand(i));
25373       }
25374     }
25375
25376     if (!Ld || !ISD::isNormalLoad(Ld))
25377       return SDValue();
25378
25379     // If this is not the MMX case, i.e. we are just turning i64 load/store
25380     // into f64 load/store, avoid the transformation if there are multiple
25381     // uses of the loaded value.
25382     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
25383       return SDValue();
25384
25385     SDLoc LdDL(Ld);
25386     SDLoc StDL(N);
25387     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
25388     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
25389     // pair instead.
25390     if (Subtarget->is64Bit() || F64IsLegal) {
25391       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
25392       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
25393                                   Ld->getPointerInfo(), Ld->isVolatile(),
25394                                   Ld->isNonTemporal(), Ld->isInvariant(),
25395                                   Ld->getAlignment());
25396       SDValue NewChain = NewLd.getValue(1);
25397       if (TokenFactorIndex != -1) {
25398         Ops.push_back(NewChain);
25399         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25400       }
25401       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
25402                           St->getPointerInfo(),
25403                           St->isVolatile(), St->isNonTemporal(),
25404                           St->getAlignment());
25405     }
25406
25407     // Otherwise, lower to two pairs of 32-bit loads / stores.
25408     SDValue LoAddr = Ld->getBasePtr();
25409     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
25410                                  DAG.getConstant(4, LdDL, MVT::i32));
25411
25412     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
25413                                Ld->getPointerInfo(),
25414                                Ld->isVolatile(), Ld->isNonTemporal(),
25415                                Ld->isInvariant(), Ld->getAlignment());
25416     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
25417                                Ld->getPointerInfo().getWithOffset(4),
25418                                Ld->isVolatile(), Ld->isNonTemporal(),
25419                                Ld->isInvariant(),
25420                                MinAlign(Ld->getAlignment(), 4));
25421
25422     SDValue NewChain = LoLd.getValue(1);
25423     if (TokenFactorIndex != -1) {
25424       Ops.push_back(LoLd);
25425       Ops.push_back(HiLd);
25426       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25427     }
25428
25429     LoAddr = St->getBasePtr();
25430     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
25431                          DAG.getConstant(4, StDL, MVT::i32));
25432
25433     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
25434                                 St->getPointerInfo(),
25435                                 St->isVolatile(), St->isNonTemporal(),
25436                                 St->getAlignment());
25437     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
25438                                 St->getPointerInfo().getWithOffset(4),
25439                                 St->isVolatile(),
25440                                 St->isNonTemporal(),
25441                                 MinAlign(St->getAlignment(), 4));
25442     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
25443   }
25444
25445   // This is similar to the above case, but here we handle a scalar 64-bit
25446   // integer store that is extracted from a vector on a 32-bit target.
25447   // If we have SSE2, then we can treat it like a floating-point double
25448   // to get past legalization. The execution dependencies fixup pass will
25449   // choose the optimal machine instruction for the store if this really is
25450   // an integer or v2f32 rather than an f64.
25451   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
25452       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
25453     SDValue OldExtract = St->getOperand(1);
25454     SDValue ExtOp0 = OldExtract.getOperand(0);
25455     unsigned VecSize = ExtOp0.getValueSizeInBits();
25456     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
25457     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
25458     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
25459                                      BitCast, OldExtract.getOperand(1));
25460     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
25461                         St->getPointerInfo(), St->isVolatile(),
25462                         St->isNonTemporal(), St->getAlignment());
25463   }
25464
25465   return SDValue();
25466 }
25467
25468 /// Return 'true' if this vector operation is "horizontal"
25469 /// and return the operands for the horizontal operation in LHS and RHS.  A
25470 /// horizontal operation performs the binary operation on successive elements
25471 /// of its first operand, then on successive elements of its second operand,
25472 /// returning the resulting values in a vector.  For example, if
25473 ///   A = < float a0, float a1, float a2, float a3 >
25474 /// and
25475 ///   B = < float b0, float b1, float b2, float b3 >
25476 /// then the result of doing a horizontal operation on A and B is
25477 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
25478 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
25479 /// A horizontal-op B, for some already available A and B, and if so then LHS is
25480 /// set to A, RHS to B, and the routine returns 'true'.
25481 /// Note that the binary operation should have the property that if one of the
25482 /// operands is UNDEF then the result is UNDEF.
25483 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
25484   // Look for the following pattern: if
25485   //   A = < float a0, float a1, float a2, float a3 >
25486   //   B = < float b0, float b1, float b2, float b3 >
25487   // and
25488   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
25489   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
25490   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
25491   // which is A horizontal-op B.
25492
25493   // At least one of the operands should be a vector shuffle.
25494   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
25495       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
25496     return false;
25497
25498   MVT VT = LHS.getSimpleValueType();
25499
25500   assert((VT.is128BitVector() || VT.is256BitVector()) &&
25501          "Unsupported vector type for horizontal add/sub");
25502
25503   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
25504   // operate independently on 128-bit lanes.
25505   unsigned NumElts = VT.getVectorNumElements();
25506   unsigned NumLanes = VT.getSizeInBits()/128;
25507   unsigned NumLaneElts = NumElts / NumLanes;
25508   assert((NumLaneElts % 2 == 0) &&
25509          "Vector type should have an even number of elements in each lane");
25510   unsigned HalfLaneElts = NumLaneElts/2;
25511
25512   // View LHS in the form
25513   //   LHS = VECTOR_SHUFFLE A, B, LMask
25514   // If LHS is not a shuffle then pretend it is the shuffle
25515   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
25516   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
25517   // type VT.
25518   SDValue A, B;
25519   SmallVector<int, 16> LMask(NumElts);
25520   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25521     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
25522       A = LHS.getOperand(0);
25523     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
25524       B = LHS.getOperand(1);
25525     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
25526     std::copy(Mask.begin(), Mask.end(), LMask.begin());
25527   } else {
25528     if (LHS.getOpcode() != ISD::UNDEF)
25529       A = LHS;
25530     for (unsigned i = 0; i != NumElts; ++i)
25531       LMask[i] = i;
25532   }
25533
25534   // Likewise, view RHS in the form
25535   //   RHS = VECTOR_SHUFFLE C, D, RMask
25536   SDValue C, D;
25537   SmallVector<int, 16> RMask(NumElts);
25538   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25539     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
25540       C = RHS.getOperand(0);
25541     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
25542       D = RHS.getOperand(1);
25543     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
25544     std::copy(Mask.begin(), Mask.end(), RMask.begin());
25545   } else {
25546     if (RHS.getOpcode() != ISD::UNDEF)
25547       C = RHS;
25548     for (unsigned i = 0; i != NumElts; ++i)
25549       RMask[i] = i;
25550   }
25551
25552   // Check that the shuffles are both shuffling the same vectors.
25553   if (!(A == C && B == D) && !(A == D && B == C))
25554     return false;
25555
25556   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
25557   if (!A.getNode() && !B.getNode())
25558     return false;
25559
25560   // If A and B occur in reverse order in RHS, then "swap" them (which means
25561   // rewriting the mask).
25562   if (A != C)
25563     ShuffleVectorSDNode::commuteMask(RMask);
25564
25565   // At this point LHS and RHS are equivalent to
25566   //   LHS = VECTOR_SHUFFLE A, B, LMask
25567   //   RHS = VECTOR_SHUFFLE A, B, RMask
25568   // Check that the masks correspond to performing a horizontal operation.
25569   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
25570     for (unsigned i = 0; i != NumLaneElts; ++i) {
25571       int LIdx = LMask[i+l], RIdx = RMask[i+l];
25572
25573       // Ignore any UNDEF components.
25574       if (LIdx < 0 || RIdx < 0 ||
25575           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
25576           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
25577         continue;
25578
25579       // Check that successive elements are being operated on.  If not, this is
25580       // not a horizontal operation.
25581       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
25582       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
25583       if (!(LIdx == Index && RIdx == Index + 1) &&
25584           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
25585         return false;
25586     }
25587   }
25588
25589   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
25590   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
25591   return true;
25592 }
25593
25594 /// Do target-specific dag combines on floating point adds.
25595 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
25596                                   const X86Subtarget *Subtarget) {
25597   EVT VT = N->getValueType(0);
25598   SDValue LHS = N->getOperand(0);
25599   SDValue RHS = N->getOperand(1);
25600
25601   // Try to synthesize horizontal adds from adds of shuffles.
25602   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25603        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25604       isHorizontalBinOp(LHS, RHS, true))
25605     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
25606   return SDValue();
25607 }
25608
25609 /// Do target-specific dag combines on floating point subs.
25610 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
25611                                   const X86Subtarget *Subtarget) {
25612   EVT VT = N->getValueType(0);
25613   SDValue LHS = N->getOperand(0);
25614   SDValue RHS = N->getOperand(1);
25615
25616   // Try to synthesize horizontal subs from subs of shuffles.
25617   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25618        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25619       isHorizontalBinOp(LHS, RHS, false))
25620     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
25621   return SDValue();
25622 }
25623
25624 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
25625 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
25626                                  const X86Subtarget *Subtarget) {
25627   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
25628
25629   // F[X]OR(0.0, x) -> x
25630   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25631     if (C->getValueAPF().isPosZero())
25632       return N->getOperand(1);
25633
25634   // F[X]OR(x, 0.0) -> x
25635   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25636     if (C->getValueAPF().isPosZero())
25637       return N->getOperand(0);
25638
25639   EVT VT = N->getValueType(0);
25640   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
25641     SDLoc dl(N);
25642     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
25643     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
25644
25645     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
25646     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
25647     unsigned IntOpcode = (N->getOpcode() == X86ISD::FOR) ? ISD::OR : ISD::XOR;
25648     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
25649     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
25650   }
25651   return SDValue();
25652 }
25653
25654 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
25655 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
25656   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
25657
25658   // Only perform optimizations if UnsafeMath is used.
25659   if (!DAG.getTarget().Options.UnsafeFPMath)
25660     return SDValue();
25661
25662   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25663   // into FMINC and FMAXC, which are Commutative operations.
25664   unsigned NewOp = 0;
25665   switch (N->getOpcode()) {
25666     default: llvm_unreachable("unknown opcode");
25667     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
25668     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
25669   }
25670
25671   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25672                      N->getOperand(0), N->getOperand(1));
25673 }
25674
25675 /// Do target-specific dag combines on X86ISD::FAND nodes.
25676 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25677   // FAND(0.0, x) -> 0.0
25678   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25679     if (C->getValueAPF().isPosZero())
25680       return N->getOperand(0);
25681
25682   // FAND(x, 0.0) -> 0.0
25683   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25684     if (C->getValueAPF().isPosZero())
25685       return N->getOperand(1);
25686
25687   return SDValue();
25688 }
25689
25690 /// Do target-specific dag combines on X86ISD::FANDN nodes
25691 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25692   // FANDN(0.0, x) -> x
25693   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25694     if (C->getValueAPF().isPosZero())
25695       return N->getOperand(1);
25696
25697   // FANDN(x, 0.0) -> 0.0
25698   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25699     if (C->getValueAPF().isPosZero())
25700       return N->getOperand(1);
25701
25702   return SDValue();
25703 }
25704
25705 static SDValue PerformBTCombine(SDNode *N,
25706                                 SelectionDAG &DAG,
25707                                 TargetLowering::DAGCombinerInfo &DCI) {
25708   // BT ignores high bits in the bit index operand.
25709   SDValue Op1 = N->getOperand(1);
25710   if (Op1.hasOneUse()) {
25711     unsigned BitWidth = Op1.getValueSizeInBits();
25712     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25713     APInt KnownZero, KnownOne;
25714     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25715                                           !DCI.isBeforeLegalizeOps());
25716     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25717     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25718         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25719       DCI.CommitTargetLoweringOpt(TLO);
25720   }
25721   return SDValue();
25722 }
25723
25724 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25725   SDValue Op = N->getOperand(0);
25726   if (Op.getOpcode() == ISD::BITCAST)
25727     Op = Op.getOperand(0);
25728   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25729   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25730       VT.getVectorElementType().getSizeInBits() ==
25731       OpVT.getVectorElementType().getSizeInBits()) {
25732     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25733   }
25734   return SDValue();
25735 }
25736
25737 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25738                                                const X86Subtarget *Subtarget) {
25739   EVT VT = N->getValueType(0);
25740   if (!VT.isVector())
25741     return SDValue();
25742
25743   SDValue N0 = N->getOperand(0);
25744   SDValue N1 = N->getOperand(1);
25745   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25746   SDLoc dl(N);
25747
25748   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25749   // both SSE and AVX2 since there is no sign-extended shift right
25750   // operation on a vector with 64-bit elements.
25751   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25752   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25753   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25754       N0.getOpcode() == ISD::SIGN_EXTEND)) {
25755     SDValue N00 = N0.getOperand(0);
25756
25757     // EXTLOAD has a better solution on AVX2,
25758     // it may be replaced with X86ISD::VSEXT node.
25759     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25760       if (!ISD::isNormalLoad(N00.getNode()))
25761         return SDValue();
25762
25763     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25764         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25765                                   N00, N1);
25766       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25767     }
25768   }
25769   return SDValue();
25770 }
25771
25772 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
25773 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
25774 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
25775 /// eliminate extend, add, and shift instructions.
25776 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
25777                                        const X86Subtarget *Subtarget) {
25778   // TODO: This should be valid for other integer types.
25779   EVT VT = Sext->getValueType(0);
25780   if (VT != MVT::i64)
25781     return SDValue();
25782
25783   // We need an 'add nsw' feeding into the 'sext'.
25784   SDValue Add = Sext->getOperand(0);
25785   if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
25786     return SDValue();
25787
25788   // Having a constant operand to the 'add' ensures that we are not increasing
25789   // the instruction count because the constant is extended for free below.
25790   // A constant operand can also become the displacement field of an LEA.
25791   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
25792   if (!AddOp1)
25793     return SDValue();
25794
25795   // Don't make the 'add' bigger if there's no hope of combining it with some
25796   // other 'add' or 'shl' instruction.
25797   // TODO: It may be profitable to generate simpler LEA instructions in place
25798   // of single 'add' instructions, but the cost model for selecting an LEA
25799   // currently has a high threshold.
25800   bool HasLEAPotential = false;
25801   for (auto *User : Sext->uses()) {
25802     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
25803       HasLEAPotential = true;
25804       break;
25805     }
25806   }
25807   if (!HasLEAPotential)
25808     return SDValue();
25809
25810   // Everything looks good, so pull the 'sext' ahead of the 'add'.
25811   int64_t AddConstant = AddOp1->getSExtValue();
25812   SDValue AddOp0 = Add.getOperand(0);
25813   SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
25814   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
25815
25816   // The wider add is guaranteed to not wrap because both operands are
25817   // sign-extended.
25818   SDNodeFlags Flags;
25819   Flags.setNoSignedWrap(true);
25820   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
25821 }
25822
25823 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25824                                   TargetLowering::DAGCombinerInfo &DCI,
25825                                   const X86Subtarget *Subtarget) {
25826   SDValue N0 = N->getOperand(0);
25827   EVT VT = N->getValueType(0);
25828   EVT SVT = VT.getScalarType();
25829   EVT InVT = N0.getValueType();
25830   EVT InSVT = InVT.getScalarType();
25831   SDLoc DL(N);
25832
25833   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25834   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25835   // This exposes the sext to the sdivrem lowering, so that it directly extends
25836   // from AH (which we otherwise need to do contortions to access).
25837   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25838       InVT == MVT::i8 && VT == MVT::i32) {
25839     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25840     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25841                             N0.getOperand(0), N0.getOperand(1));
25842     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25843     return R.getValue(1);
25844   }
25845
25846   if (!DCI.isBeforeLegalizeOps()) {
25847     if (InVT == MVT::i1) {
25848       SDValue Zero = DAG.getConstant(0, DL, VT);
25849       SDValue AllOnes =
25850         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25851       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25852     }
25853     return SDValue();
25854   }
25855
25856   if (VT.isVector() && Subtarget->hasSSE2()) {
25857     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25858       EVT InVT = N.getValueType();
25859       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25860                                    Size / InVT.getScalarSizeInBits());
25861       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25862                                     DAG.getUNDEF(InVT));
25863       Opnds[0] = N;
25864       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25865     };
25866
25867     // If target-size is less than 128-bits, extend to a type that would extend
25868     // to 128 bits, extend that and extract the original target vector.
25869     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25870         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25871         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25872       unsigned Scale = 128 / VT.getSizeInBits();
25873       EVT ExVT =
25874           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25875       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25876       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25877       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25878                          DAG.getIntPtrConstant(0, DL));
25879     }
25880
25881     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25882     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25883     if (VT.getSizeInBits() == 128 &&
25884         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25885         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25886       SDValue ExOp = ExtendVecSize(DL, N0, 128);
25887       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25888     }
25889
25890     // On pre-AVX2 targets, split into 128-bit nodes of
25891     // ISD::SIGN_EXTEND_VECTOR_INREG.
25892     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25893         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25894         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25895       unsigned NumVecs = VT.getSizeInBits() / 128;
25896       unsigned NumSubElts = 128 / SVT.getSizeInBits();
25897       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25898       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25899
25900       SmallVector<SDValue, 8> Opnds;
25901       for (unsigned i = 0, Offset = 0; i != NumVecs;
25902            ++i, Offset += NumSubElts) {
25903         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25904                                      DAG.getIntPtrConstant(Offset, DL));
25905         SrcVec = ExtendVecSize(DL, SrcVec, 128);
25906         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25907         Opnds.push_back(SrcVec);
25908       }
25909       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25910     }
25911   }
25912
25913   if (Subtarget->hasAVX() && VT.isVector() && VT.getSizeInBits() == 256)
25914     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25915       return R;
25916
25917   if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
25918     return NewAdd;
25919
25920   return SDValue();
25921 }
25922
25923 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25924                                  const X86Subtarget* Subtarget) {
25925   SDLoc dl(N);
25926   EVT VT = N->getValueType(0);
25927
25928   // Let legalize expand this if it isn't a legal type yet.
25929   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25930     return SDValue();
25931
25932   EVT ScalarVT = VT.getScalarType();
25933   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25934       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25935        !Subtarget->hasAVX512()))
25936     return SDValue();
25937
25938   SDValue A = N->getOperand(0);
25939   SDValue B = N->getOperand(1);
25940   SDValue C = N->getOperand(2);
25941
25942   bool NegA = (A.getOpcode() == ISD::FNEG);
25943   bool NegB = (B.getOpcode() == ISD::FNEG);
25944   bool NegC = (C.getOpcode() == ISD::FNEG);
25945
25946   // Negative multiplication when NegA xor NegB
25947   bool NegMul = (NegA != NegB);
25948   if (NegA)
25949     A = A.getOperand(0);
25950   if (NegB)
25951     B = B.getOperand(0);
25952   if (NegC)
25953     C = C.getOperand(0);
25954
25955   unsigned Opcode;
25956   if (!NegMul)
25957     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25958   else
25959     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25960
25961   return DAG.getNode(Opcode, dl, VT, A, B, C);
25962 }
25963
25964 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25965                                   TargetLowering::DAGCombinerInfo &DCI,
25966                                   const X86Subtarget *Subtarget) {
25967   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
25968   //           (and (i32 x86isd::setcc_carry), 1)
25969   // This eliminates the zext. This transformation is necessary because
25970   // ISD::SETCC is always legalized to i8.
25971   SDLoc dl(N);
25972   SDValue N0 = N->getOperand(0);
25973   EVT VT = N->getValueType(0);
25974
25975   if (N0.getOpcode() == ISD::AND &&
25976       N0.hasOneUse() &&
25977       N0.getOperand(0).hasOneUse()) {
25978     SDValue N00 = N0.getOperand(0);
25979     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25980       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25981       if (!C || C->getZExtValue() != 1)
25982         return SDValue();
25983       return DAG.getNode(ISD::AND, dl, VT,
25984                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25985                                      N00.getOperand(0), N00.getOperand(1)),
25986                          DAG.getConstant(1, dl, VT));
25987     }
25988   }
25989
25990   if (N0.getOpcode() == ISD::TRUNCATE &&
25991       N0.hasOneUse() &&
25992       N0.getOperand(0).hasOneUse()) {
25993     SDValue N00 = N0.getOperand(0);
25994     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25995       return DAG.getNode(ISD::AND, dl, VT,
25996                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25997                                      N00.getOperand(0), N00.getOperand(1)),
25998                          DAG.getConstant(1, dl, VT));
25999     }
26000   }
26001
26002   if (VT.is256BitVector())
26003     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
26004       return R;
26005
26006   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
26007   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
26008   // This exposes the zext to the udivrem lowering, so that it directly extends
26009   // from AH (which we otherwise need to do contortions to access).
26010   if (N0.getOpcode() == ISD::UDIVREM &&
26011       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
26012       (VT == MVT::i32 || VT == MVT::i64)) {
26013     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
26014     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
26015                             N0.getOperand(0), N0.getOperand(1));
26016     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
26017     return R.getValue(1);
26018   }
26019
26020   return SDValue();
26021 }
26022
26023 // Optimize x == -y --> x+y == 0
26024 //          x != -y --> x+y != 0
26025 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
26026                                       const X86Subtarget* Subtarget) {
26027   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
26028   SDValue LHS = N->getOperand(0);
26029   SDValue RHS = N->getOperand(1);
26030   EVT VT = N->getValueType(0);
26031   SDLoc DL(N);
26032
26033   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
26034     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
26035       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
26036         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
26037                                    LHS.getOperand(1));
26038         return DAG.getSetCC(DL, N->getValueType(0), addV,
26039                             DAG.getConstant(0, DL, addV.getValueType()), CC);
26040       }
26041   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
26042     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
26043       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
26044         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
26045                                    RHS.getOperand(1));
26046         return DAG.getSetCC(DL, N->getValueType(0), addV,
26047                             DAG.getConstant(0, DL, addV.getValueType()), CC);
26048       }
26049
26050   if (VT.getScalarType() == MVT::i1 &&
26051       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
26052     bool IsSEXT0 =
26053         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
26054         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
26055     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
26056
26057     if (!IsSEXT0 || !IsVZero1) {
26058       // Swap the operands and update the condition code.
26059       std::swap(LHS, RHS);
26060       CC = ISD::getSetCCSwappedOperands(CC);
26061
26062       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
26063                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
26064       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
26065     }
26066
26067     if (IsSEXT0 && IsVZero1) {
26068       assert(VT == LHS.getOperand(0).getValueType() &&
26069              "Uexpected operand type");
26070       if (CC == ISD::SETGT)
26071         return DAG.getConstant(0, DL, VT);
26072       if (CC == ISD::SETLE)
26073         return DAG.getConstant(1, DL, VT);
26074       if (CC == ISD::SETEQ || CC == ISD::SETGE)
26075         return DAG.getNOT(DL, LHS.getOperand(0), VT);
26076
26077       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
26078              "Unexpected condition code!");
26079       return LHS.getOperand(0);
26080     }
26081   }
26082
26083   return SDValue();
26084 }
26085
26086 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
26087                                          SelectionDAG &DAG) {
26088   SDLoc dl(Load);
26089   MVT VT = Load->getSimpleValueType(0);
26090   MVT EVT = VT.getVectorElementType();
26091   SDValue Addr = Load->getOperand(1);
26092   SDValue NewAddr = DAG.getNode(
26093       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
26094       DAG.getConstant(Index * EVT.getStoreSize(), dl,
26095                       Addr.getSimpleValueType()));
26096
26097   SDValue NewLoad =
26098       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
26099                   DAG.getMachineFunction().getMachineMemOperand(
26100                       Load->getMemOperand(), 0, EVT.getStoreSize()));
26101   return NewLoad;
26102 }
26103
26104 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
26105                                       const X86Subtarget *Subtarget) {
26106   SDLoc dl(N);
26107   MVT VT = N->getOperand(1)->getSimpleValueType(0);
26108   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
26109          "X86insertps is only defined for v4x32");
26110
26111   SDValue Ld = N->getOperand(1);
26112   if (MayFoldLoad(Ld)) {
26113     // Extract the countS bits from the immediate so we can get the proper
26114     // address when narrowing the vector load to a specific element.
26115     // When the second source op is a memory address, insertps doesn't use
26116     // countS and just gets an f32 from that address.
26117     unsigned DestIndex =
26118         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
26119
26120     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
26121
26122     // Create this as a scalar to vector to match the instruction pattern.
26123     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
26124     // countS bits are ignored when loading from memory on insertps, which
26125     // means we don't need to explicitly set them to 0.
26126     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
26127                        LoadScalarToVector, N->getOperand(2));
26128   }
26129   return SDValue();
26130 }
26131
26132 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
26133   SDValue V0 = N->getOperand(0);
26134   SDValue V1 = N->getOperand(1);
26135   SDLoc DL(N);
26136   EVT VT = N->getValueType(0);
26137
26138   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
26139   // operands and changing the mask to 1. This saves us a bunch of
26140   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
26141   // x86InstrInfo knows how to commute this back after instruction selection
26142   // if it would help register allocation.
26143
26144   // TODO: If optimizing for size or a processor that doesn't suffer from
26145   // partial register update stalls, this should be transformed into a MOVSD
26146   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
26147
26148   if (VT == MVT::v2f64)
26149     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
26150       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
26151         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
26152         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
26153       }
26154
26155   return SDValue();
26156 }
26157
26158 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
26159 // as "sbb reg,reg", since it can be extended without zext and produces
26160 // an all-ones bit which is more useful than 0/1 in some cases.
26161 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
26162                                MVT VT) {
26163   if (VT == MVT::i8)
26164     return DAG.getNode(ISD::AND, DL, VT,
26165                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
26166                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
26167                                    EFLAGS),
26168                        DAG.getConstant(1, DL, VT));
26169   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
26170   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
26171                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
26172                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
26173                                  EFLAGS));
26174 }
26175
26176 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
26177 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
26178                                    TargetLowering::DAGCombinerInfo &DCI,
26179                                    const X86Subtarget *Subtarget) {
26180   SDLoc DL(N);
26181   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
26182   SDValue EFLAGS = N->getOperand(1);
26183
26184   if (CC == X86::COND_A) {
26185     // Try to convert COND_A into COND_B in an attempt to facilitate
26186     // materializing "setb reg".
26187     //
26188     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
26189     // cannot take an immediate as its first operand.
26190     //
26191     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
26192         EFLAGS.getValueType().isInteger() &&
26193         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
26194       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
26195                                    EFLAGS.getNode()->getVTList(),
26196                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
26197       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
26198       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
26199     }
26200   }
26201
26202   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
26203   // a zext and produces an all-ones bit which is more useful than 0/1 in some
26204   // cases.
26205   if (CC == X86::COND_B)
26206     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
26207
26208   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26209     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26210     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
26211   }
26212
26213   return SDValue();
26214 }
26215
26216 // Optimize branch condition evaluation.
26217 //
26218 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
26219                                     TargetLowering::DAGCombinerInfo &DCI,
26220                                     const X86Subtarget *Subtarget) {
26221   SDLoc DL(N);
26222   SDValue Chain = N->getOperand(0);
26223   SDValue Dest = N->getOperand(1);
26224   SDValue EFLAGS = N->getOperand(3);
26225   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
26226
26227   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26228     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26229     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
26230                        Flags);
26231   }
26232
26233   return SDValue();
26234 }
26235
26236 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
26237                                                          SelectionDAG &DAG) {
26238   // Take advantage of vector comparisons producing 0 or -1 in each lane to
26239   // optimize away operation when it's from a constant.
26240   //
26241   // The general transformation is:
26242   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
26243   //       AND(VECTOR_CMP(x,y), constant2)
26244   //    constant2 = UNARYOP(constant)
26245
26246   // Early exit if this isn't a vector operation, the operand of the
26247   // unary operation isn't a bitwise AND, or if the sizes of the operations
26248   // aren't the same.
26249   EVT VT = N->getValueType(0);
26250   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
26251       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
26252       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
26253     return SDValue();
26254
26255   // Now check that the other operand of the AND is a constant. We could
26256   // make the transformation for non-constant splats as well, but it's unclear
26257   // that would be a benefit as it would not eliminate any operations, just
26258   // perform one more step in scalar code before moving to the vector unit.
26259   if (BuildVectorSDNode *BV =
26260           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
26261     // Bail out if the vector isn't a constant.
26262     if (!BV->isConstant())
26263       return SDValue();
26264
26265     // Everything checks out. Build up the new and improved node.
26266     SDLoc DL(N);
26267     EVT IntVT = BV->getValueType(0);
26268     // Create a new constant of the appropriate type for the transformed
26269     // DAG.
26270     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
26271     // The AND node needs bitcasts to/from an integer vector type around it.
26272     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
26273     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
26274                                  N->getOperand(0)->getOperand(0), MaskConst);
26275     SDValue Res = DAG.getBitcast(VT, NewAnd);
26276     return Res;
26277   }
26278
26279   return SDValue();
26280 }
26281
26282 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26283                                         const X86Subtarget *Subtarget) {
26284   SDValue Op0 = N->getOperand(0);
26285   EVT VT = N->getValueType(0);
26286   EVT InVT = Op0.getValueType();
26287   EVT InSVT = InVT.getScalarType();
26288   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26289
26290   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
26291   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
26292   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26293     SDLoc dl(N);
26294     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26295                                  InVT.getVectorNumElements());
26296     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
26297
26298     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
26299       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
26300
26301     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26302   }
26303
26304   return SDValue();
26305 }
26306
26307 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26308                                         const X86Subtarget *Subtarget) {
26309   // First try to optimize away the conversion entirely when it's
26310   // conditionally from a constant. Vectors only.
26311   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
26312     return Res;
26313
26314   // Now move on to more general possibilities.
26315   SDValue Op0 = N->getOperand(0);
26316   EVT VT = N->getValueType(0);
26317   EVT InVT = Op0.getValueType();
26318   EVT InSVT = InVT.getScalarType();
26319
26320   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
26321   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
26322   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26323     SDLoc dl(N);
26324     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26325                                  InVT.getVectorNumElements());
26326     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
26327     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26328   }
26329
26330   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
26331   // a 32-bit target where SSE doesn't support i64->FP operations.
26332   if (Op0.getOpcode() == ISD::LOAD) {
26333     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
26334     EVT LdVT = Ld->getValueType(0);
26335
26336     // This transformation is not supported if the result type is f16
26337     if (VT == MVT::f16)
26338       return SDValue();
26339
26340     if (!Ld->isVolatile() && !VT.isVector() &&
26341         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
26342         !Subtarget->is64Bit() && LdVT == MVT::i64) {
26343       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
26344           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
26345       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
26346       return FILDChain;
26347     }
26348   }
26349   return SDValue();
26350 }
26351
26352 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
26353 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
26354                                  X86TargetLowering::DAGCombinerInfo &DCI) {
26355   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
26356   // the result is either zero or one (depending on the input carry bit).
26357   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
26358   if (X86::isZeroNode(N->getOperand(0)) &&
26359       X86::isZeroNode(N->getOperand(1)) &&
26360       // We don't have a good way to replace an EFLAGS use, so only do this when
26361       // dead right now.
26362       SDValue(N, 1).use_empty()) {
26363     SDLoc DL(N);
26364     EVT VT = N->getValueType(0);
26365     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
26366     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
26367                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
26368                                            DAG.getConstant(X86::COND_B, DL,
26369                                                            MVT::i8),
26370                                            N->getOperand(2)),
26371                                DAG.getConstant(1, DL, VT));
26372     return DCI.CombineTo(N, Res1, CarryOut);
26373   }
26374
26375   return SDValue();
26376 }
26377
26378 // fold (add Y, (sete  X, 0)) -> adc  0, Y
26379 //      (add Y, (setne X, 0)) -> sbb -1, Y
26380 //      (sub (sete  X, 0), Y) -> sbb  0, Y
26381 //      (sub (setne X, 0), Y) -> adc -1, Y
26382 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
26383   SDLoc DL(N);
26384
26385   // Look through ZExts.
26386   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
26387   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
26388     return SDValue();
26389
26390   SDValue SetCC = Ext.getOperand(0);
26391   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
26392     return SDValue();
26393
26394   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
26395   if (CC != X86::COND_E && CC != X86::COND_NE)
26396     return SDValue();
26397
26398   SDValue Cmp = SetCC.getOperand(1);
26399   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
26400       !X86::isZeroNode(Cmp.getOperand(1)) ||
26401       !Cmp.getOperand(0).getValueType().isInteger())
26402     return SDValue();
26403
26404   SDValue CmpOp0 = Cmp.getOperand(0);
26405   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
26406                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
26407
26408   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
26409   if (CC == X86::COND_NE)
26410     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
26411                        DL, OtherVal.getValueType(), OtherVal,
26412                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
26413                        NewCmp);
26414   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
26415                      DL, OtherVal.getValueType(), OtherVal,
26416                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
26417 }
26418
26419 /// PerformADDCombine - Do target-specific dag combines on integer adds.
26420 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
26421                                  const X86Subtarget *Subtarget) {
26422   EVT VT = N->getValueType(0);
26423   SDValue Op0 = N->getOperand(0);
26424   SDValue Op1 = N->getOperand(1);
26425
26426   // Try to synthesize horizontal adds from adds of shuffles.
26427   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26428        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26429       isHorizontalBinOp(Op0, Op1, true))
26430     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
26431
26432   return OptimizeConditionalInDecrement(N, DAG);
26433 }
26434
26435 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
26436                                  const X86Subtarget *Subtarget) {
26437   SDValue Op0 = N->getOperand(0);
26438   SDValue Op1 = N->getOperand(1);
26439
26440   // X86 can't encode an immediate LHS of a sub. See if we can push the
26441   // negation into a preceding instruction.
26442   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
26443     // If the RHS of the sub is a XOR with one use and a constant, invert the
26444     // immediate. Then add one to the LHS of the sub so we can turn
26445     // X-Y -> X+~Y+1, saving one register.
26446     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
26447         isa<ConstantSDNode>(Op1.getOperand(1))) {
26448       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
26449       EVT VT = Op0.getValueType();
26450       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
26451                                    Op1.getOperand(0),
26452                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
26453       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
26454                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
26455     }
26456   }
26457
26458   // Try to synthesize horizontal adds from adds of shuffles.
26459   EVT VT = N->getValueType(0);
26460   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26461        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26462       isHorizontalBinOp(Op0, Op1, true))
26463     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
26464
26465   return OptimizeConditionalInDecrement(N, DAG);
26466 }
26467
26468 /// performVZEXTCombine - Performs build vector combines
26469 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
26470                                    TargetLowering::DAGCombinerInfo &DCI,
26471                                    const X86Subtarget *Subtarget) {
26472   SDLoc DL(N);
26473   MVT VT = N->getSimpleValueType(0);
26474   SDValue Op = N->getOperand(0);
26475   MVT OpVT = Op.getSimpleValueType();
26476   MVT OpEltVT = OpVT.getVectorElementType();
26477   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
26478
26479   // (vzext (bitcast (vzext (x)) -> (vzext x)
26480   SDValue V = Op;
26481   while (V.getOpcode() == ISD::BITCAST)
26482     V = V.getOperand(0);
26483
26484   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
26485     MVT InnerVT = V.getSimpleValueType();
26486     MVT InnerEltVT = InnerVT.getVectorElementType();
26487
26488     // If the element sizes match exactly, we can just do one larger vzext. This
26489     // is always an exact type match as vzext operates on integer types.
26490     if (OpEltVT == InnerEltVT) {
26491       assert(OpVT == InnerVT && "Types must match for vzext!");
26492       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
26493     }
26494
26495     // The only other way we can combine them is if only a single element of the
26496     // inner vzext is used in the input to the outer vzext.
26497     if (InnerEltVT.getSizeInBits() < InputBits)
26498       return SDValue();
26499
26500     // In this case, the inner vzext is completely dead because we're going to
26501     // only look at bits inside of the low element. Just do the outer vzext on
26502     // a bitcast of the input to the inner.
26503     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
26504   }
26505
26506   // Check if we can bypass extracting and re-inserting an element of an input
26507   // vector. Essentially:
26508   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
26509   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
26510       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
26511       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
26512     SDValue ExtractedV = V.getOperand(0);
26513     SDValue OrigV = ExtractedV.getOperand(0);
26514     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
26515       if (ExtractIdx->getZExtValue() == 0) {
26516         MVT OrigVT = OrigV.getSimpleValueType();
26517         // Extract a subvector if necessary...
26518         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
26519           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
26520           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
26521                                     OrigVT.getVectorNumElements() / Ratio);
26522           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
26523                               DAG.getIntPtrConstant(0, DL));
26524         }
26525         Op = DAG.getBitcast(OpVT, OrigV);
26526         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
26527       }
26528   }
26529
26530   return SDValue();
26531 }
26532
26533 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
26534                                              DAGCombinerInfo &DCI) const {
26535   SelectionDAG &DAG = DCI.DAG;
26536   switch (N->getOpcode()) {
26537   default: break;
26538   case ISD::EXTRACT_VECTOR_ELT:
26539     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
26540   case ISD::VSELECT:
26541   case ISD::SELECT:
26542   case X86ISD::SHRUNKBLEND:
26543     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
26544   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
26545   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
26546   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
26547   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
26548   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
26549   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
26550   case ISD::SHL:
26551   case ISD::SRA:
26552   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
26553   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
26554   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
26555   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
26556   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
26557   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
26558   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
26559   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
26560   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
26561   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
26562   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
26563   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
26564   case X86ISD::FXOR:
26565   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
26566   case X86ISD::FMIN:
26567   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
26568   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
26569   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
26570   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
26571   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
26572   case ISD::ANY_EXTEND:
26573   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
26574   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
26575   case ISD::SIGN_EXTEND_INREG:
26576     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
26577   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
26578   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
26579   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
26580   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
26581   case X86ISD::SHUFP:       // Handle all target specific shuffles
26582   case X86ISD::PALIGNR:
26583   case X86ISD::UNPCKH:
26584   case X86ISD::UNPCKL:
26585   case X86ISD::MOVHLPS:
26586   case X86ISD::MOVLHPS:
26587   case X86ISD::PSHUFB:
26588   case X86ISD::PSHUFD:
26589   case X86ISD::PSHUFHW:
26590   case X86ISD::PSHUFLW:
26591   case X86ISD::MOVSS:
26592   case X86ISD::MOVSD:
26593   case X86ISD::VPERMILPI:
26594   case X86ISD::VPERM2X128:
26595   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
26596   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
26597   case X86ISD::INSERTPS: {
26598     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
26599       return PerformINSERTPSCombine(N, DAG, Subtarget);
26600     break;
26601   }
26602   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
26603   }
26604
26605   return SDValue();
26606 }
26607
26608 /// isTypeDesirableForOp - Return true if the target has native support for
26609 /// the specified value type and it is 'desirable' to use the type for the
26610 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
26611 /// instruction encodings are longer and some i16 instructions are slow.
26612 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
26613   if (!isTypeLegal(VT))
26614     return false;
26615   if (VT != MVT::i16)
26616     return true;
26617
26618   switch (Opc) {
26619   default:
26620     return true;
26621   case ISD::LOAD:
26622   case ISD::SIGN_EXTEND:
26623   case ISD::ZERO_EXTEND:
26624   case ISD::ANY_EXTEND:
26625   case ISD::SHL:
26626   case ISD::SRL:
26627   case ISD::SUB:
26628   case ISD::ADD:
26629   case ISD::MUL:
26630   case ISD::AND:
26631   case ISD::OR:
26632   case ISD::XOR:
26633     return false;
26634   }
26635 }
26636
26637 /// IsDesirableToPromoteOp - This method query the target whether it is
26638 /// beneficial for dag combiner to promote the specified node. If true, it
26639 /// should return the desired promotion type by reference.
26640 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
26641   EVT VT = Op.getValueType();
26642   if (VT != MVT::i16)
26643     return false;
26644
26645   bool Promote = false;
26646   bool Commute = false;
26647   switch (Op.getOpcode()) {
26648   default: break;
26649   case ISD::LOAD: {
26650     LoadSDNode *LD = cast<LoadSDNode>(Op);
26651     // If the non-extending load has a single use and it's not live out, then it
26652     // might be folded.
26653     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
26654                                                      Op.hasOneUse()*/) {
26655       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
26656              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
26657         // The only case where we'd want to promote LOAD (rather then it being
26658         // promoted as an operand is when it's only use is liveout.
26659         if (UI->getOpcode() != ISD::CopyToReg)
26660           return false;
26661       }
26662     }
26663     Promote = true;
26664     break;
26665   }
26666   case ISD::SIGN_EXTEND:
26667   case ISD::ZERO_EXTEND:
26668   case ISD::ANY_EXTEND:
26669     Promote = true;
26670     break;
26671   case ISD::SHL:
26672   case ISD::SRL: {
26673     SDValue N0 = Op.getOperand(0);
26674     // Look out for (store (shl (load), x)).
26675     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
26676       return false;
26677     Promote = true;
26678     break;
26679   }
26680   case ISD::ADD:
26681   case ISD::MUL:
26682   case ISD::AND:
26683   case ISD::OR:
26684   case ISD::XOR:
26685     Commute = true;
26686     // fallthrough
26687   case ISD::SUB: {
26688     SDValue N0 = Op.getOperand(0);
26689     SDValue N1 = Op.getOperand(1);
26690     if (!Commute && MayFoldLoad(N1))
26691       return false;
26692     // Avoid disabling potential load folding opportunities.
26693     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
26694       return false;
26695     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
26696       return false;
26697     Promote = true;
26698   }
26699   }
26700
26701   PVT = MVT::i32;
26702   return Promote;
26703 }
26704
26705 //===----------------------------------------------------------------------===//
26706 //                           X86 Inline Assembly Support
26707 //===----------------------------------------------------------------------===//
26708
26709 // Helper to match a string separated by whitespace.
26710 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
26711   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
26712
26713   for (StringRef Piece : Pieces) {
26714     if (!S.startswith(Piece)) // Check if the piece matches.
26715       return false;
26716
26717     S = S.substr(Piece.size());
26718     StringRef::size_type Pos = S.find_first_not_of(" \t");
26719     if (Pos == 0) // We matched a prefix.
26720       return false;
26721
26722     S = S.substr(Pos);
26723   }
26724
26725   return S.empty();
26726 }
26727
26728 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26729
26730   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26731     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26732         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26733         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26734
26735       if (AsmPieces.size() == 3)
26736         return true;
26737       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26738         return true;
26739     }
26740   }
26741   return false;
26742 }
26743
26744 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26745   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26746
26747   std::string AsmStr = IA->getAsmString();
26748
26749   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26750   if (!Ty || Ty->getBitWidth() % 16 != 0)
26751     return false;
26752
26753   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26754   SmallVector<StringRef, 4> AsmPieces;
26755   SplitString(AsmStr, AsmPieces, ";\n");
26756
26757   switch (AsmPieces.size()) {
26758   default: return false;
26759   case 1:
26760     // FIXME: this should verify that we are targeting a 486 or better.  If not,
26761     // we will turn this bswap into something that will be lowered to logical
26762     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
26763     // lower so don't worry about this.
26764     // bswap $0
26765     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26766         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26767         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26768         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26769         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26770         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26771       // No need to check constraints, nothing other than the equivalent of
26772       // "=r,0" would be valid here.
26773       return IntrinsicLowering::LowerToByteSwap(CI);
26774     }
26775
26776     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
26777     if (CI->getType()->isIntegerTy(16) &&
26778         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26779         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26780          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26781       AsmPieces.clear();
26782       StringRef ConstraintsStr = IA->getConstraintString();
26783       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26784       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26785       if (clobbersFlagRegisters(AsmPieces))
26786         return IntrinsicLowering::LowerToByteSwap(CI);
26787     }
26788     break;
26789   case 3:
26790     if (CI->getType()->isIntegerTy(32) &&
26791         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26792         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26793         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26794         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26795       AsmPieces.clear();
26796       StringRef ConstraintsStr = IA->getConstraintString();
26797       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26798       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26799       if (clobbersFlagRegisters(AsmPieces))
26800         return IntrinsicLowering::LowerToByteSwap(CI);
26801     }
26802
26803     if (CI->getType()->isIntegerTy(64)) {
26804       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26805       if (Constraints.size() >= 2 &&
26806           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26807           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26808         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
26809         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26810             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26811             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26812           return IntrinsicLowering::LowerToByteSwap(CI);
26813       }
26814     }
26815     break;
26816   }
26817   return false;
26818 }
26819
26820 /// getConstraintType - Given a constraint letter, return the type of
26821 /// constraint it is for this target.
26822 X86TargetLowering::ConstraintType
26823 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26824   if (Constraint.size() == 1) {
26825     switch (Constraint[0]) {
26826     case 'R':
26827     case 'q':
26828     case 'Q':
26829     case 'f':
26830     case 't':
26831     case 'u':
26832     case 'y':
26833     case 'x':
26834     case 'Y':
26835     case 'l':
26836       return C_RegisterClass;
26837     case 'a':
26838     case 'b':
26839     case 'c':
26840     case 'd':
26841     case 'S':
26842     case 'D':
26843     case 'A':
26844       return C_Register;
26845     case 'I':
26846     case 'J':
26847     case 'K':
26848     case 'L':
26849     case 'M':
26850     case 'N':
26851     case 'G':
26852     case 'C':
26853     case 'e':
26854     case 'Z':
26855       return C_Other;
26856     default:
26857       break;
26858     }
26859   }
26860   return TargetLowering::getConstraintType(Constraint);
26861 }
26862
26863 /// Examine constraint type and operand type and determine a weight value.
26864 /// This object must already have been set up with the operand type
26865 /// and the current alternative constraint selected.
26866 TargetLowering::ConstraintWeight
26867   X86TargetLowering::getSingleConstraintMatchWeight(
26868     AsmOperandInfo &info, const char *constraint) const {
26869   ConstraintWeight weight = CW_Invalid;
26870   Value *CallOperandVal = info.CallOperandVal;
26871     // If we don't have a value, we can't do a match,
26872     // but allow it at the lowest weight.
26873   if (!CallOperandVal)
26874     return CW_Default;
26875   Type *type = CallOperandVal->getType();
26876   // Look at the constraint type.
26877   switch (*constraint) {
26878   default:
26879     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26880   case 'R':
26881   case 'q':
26882   case 'Q':
26883   case 'a':
26884   case 'b':
26885   case 'c':
26886   case 'd':
26887   case 'S':
26888   case 'D':
26889   case 'A':
26890     if (CallOperandVal->getType()->isIntegerTy())
26891       weight = CW_SpecificReg;
26892     break;
26893   case 'f':
26894   case 't':
26895   case 'u':
26896     if (type->isFloatingPointTy())
26897       weight = CW_SpecificReg;
26898     break;
26899   case 'y':
26900     if (type->isX86_MMXTy() && Subtarget->hasMMX())
26901       weight = CW_SpecificReg;
26902     break;
26903   case 'x':
26904   case 'Y':
26905     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26906         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26907       weight = CW_Register;
26908     break;
26909   case 'I':
26910     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26911       if (C->getZExtValue() <= 31)
26912         weight = CW_Constant;
26913     }
26914     break;
26915   case 'J':
26916     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26917       if (C->getZExtValue() <= 63)
26918         weight = CW_Constant;
26919     }
26920     break;
26921   case 'K':
26922     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26923       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26924         weight = CW_Constant;
26925     }
26926     break;
26927   case 'L':
26928     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26929       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26930         weight = CW_Constant;
26931     }
26932     break;
26933   case 'M':
26934     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26935       if (C->getZExtValue() <= 3)
26936         weight = CW_Constant;
26937     }
26938     break;
26939   case 'N':
26940     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26941       if (C->getZExtValue() <= 0xff)
26942         weight = CW_Constant;
26943     }
26944     break;
26945   case 'G':
26946   case 'C':
26947     if (isa<ConstantFP>(CallOperandVal)) {
26948       weight = CW_Constant;
26949     }
26950     break;
26951   case 'e':
26952     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26953       if ((C->getSExtValue() >= -0x80000000LL) &&
26954           (C->getSExtValue() <= 0x7fffffffLL))
26955         weight = CW_Constant;
26956     }
26957     break;
26958   case 'Z':
26959     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26960       if (C->getZExtValue() <= 0xffffffff)
26961         weight = CW_Constant;
26962     }
26963     break;
26964   }
26965   return weight;
26966 }
26967
26968 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26969 /// with another that has more specific requirements based on the type of the
26970 /// corresponding operand.
26971 const char *X86TargetLowering::
26972 LowerXConstraint(EVT ConstraintVT) const {
26973   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26974   // 'f' like normal targets.
26975   if (ConstraintVT.isFloatingPoint()) {
26976     if (Subtarget->hasSSE2())
26977       return "Y";
26978     if (Subtarget->hasSSE1())
26979       return "x";
26980   }
26981
26982   return TargetLowering::LowerXConstraint(ConstraintVT);
26983 }
26984
26985 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26986 /// vector.  If it is invalid, don't add anything to Ops.
26987 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26988                                                      std::string &Constraint,
26989                                                      std::vector<SDValue>&Ops,
26990                                                      SelectionDAG &DAG) const {
26991   SDValue Result;
26992
26993   // Only support length 1 constraints for now.
26994   if (Constraint.length() > 1) return;
26995
26996   char ConstraintLetter = Constraint[0];
26997   switch (ConstraintLetter) {
26998   default: break;
26999   case 'I':
27000     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27001       if (C->getZExtValue() <= 31) {
27002         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27003                                        Op.getValueType());
27004         break;
27005       }
27006     }
27007     return;
27008   case 'J':
27009     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27010       if (C->getZExtValue() <= 63) {
27011         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27012                                        Op.getValueType());
27013         break;
27014       }
27015     }
27016     return;
27017   case 'K':
27018     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27019       if (isInt<8>(C->getSExtValue())) {
27020         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27021                                        Op.getValueType());
27022         break;
27023       }
27024     }
27025     return;
27026   case 'L':
27027     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27028       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
27029           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
27030         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
27031                                        Op.getValueType());
27032         break;
27033       }
27034     }
27035     return;
27036   case 'M':
27037     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27038       if (C->getZExtValue() <= 3) {
27039         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27040                                        Op.getValueType());
27041         break;
27042       }
27043     }
27044     return;
27045   case 'N':
27046     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27047       if (C->getZExtValue() <= 255) {
27048         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27049                                        Op.getValueType());
27050         break;
27051       }
27052     }
27053     return;
27054   case 'O':
27055     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27056       if (C->getZExtValue() <= 127) {
27057         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27058                                        Op.getValueType());
27059         break;
27060       }
27061     }
27062     return;
27063   case 'e': {
27064     // 32-bit signed value
27065     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27066       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
27067                                            C->getSExtValue())) {
27068         // Widen to 64 bits here to get it sign extended.
27069         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
27070         break;
27071       }
27072     // FIXME gcc accepts some relocatable values here too, but only in certain
27073     // memory models; it's complicated.
27074     }
27075     return;
27076   }
27077   case 'Z': {
27078     // 32-bit unsigned value
27079     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27080       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
27081                                            C->getZExtValue())) {
27082         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27083                                        Op.getValueType());
27084         break;
27085       }
27086     }
27087     // FIXME gcc accepts some relocatable values here too, but only in certain
27088     // memory models; it's complicated.
27089     return;
27090   }
27091   case 'i': {
27092     // Literal immediates are always ok.
27093     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
27094       // Widen to 64 bits here to get it sign extended.
27095       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
27096       break;
27097     }
27098
27099     // In any sort of PIC mode addresses need to be computed at runtime by
27100     // adding in a register or some sort of table lookup.  These can't
27101     // be used as immediates.
27102     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
27103       return;
27104
27105     // If we are in non-pic codegen mode, we allow the address of a global (with
27106     // an optional displacement) to be used with 'i'.
27107     GlobalAddressSDNode *GA = nullptr;
27108     int64_t Offset = 0;
27109
27110     // Match either (GA), (GA+C), (GA+C1+C2), etc.
27111     while (1) {
27112       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
27113         Offset += GA->getOffset();
27114         break;
27115       } else if (Op.getOpcode() == ISD::ADD) {
27116         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
27117           Offset += C->getZExtValue();
27118           Op = Op.getOperand(0);
27119           continue;
27120         }
27121       } else if (Op.getOpcode() == ISD::SUB) {
27122         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
27123           Offset += -C->getZExtValue();
27124           Op = Op.getOperand(0);
27125           continue;
27126         }
27127       }
27128
27129       // Otherwise, this isn't something we can handle, reject it.
27130       return;
27131     }
27132
27133     const GlobalValue *GV = GA->getGlobal();
27134     // If we require an extra load to get this address, as in PIC mode, we
27135     // can't accept it.
27136     if (isGlobalStubReference(
27137             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
27138       return;
27139
27140     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
27141                                         GA->getValueType(0), Offset);
27142     break;
27143   }
27144   }
27145
27146   if (Result.getNode()) {
27147     Ops.push_back(Result);
27148     return;
27149   }
27150   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
27151 }
27152
27153 std::pair<unsigned, const TargetRegisterClass *>
27154 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
27155                                                 StringRef Constraint,
27156                                                 MVT VT) const {
27157   // First, see if this is a constraint that directly corresponds to an LLVM
27158   // register class.
27159   if (Constraint.size() == 1) {
27160     // GCC Constraint Letters
27161     switch (Constraint[0]) {
27162     default: break;
27163       // TODO: Slight differences here in allocation order and leaving
27164       // RIP in the class. Do they matter any more here than they do
27165       // in the normal allocation?
27166     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
27167       if (Subtarget->is64Bit()) {
27168         if (VT == MVT::i32 || VT == MVT::f32)
27169           return std::make_pair(0U, &X86::GR32RegClass);
27170         if (VT == MVT::i16)
27171           return std::make_pair(0U, &X86::GR16RegClass);
27172         if (VT == MVT::i8 || VT == MVT::i1)
27173           return std::make_pair(0U, &X86::GR8RegClass);
27174         if (VT == MVT::i64 || VT == MVT::f64)
27175           return std::make_pair(0U, &X86::GR64RegClass);
27176         break;
27177       }
27178       // 32-bit fallthrough
27179     case 'Q':   // Q_REGS
27180       if (VT == MVT::i32 || VT == MVT::f32)
27181         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
27182       if (VT == MVT::i16)
27183         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
27184       if (VT == MVT::i8 || VT == MVT::i1)
27185         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
27186       if (VT == MVT::i64)
27187         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
27188       break;
27189     case 'r':   // GENERAL_REGS
27190     case 'l':   // INDEX_REGS
27191       if (VT == MVT::i8 || VT == MVT::i1)
27192         return std::make_pair(0U, &X86::GR8RegClass);
27193       if (VT == MVT::i16)
27194         return std::make_pair(0U, &X86::GR16RegClass);
27195       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
27196         return std::make_pair(0U, &X86::GR32RegClass);
27197       return std::make_pair(0U, &X86::GR64RegClass);
27198     case 'R':   // LEGACY_REGS
27199       if (VT == MVT::i8 || VT == MVT::i1)
27200         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
27201       if (VT == MVT::i16)
27202         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
27203       if (VT == MVT::i32 || !Subtarget->is64Bit())
27204         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
27205       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
27206     case 'f':  // FP Stack registers.
27207       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
27208       // value to the correct fpstack register class.
27209       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
27210         return std::make_pair(0U, &X86::RFP32RegClass);
27211       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
27212         return std::make_pair(0U, &X86::RFP64RegClass);
27213       return std::make_pair(0U, &X86::RFP80RegClass);
27214     case 'y':   // MMX_REGS if MMX allowed.
27215       if (!Subtarget->hasMMX()) break;
27216       return std::make_pair(0U, &X86::VR64RegClass);
27217     case 'Y':   // SSE_REGS if SSE2 allowed
27218       if (!Subtarget->hasSSE2()) break;
27219       // FALL THROUGH.
27220     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
27221       if (!Subtarget->hasSSE1()) break;
27222
27223       switch (VT.SimpleTy) {
27224       default: break;
27225       // Scalar SSE types.
27226       case MVT::f32:
27227       case MVT::i32:
27228         return std::make_pair(0U, &X86::FR32RegClass);
27229       case MVT::f64:
27230       case MVT::i64:
27231         return std::make_pair(0U, &X86::FR64RegClass);
27232       // Vector types.
27233       case MVT::v16i8:
27234       case MVT::v8i16:
27235       case MVT::v4i32:
27236       case MVT::v2i64:
27237       case MVT::v4f32:
27238       case MVT::v2f64:
27239         return std::make_pair(0U, &X86::VR128RegClass);
27240       // AVX types.
27241       case MVT::v32i8:
27242       case MVT::v16i16:
27243       case MVT::v8i32:
27244       case MVT::v4i64:
27245       case MVT::v8f32:
27246       case MVT::v4f64:
27247         return std::make_pair(0U, &X86::VR256RegClass);
27248       case MVT::v8f64:
27249       case MVT::v16f32:
27250       case MVT::v16i32:
27251       case MVT::v8i64:
27252         return std::make_pair(0U, &X86::VR512RegClass);
27253       }
27254       break;
27255     }
27256   }
27257
27258   // Use the default implementation in TargetLowering to convert the register
27259   // constraint into a member of a register class.
27260   std::pair<unsigned, const TargetRegisterClass*> Res;
27261   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
27262
27263   // Not found as a standard register?
27264   if (!Res.second) {
27265     // Map st(0) -> st(7) -> ST0
27266     if (Constraint.size() == 7 && Constraint[0] == '{' &&
27267         tolower(Constraint[1]) == 's' &&
27268         tolower(Constraint[2]) == 't' &&
27269         Constraint[3] == '(' &&
27270         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
27271         Constraint[5] == ')' &&
27272         Constraint[6] == '}') {
27273
27274       Res.first = X86::FP0+Constraint[4]-'0';
27275       Res.second = &X86::RFP80RegClass;
27276       return Res;
27277     }
27278
27279     // GCC allows "st(0)" to be called just plain "st".
27280     if (StringRef("{st}").equals_lower(Constraint)) {
27281       Res.first = X86::FP0;
27282       Res.second = &X86::RFP80RegClass;
27283       return Res;
27284     }
27285
27286     // flags -> EFLAGS
27287     if (StringRef("{flags}").equals_lower(Constraint)) {
27288       Res.first = X86::EFLAGS;
27289       Res.second = &X86::CCRRegClass;
27290       return Res;
27291     }
27292
27293     // 'A' means EAX + EDX.
27294     if (Constraint == "A") {
27295       Res.first = X86::EAX;
27296       Res.second = &X86::GR32_ADRegClass;
27297       return Res;
27298     }
27299     return Res;
27300   }
27301
27302   // Otherwise, check to see if this is a register class of the wrong value
27303   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
27304   // turn into {ax},{dx}.
27305   // MVT::Other is used to specify clobber names.
27306   if (Res.second->hasType(VT) || VT == MVT::Other)
27307     return Res;   // Correct type already, nothing to do.
27308
27309   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
27310   // return "eax". This should even work for things like getting 64bit integer
27311   // registers when given an f64 type.
27312   const TargetRegisterClass *Class = Res.second;
27313   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
27314       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
27315     unsigned Size = VT.getSizeInBits();
27316     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
27317                                   : Size == 16 ? MVT::i16
27318                                   : Size == 32 ? MVT::i32
27319                                   : Size == 64 ? MVT::i64
27320                                   : MVT::Other;
27321     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
27322     if (DestReg > 0) {
27323       Res.first = DestReg;
27324       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
27325                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
27326                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
27327                  : &X86::GR64RegClass;
27328       assert(Res.second->contains(Res.first) && "Register in register class");
27329     } else {
27330       // No register found/type mismatch.
27331       Res.first = 0;
27332       Res.second = nullptr;
27333     }
27334   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
27335              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
27336              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
27337              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
27338              Class == &X86::VR512RegClass) {
27339     // Handle references to XMM physical registers that got mapped into the
27340     // wrong class.  This can happen with constraints like {xmm0} where the
27341     // target independent register mapper will just pick the first match it can
27342     // find, ignoring the required type.
27343
27344     if (VT == MVT::f32 || VT == MVT::i32)
27345       Res.second = &X86::FR32RegClass;
27346     else if (VT == MVT::f64 || VT == MVT::i64)
27347       Res.second = &X86::FR64RegClass;
27348     else if (X86::VR128RegClass.hasType(VT))
27349       Res.second = &X86::VR128RegClass;
27350     else if (X86::VR256RegClass.hasType(VT))
27351       Res.second = &X86::VR256RegClass;
27352     else if (X86::VR512RegClass.hasType(VT))
27353       Res.second = &X86::VR512RegClass;
27354     else {
27355       // Type mismatch and not a clobber: Return an error;
27356       Res.first = 0;
27357       Res.second = nullptr;
27358     }
27359   }
27360
27361   return Res;
27362 }
27363
27364 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
27365                                             const AddrMode &AM, Type *Ty,
27366                                             unsigned AS) const {
27367   // Scaling factors are not free at all.
27368   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
27369   // will take 2 allocations in the out of order engine instead of 1
27370   // for plain addressing mode, i.e. inst (reg1).
27371   // E.g.,
27372   // vaddps (%rsi,%drx), %ymm0, %ymm1
27373   // Requires two allocations (one for the load, one for the computation)
27374   // whereas:
27375   // vaddps (%rsi), %ymm0, %ymm1
27376   // Requires just 1 allocation, i.e., freeing allocations for other operations
27377   // and having less micro operations to execute.
27378   //
27379   // For some X86 architectures, this is even worse because for instance for
27380   // stores, the complex addressing mode forces the instruction to use the
27381   // "load" ports instead of the dedicated "store" port.
27382   // E.g., on Haswell:
27383   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
27384   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
27385   if (isLegalAddressingMode(DL, AM, Ty, AS))
27386     // Scale represents reg2 * scale, thus account for 1
27387     // as soon as we use a second register.
27388     return AM.Scale != 0;
27389   return -1;
27390 }
27391
27392 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
27393   // Integer division on x86 is expensive. However, when aggressively optimizing
27394   // for code size, we prefer to use a div instruction, as it is usually smaller
27395   // than the alternative sequence.
27396   // The exception to this is vector division. Since x86 doesn't have vector
27397   // integer division, leaving the division as-is is a loss even in terms of
27398   // size, because it will have to be scalarized, while the alternative code
27399   // sequence can be performed in vector form.
27400   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
27401                                    Attribute::MinSize);
27402   return OptSize && !VT.isVector();
27403 }