4f18b82bd99dd4208e6b90719b5cee0e0eb8f264
[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
1283     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1284     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1285       MVT VT = (MVT::SimpleValueType)i;
1286
1287       // Do not attempt to promote non-256-bit vectors
1288       if (!VT.is256BitVector())
1289         continue;
1290
1291       setOperationAction(ISD::AND,    VT, Promote);
1292       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1293       setOperationAction(ISD::OR,     VT, Promote);
1294       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1295       setOperationAction(ISD::XOR,    VT, Promote);
1296       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1297       setOperationAction(ISD::LOAD,   VT, Promote);
1298       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1299       setOperationAction(ISD::SELECT, VT, Promote);
1300       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1301     }
1302   }
1303
1304   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1305     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1306     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1307     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1308     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1309
1310     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1311     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1312     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1313
1314     for (MVT VT : MVT::fp_vector_valuetypes())
1315       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1316
1317     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1318     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1319     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1320     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1321     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1322     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1323     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1324     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1325     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1326     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1327     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1328     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1329
1330     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1331     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1332     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1333     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1334     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1335     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1336     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1337     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1338     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1339     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1340     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1341     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1342     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1343
1344     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1345     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1346     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1347     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1348     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1349     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1350
1351     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1352     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1353     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1354     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1355     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1356     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1357     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1358     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1359
1360     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1361     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1362     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1363     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1364     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1365     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1366     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1367     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1368     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1369     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1370     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1371     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1372     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1373     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1374     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1375     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1376
1377     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1378     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1379     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1380     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1381     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1382     if (Subtarget->hasVLX()){
1383       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1384       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1385       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1386       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1387       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1388
1389       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1390       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1391       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1392       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1393       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1394     }
1395     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1396     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1397     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1398     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i1,  Custom);
1399     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v16i1, Custom);
1400     if (Subtarget->hasDQI()) {
1401       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1402       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1403
1404       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1405       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1406       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1407       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1408       if (Subtarget->hasVLX()) {
1409         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1410         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1411         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1412         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1413         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1414         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1415         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1416         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1417       }
1418     }
1419     if (Subtarget->hasVLX()) {
1420       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1421       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1422       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1423       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1424       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1425       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1426       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1427       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1428     }
1429     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1430     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1431     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1432     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1433     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1434     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1435     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1436     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1437     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1438     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1439     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1440     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1441     if (Subtarget->hasDQI()) {
1442       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1443       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1444     }
1445     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1446     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1447     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1448     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1449     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1450     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1451     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1452     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1453     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1454     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1455
1456     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1457     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1458     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1459     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1460     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1461
1462     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1463     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1464
1465     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1466
1467     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1468     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1469     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1470     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1471     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1472     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1473     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1474     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1475     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1476     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1477     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1478
1479     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1480     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1481     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1482     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1483     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1484     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1485     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1486     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1487
1488     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1489     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1490
1491     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1492     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1493
1494     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1495
1496     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1497     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1498
1499     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1500     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1501
1502     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1503     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1504
1505     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1506     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1507     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1508     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1509     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1510     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1511
1512     if (Subtarget->hasCDI()) {
1513       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1514       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1515       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64, Legal);
1516       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Legal);
1517
1518       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i64, Custom);
1519       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v16i32, Custom);
1520     }
1521     if (Subtarget->hasVLX() && Subtarget->hasCDI()) {
1522       setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1523       setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1524       setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1525       setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1526       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Legal);
1527       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Legal);
1528       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Legal);
1529       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Legal);
1530
1531       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1532       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1533       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1534       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1535     }
1536     if (Subtarget->hasDQI()) {
1537       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1538       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1539       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1540     }
1541     // Custom lower several nodes.
1542     for (MVT VT : MVT::vector_valuetypes()) {
1543       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1544       if (EltSize == 1) {
1545         setOperationAction(ISD::AND, VT, Legal);
1546         setOperationAction(ISD::OR,  VT, Legal);
1547         setOperationAction(ISD::XOR,  VT, Legal);
1548       }
1549       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1550         setOperationAction(ISD::MGATHER,  VT, Custom);
1551         setOperationAction(ISD::MSCATTER, VT, Custom);
1552       }
1553       // Extract subvector is special because the value type
1554       // (result) is 256/128-bit but the source is 512-bit wide.
1555       if (VT.is128BitVector() || VT.is256BitVector()) {
1556         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1557       }
1558       if (VT.getVectorElementType() == MVT::i1)
1559         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1560
1561       // Do not attempt to custom lower other non-512-bit vectors
1562       if (!VT.is512BitVector())
1563         continue;
1564
1565       if (EltSize >= 32) {
1566         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1567         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1568         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1569         setOperationAction(ISD::VSELECT,             VT, Legal);
1570         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1571         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1572         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1573         setOperationAction(ISD::MLOAD,               VT, Legal);
1574         setOperationAction(ISD::MSTORE,              VT, Legal);
1575       }
1576     }
1577     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1578       MVT VT = (MVT::SimpleValueType)i;
1579
1580       // Do not attempt to promote non-512-bit vectors.
1581       if (!VT.is512BitVector())
1582         continue;
1583
1584       setOperationAction(ISD::SELECT, VT, Promote);
1585       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1586     }
1587   }// has  AVX-512
1588
1589   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1590     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1591     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1592
1593     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1594     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1595
1596     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1597     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1598     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1599     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1600     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1601     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1602     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1603     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1604     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1605     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1606     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1607     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Legal);
1608     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Legal);
1609     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1610     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1611     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1612     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1613     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1614     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1615     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1616     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1617     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1618     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1619     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1620     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1621     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1622     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1623     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1624     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1625     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1626     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1627     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i1, Custom);
1628     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i1, Custom);
1629
1630     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1631     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1632     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1633     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1634     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1635     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1636     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1637     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1638
1639     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1640     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1641     if (Subtarget->hasVLX())
1642       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1643
1644     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1645       const MVT VT = (MVT::SimpleValueType)i;
1646
1647       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1648
1649       // Do not attempt to promote non-512-bit vectors.
1650       if (!VT.is512BitVector())
1651         continue;
1652
1653       if (EltSize < 32) {
1654         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1655         setOperationAction(ISD::VSELECT,             VT, Legal);
1656       }
1657     }
1658   }
1659
1660   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1661     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1662     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1663
1664     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1665     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1666     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1667     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1668     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1669     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1670     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1671     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1672     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1673     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1674     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i1, Custom);
1675     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i1, Custom);
1676
1677     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1678     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1679     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1680     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1681     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1682     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1683     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1684     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1685
1686     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1687     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1688     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1689     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1690     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1691     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1692     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1693     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1694   }
1695
1696   // We want to custom lower some of our intrinsics.
1697   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1698   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1699   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1700   if (!Subtarget->is64Bit())
1701     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1702
1703   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1704   // handle type legalization for these operations here.
1705   //
1706   // FIXME: We really should do custom legalization for addition and
1707   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1708   // than generic legalization for 64-bit multiplication-with-overflow, though.
1709   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1710     // Add/Sub/Mul with overflow operations are custom lowered.
1711     MVT VT = IntVTs[i];
1712     setOperationAction(ISD::SADDO, VT, Custom);
1713     setOperationAction(ISD::UADDO, VT, Custom);
1714     setOperationAction(ISD::SSUBO, VT, Custom);
1715     setOperationAction(ISD::USUBO, VT, Custom);
1716     setOperationAction(ISD::SMULO, VT, Custom);
1717     setOperationAction(ISD::UMULO, VT, Custom);
1718   }
1719
1720
1721   if (!Subtarget->is64Bit()) {
1722     // These libcalls are not available in 32-bit.
1723     setLibcallName(RTLIB::SHL_I128, nullptr);
1724     setLibcallName(RTLIB::SRL_I128, nullptr);
1725     setLibcallName(RTLIB::SRA_I128, nullptr);
1726   }
1727
1728   // Combine sin / cos into one node or libcall if possible.
1729   if (Subtarget->hasSinCos()) {
1730     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1731     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1732     if (Subtarget->isTargetDarwin()) {
1733       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1734       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1735       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1736       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1737     }
1738   }
1739
1740   if (Subtarget->isTargetWin64()) {
1741     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1742     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1743     setOperationAction(ISD::SREM, MVT::i128, Custom);
1744     setOperationAction(ISD::UREM, MVT::i128, Custom);
1745     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1746     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1747   }
1748
1749   // We have target-specific dag combine patterns for the following nodes:
1750   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1751   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1752   setTargetDAGCombine(ISD::BITCAST);
1753   setTargetDAGCombine(ISD::VSELECT);
1754   setTargetDAGCombine(ISD::SELECT);
1755   setTargetDAGCombine(ISD::SHL);
1756   setTargetDAGCombine(ISD::SRA);
1757   setTargetDAGCombine(ISD::SRL);
1758   setTargetDAGCombine(ISD::OR);
1759   setTargetDAGCombine(ISD::AND);
1760   setTargetDAGCombine(ISD::ADD);
1761   setTargetDAGCombine(ISD::FADD);
1762   setTargetDAGCombine(ISD::FSUB);
1763   setTargetDAGCombine(ISD::FMA);
1764   setTargetDAGCombine(ISD::SUB);
1765   setTargetDAGCombine(ISD::LOAD);
1766   setTargetDAGCombine(ISD::MLOAD);
1767   setTargetDAGCombine(ISD::STORE);
1768   setTargetDAGCombine(ISD::MSTORE);
1769   setTargetDAGCombine(ISD::ZERO_EXTEND);
1770   setTargetDAGCombine(ISD::ANY_EXTEND);
1771   setTargetDAGCombine(ISD::SIGN_EXTEND);
1772   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1773   setTargetDAGCombine(ISD::SINT_TO_FP);
1774   setTargetDAGCombine(ISD::UINT_TO_FP);
1775   setTargetDAGCombine(ISD::SETCC);
1776   setTargetDAGCombine(ISD::BUILD_VECTOR);
1777   setTargetDAGCombine(ISD::MUL);
1778   setTargetDAGCombine(ISD::XOR);
1779
1780   computeRegisterProperties(Subtarget->getRegisterInfo());
1781
1782   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1783   MaxStoresPerMemsetOptSize = 8;
1784   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1785   MaxStoresPerMemcpyOptSize = 4;
1786   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1787   MaxStoresPerMemmoveOptSize = 4;
1788   setPrefLoopAlignment(4); // 2^4 bytes.
1789
1790   // Predictable cmov don't hurt on atom because it's in-order.
1791   PredictableSelectIsExpensive = !Subtarget->isAtom();
1792   EnableExtLdPromotion = true;
1793   setPrefFunctionAlignment(4); // 2^4 bytes.
1794
1795   verifyIntrinsicTables();
1796 }
1797
1798 // This has so far only been implemented for 64-bit MachO.
1799 bool X86TargetLowering::useLoadStackGuardNode() const {
1800   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1801 }
1802
1803 TargetLoweringBase::LegalizeTypeAction
1804 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1805   if (ExperimentalVectorWideningLegalization &&
1806       VT.getVectorNumElements() != 1 &&
1807       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1808     return TypeWidenVector;
1809
1810   return TargetLoweringBase::getPreferredVectorAction(VT);
1811 }
1812
1813 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1814                                           EVT VT) const {
1815   if (!VT.isVector())
1816     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1817
1818   const unsigned NumElts = VT.getVectorNumElements();
1819   const EVT EltVT = VT.getVectorElementType();
1820   if (VT.is512BitVector()) {
1821     if (Subtarget->hasAVX512())
1822       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1823           EltVT == MVT::f32 || EltVT == MVT::f64)
1824         switch(NumElts) {
1825         case  8: return MVT::v8i1;
1826         case 16: return MVT::v16i1;
1827       }
1828     if (Subtarget->hasBWI())
1829       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1830         switch(NumElts) {
1831         case 32: return MVT::v32i1;
1832         case 64: return MVT::v64i1;
1833       }
1834   }
1835
1836   if (VT.is256BitVector() || VT.is128BitVector()) {
1837     if (Subtarget->hasVLX())
1838       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1839           EltVT == MVT::f32 || EltVT == MVT::f64)
1840         switch(NumElts) {
1841         case 2: return MVT::v2i1;
1842         case 4: return MVT::v4i1;
1843         case 8: return MVT::v8i1;
1844       }
1845     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1846       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1847         switch(NumElts) {
1848         case  8: return MVT::v8i1;
1849         case 16: return MVT::v16i1;
1850         case 32: return MVT::v32i1;
1851       }
1852   }
1853
1854   return VT.changeVectorElementTypeToInteger();
1855 }
1856
1857 /// Helper for getByValTypeAlignment to determine
1858 /// the desired ByVal argument alignment.
1859 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1860   if (MaxAlign == 16)
1861     return;
1862   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1863     if (VTy->getBitWidth() == 128)
1864       MaxAlign = 16;
1865   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1866     unsigned EltAlign = 0;
1867     getMaxByValAlign(ATy->getElementType(), EltAlign);
1868     if (EltAlign > MaxAlign)
1869       MaxAlign = EltAlign;
1870   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1871     for (auto *EltTy : STy->elements()) {
1872       unsigned EltAlign = 0;
1873       getMaxByValAlign(EltTy, EltAlign);
1874       if (EltAlign > MaxAlign)
1875         MaxAlign = EltAlign;
1876       if (MaxAlign == 16)
1877         break;
1878     }
1879   }
1880 }
1881
1882 /// Return the desired alignment for ByVal aggregate
1883 /// function arguments in the caller parameter area. For X86, aggregates
1884 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1885 /// are at 4-byte boundaries.
1886 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1887                                                   const DataLayout &DL) const {
1888   if (Subtarget->is64Bit()) {
1889     // Max of 8 and alignment of type.
1890     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1891     if (TyAlign > 8)
1892       return TyAlign;
1893     return 8;
1894   }
1895
1896   unsigned Align = 4;
1897   if (Subtarget->hasSSE1())
1898     getMaxByValAlign(Ty, Align);
1899   return Align;
1900 }
1901
1902 /// Returns the target specific optimal type for load
1903 /// and store operations as a result of memset, memcpy, and memmove
1904 /// lowering. If DstAlign is zero that means it's safe to destination
1905 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1906 /// means there isn't a need to check it against alignment requirement,
1907 /// probably because the source does not need to be loaded. If 'IsMemset' is
1908 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1909 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1910 /// source is constant so it does not need to be loaded.
1911 /// It returns EVT::Other if the type should be determined using generic
1912 /// target-independent logic.
1913 EVT
1914 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1915                                        unsigned DstAlign, unsigned SrcAlign,
1916                                        bool IsMemset, bool ZeroMemset,
1917                                        bool MemcpyStrSrc,
1918                                        MachineFunction &MF) const {
1919   const Function *F = MF.getFunction();
1920   if ((!IsMemset || ZeroMemset) &&
1921       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1922     if (Size >= 16 &&
1923         (!Subtarget->isUnalignedMem16Slow() ||
1924          ((DstAlign == 0 || DstAlign >= 16) &&
1925           (SrcAlign == 0 || SrcAlign >= 16)))) {
1926       if (Size >= 32) {
1927         // FIXME: Check if unaligned 32-byte accesses are slow.
1928         if (Subtarget->hasInt256())
1929           return MVT::v8i32;
1930         if (Subtarget->hasFp256())
1931           return MVT::v8f32;
1932       }
1933       if (Subtarget->hasSSE2())
1934         return MVT::v4i32;
1935       if (Subtarget->hasSSE1())
1936         return MVT::v4f32;
1937     } else if (!MemcpyStrSrc && Size >= 8 &&
1938                !Subtarget->is64Bit() &&
1939                Subtarget->hasSSE2()) {
1940       // Do not use f64 to lower memcpy if source is string constant. It's
1941       // better to use i32 to avoid the loads.
1942       return MVT::f64;
1943     }
1944   }
1945   // This is a compromise. If we reach here, unaligned accesses may be slow on
1946   // this target. However, creating smaller, aligned accesses could be even
1947   // slower and would certainly be a lot more code.
1948   if (Subtarget->is64Bit() && Size >= 8)
1949     return MVT::i64;
1950   return MVT::i32;
1951 }
1952
1953 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1954   if (VT == MVT::f32)
1955     return X86ScalarSSEf32;
1956   else if (VT == MVT::f64)
1957     return X86ScalarSSEf64;
1958   return true;
1959 }
1960
1961 bool
1962 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1963                                                   unsigned,
1964                                                   unsigned,
1965                                                   bool *Fast) const {
1966   if (Fast) {
1967     switch (VT.getSizeInBits()) {
1968     default:
1969       // 8-byte and under are always assumed to be fast.
1970       *Fast = true;
1971       break;
1972     case 128:
1973       *Fast = !Subtarget->isUnalignedMem16Slow();
1974       break;
1975     case 256:
1976       *Fast = !Subtarget->isUnalignedMem32Slow();
1977       break;
1978     // TODO: What about AVX-512 (512-bit) accesses?
1979     }
1980   }
1981   // Misaligned accesses of any size are always allowed.
1982   return true;
1983 }
1984
1985 /// Return the entry encoding for a jump table in the
1986 /// current function.  The returned value is a member of the
1987 /// MachineJumpTableInfo::JTEntryKind enum.
1988 unsigned X86TargetLowering::getJumpTableEncoding() const {
1989   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1990   // symbol.
1991   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1992       Subtarget->isPICStyleGOT())
1993     return MachineJumpTableInfo::EK_Custom32;
1994
1995   // Otherwise, use the normal jump table encoding heuristics.
1996   return TargetLowering::getJumpTableEncoding();
1997 }
1998
1999 bool X86TargetLowering::useSoftFloat() const {
2000   return Subtarget->useSoftFloat();
2001 }
2002
2003 const MCExpr *
2004 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2005                                              const MachineBasicBlock *MBB,
2006                                              unsigned uid,MCContext &Ctx) const{
2007   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2008          Subtarget->isPICStyleGOT());
2009   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2010   // entries.
2011   return MCSymbolRefExpr::create(MBB->getSymbol(),
2012                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2013 }
2014
2015 /// Returns relocation base for the given PIC jumptable.
2016 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2017                                                     SelectionDAG &DAG) const {
2018   if (!Subtarget->is64Bit())
2019     // This doesn't have SDLoc associated with it, but is not really the
2020     // same as a Register.
2021     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2022                        getPointerTy(DAG.getDataLayout()));
2023   return Table;
2024 }
2025
2026 /// This returns the relocation base for the given PIC jumptable,
2027 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2028 const MCExpr *X86TargetLowering::
2029 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2030                              MCContext &Ctx) const {
2031   // X86-64 uses RIP relative addressing based on the jump table label.
2032   if (Subtarget->isPICStyleRIPRel())
2033     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2034
2035   // Otherwise, the reference is relative to the PIC base.
2036   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2037 }
2038
2039 std::pair<const TargetRegisterClass *, uint8_t>
2040 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2041                                            MVT VT) const {
2042   const TargetRegisterClass *RRC = nullptr;
2043   uint8_t Cost = 1;
2044   switch (VT.SimpleTy) {
2045   default:
2046     return TargetLowering::findRepresentativeClass(TRI, VT);
2047   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2048     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2049     break;
2050   case MVT::x86mmx:
2051     RRC = &X86::VR64RegClass;
2052     break;
2053   case MVT::f32: case MVT::f64:
2054   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2055   case MVT::v4f32: case MVT::v2f64:
2056   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2057   case MVT::v4f64:
2058     RRC = &X86::VR128RegClass;
2059     break;
2060   }
2061   return std::make_pair(RRC, Cost);
2062 }
2063
2064 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2065                                                unsigned &Offset) const {
2066   if (!Subtarget->isTargetLinux())
2067     return false;
2068
2069   if (Subtarget->is64Bit()) {
2070     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2071     Offset = 0x28;
2072     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2073       AddressSpace = 256;
2074     else
2075       AddressSpace = 257;
2076   } else {
2077     // %gs:0x14 on i386
2078     Offset = 0x14;
2079     AddressSpace = 256;
2080   }
2081   return true;
2082 }
2083
2084 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2085                                             unsigned DestAS) const {
2086   assert(SrcAS != DestAS && "Expected different address spaces!");
2087
2088   return SrcAS < 256 && DestAS < 256;
2089 }
2090
2091 //===----------------------------------------------------------------------===//
2092 //               Return Value Calling Convention Implementation
2093 //===----------------------------------------------------------------------===//
2094
2095 #include "X86GenCallingConv.inc"
2096
2097 bool
2098 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2099                                   MachineFunction &MF, bool isVarArg,
2100                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2101                         LLVMContext &Context) const {
2102   SmallVector<CCValAssign, 16> RVLocs;
2103   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2104   return CCInfo.CheckReturn(Outs, RetCC_X86);
2105 }
2106
2107 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2108   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2109   return ScratchRegs;
2110 }
2111
2112 SDValue
2113 X86TargetLowering::LowerReturn(SDValue Chain,
2114                                CallingConv::ID CallConv, bool isVarArg,
2115                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2116                                const SmallVectorImpl<SDValue> &OutVals,
2117                                SDLoc dl, SelectionDAG &DAG) const {
2118   MachineFunction &MF = DAG.getMachineFunction();
2119   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2120
2121   SmallVector<CCValAssign, 16> RVLocs;
2122   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2123   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2124
2125   SDValue Flag;
2126   SmallVector<SDValue, 6> RetOps;
2127   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2128   // Operand #1 = Bytes To Pop
2129   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2130                    MVT::i16));
2131
2132   // Copy the result values into the output registers.
2133   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2134     CCValAssign &VA = RVLocs[i];
2135     assert(VA.isRegLoc() && "Can only return in registers!");
2136     SDValue ValToCopy = OutVals[i];
2137     EVT ValVT = ValToCopy.getValueType();
2138
2139     // Promote values to the appropriate types.
2140     if (VA.getLocInfo() == CCValAssign::SExt)
2141       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2142     else if (VA.getLocInfo() == CCValAssign::ZExt)
2143       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2144     else if (VA.getLocInfo() == CCValAssign::AExt) {
2145       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2146         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2147       else
2148         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2149     }
2150     else if (VA.getLocInfo() == CCValAssign::BCvt)
2151       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2152
2153     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2154            "Unexpected FP-extend for return value.");
2155
2156     // If this is x86-64, and we disabled SSE, we can't return FP values,
2157     // or SSE or MMX vectors.
2158     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2159          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2160           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2161       report_fatal_error("SSE register return with SSE disabled");
2162     }
2163     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2164     // llvm-gcc has never done it right and no one has noticed, so this
2165     // should be OK for now.
2166     if (ValVT == MVT::f64 &&
2167         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2168       report_fatal_error("SSE2 register return with SSE2 disabled");
2169
2170     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2171     // the RET instruction and handled by the FP Stackifier.
2172     if (VA.getLocReg() == X86::FP0 ||
2173         VA.getLocReg() == X86::FP1) {
2174       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2175       // change the value to the FP stack register class.
2176       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2177         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2178       RetOps.push_back(ValToCopy);
2179       // Don't emit a copytoreg.
2180       continue;
2181     }
2182
2183     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2184     // which is returned in RAX / RDX.
2185     if (Subtarget->is64Bit()) {
2186       if (ValVT == MVT::x86mmx) {
2187         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2188           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2189           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2190                                   ValToCopy);
2191           // If we don't have SSE2 available, convert to v4f32 so the generated
2192           // register is legal.
2193           if (!Subtarget->hasSSE2())
2194             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2195         }
2196       }
2197     }
2198
2199     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2200     Flag = Chain.getValue(1);
2201     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2202   }
2203
2204   // All x86 ABIs require that for returning structs by value we copy
2205   // the sret argument into %rax/%eax (depending on ABI) for the return.
2206   // We saved the argument into a virtual register in the entry block,
2207   // so now we copy the value out and into %rax/%eax.
2208   //
2209   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2210   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2211   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2212   // either case FuncInfo->setSRetReturnReg() will have been called.
2213   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2214     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2215                                      getPointerTy(MF.getDataLayout()));
2216
2217     unsigned RetValReg
2218         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2219           X86::RAX : X86::EAX;
2220     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2221     Flag = Chain.getValue(1);
2222
2223     // RAX/EAX now acts like a return value.
2224     RetOps.push_back(
2225         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2226   }
2227
2228   RetOps[0] = Chain;  // Update chain.
2229
2230   // Add the flag if we have it.
2231   if (Flag.getNode())
2232     RetOps.push_back(Flag);
2233
2234   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2235 }
2236
2237 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2238   if (N->getNumValues() != 1)
2239     return false;
2240   if (!N->hasNUsesOfValue(1, 0))
2241     return false;
2242
2243   SDValue TCChain = Chain;
2244   SDNode *Copy = *N->use_begin();
2245   if (Copy->getOpcode() == ISD::CopyToReg) {
2246     // If the copy has a glue operand, we conservatively assume it isn't safe to
2247     // perform a tail call.
2248     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2249       return false;
2250     TCChain = Copy->getOperand(0);
2251   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2252     return false;
2253
2254   bool HasRet = false;
2255   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2256        UI != UE; ++UI) {
2257     if (UI->getOpcode() != X86ISD::RET_FLAG)
2258       return false;
2259     // If we are returning more than one value, we can definitely
2260     // not make a tail call see PR19530
2261     if (UI->getNumOperands() > 4)
2262       return false;
2263     if (UI->getNumOperands() == 4 &&
2264         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2265       return false;
2266     HasRet = true;
2267   }
2268
2269   if (!HasRet)
2270     return false;
2271
2272   Chain = TCChain;
2273   return true;
2274 }
2275
2276 EVT
2277 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2278                                             ISD::NodeType ExtendKind) const {
2279   MVT ReturnMVT;
2280   // TODO: Is this also valid on 32-bit?
2281   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2282     ReturnMVT = MVT::i8;
2283   else
2284     ReturnMVT = MVT::i32;
2285
2286   EVT MinVT = getRegisterType(Context, ReturnMVT);
2287   return VT.bitsLT(MinVT) ? MinVT : VT;
2288 }
2289
2290 /// Lower the result values of a call into the
2291 /// appropriate copies out of appropriate physical registers.
2292 ///
2293 SDValue
2294 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2295                                    CallingConv::ID CallConv, bool isVarArg,
2296                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2297                                    SDLoc dl, SelectionDAG &DAG,
2298                                    SmallVectorImpl<SDValue> &InVals) const {
2299
2300   // Assign locations to each value returned by this call.
2301   SmallVector<CCValAssign, 16> RVLocs;
2302   bool Is64Bit = Subtarget->is64Bit();
2303   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2304                  *DAG.getContext());
2305   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2306
2307   // Copy all of the result registers out of their specified physreg.
2308   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2309     CCValAssign &VA = RVLocs[i];
2310     EVT CopyVT = VA.getLocVT();
2311
2312     // If this is x86-64, and we disabled SSE, we can't return FP values
2313     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2314         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2315       report_fatal_error("SSE register return with SSE disabled");
2316     }
2317
2318     // If we prefer to use the value in xmm registers, copy it out as f80 and
2319     // use a truncate to move it from fp stack reg to xmm reg.
2320     bool RoundAfterCopy = false;
2321     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2322         isScalarFPTypeInSSEReg(VA.getValVT())) {
2323       CopyVT = MVT::f80;
2324       RoundAfterCopy = (CopyVT != VA.getLocVT());
2325     }
2326
2327     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2328                                CopyVT, InFlag).getValue(1);
2329     SDValue Val = Chain.getValue(0);
2330
2331     if (RoundAfterCopy)
2332       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2333                         // This truncation won't change the value.
2334                         DAG.getIntPtrConstant(1, dl));
2335
2336     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2337       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2338
2339     InFlag = Chain.getValue(2);
2340     InVals.push_back(Val);
2341   }
2342
2343   return Chain;
2344 }
2345
2346 //===----------------------------------------------------------------------===//
2347 //                C & StdCall & Fast Calling Convention implementation
2348 //===----------------------------------------------------------------------===//
2349 //  StdCall calling convention seems to be standard for many Windows' API
2350 //  routines and around. It differs from C calling convention just a little:
2351 //  callee should clean up the stack, not caller. Symbols should be also
2352 //  decorated in some fancy way :) It doesn't support any vector arguments.
2353 //  For info on fast calling convention see Fast Calling Convention (tail call)
2354 //  implementation LowerX86_32FastCCCallTo.
2355
2356 /// CallIsStructReturn - Determines whether a call uses struct return
2357 /// semantics.
2358 enum StructReturnType {
2359   NotStructReturn,
2360   RegStructReturn,
2361   StackStructReturn
2362 };
2363 static StructReturnType
2364 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2365   if (Outs.empty())
2366     return NotStructReturn;
2367
2368   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2369   if (!Flags.isSRet())
2370     return NotStructReturn;
2371   if (Flags.isInReg())
2372     return RegStructReturn;
2373   return StackStructReturn;
2374 }
2375
2376 /// Determines whether a function uses struct return semantics.
2377 static StructReturnType
2378 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2379   if (Ins.empty())
2380     return NotStructReturn;
2381
2382   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2383   if (!Flags.isSRet())
2384     return NotStructReturn;
2385   if (Flags.isInReg())
2386     return RegStructReturn;
2387   return StackStructReturn;
2388 }
2389
2390 /// Make a copy of an aggregate at address specified by "Src" to address
2391 /// "Dst" with size and alignment information specified by the specific
2392 /// parameter attribute. The copy will be passed as a byval function parameter.
2393 static SDValue
2394 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2395                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2396                           SDLoc dl) {
2397   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2398
2399   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2400                        /*isVolatile*/false, /*AlwaysInline=*/true,
2401                        /*isTailCall*/false,
2402                        MachinePointerInfo(), MachinePointerInfo());
2403 }
2404
2405 /// Return true if the calling convention is one that
2406 /// supports tail call optimization.
2407 static bool IsTailCallConvention(CallingConv::ID CC) {
2408   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2409           CC == CallingConv::HiPE);
2410 }
2411
2412 /// \brief Return true if the calling convention is a C calling convention.
2413 static bool IsCCallConvention(CallingConv::ID CC) {
2414   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2415           CC == CallingConv::X86_64_SysV);
2416 }
2417
2418 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2419   auto Attr =
2420       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2421   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2422     return false;
2423
2424   CallSite CS(CI);
2425   CallingConv::ID CalleeCC = CS.getCallingConv();
2426   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2427     return false;
2428
2429   return true;
2430 }
2431
2432 /// Return true if the function is being made into
2433 /// a tailcall target by changing its ABI.
2434 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2435                                    bool GuaranteedTailCallOpt) {
2436   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2437 }
2438
2439 SDValue
2440 X86TargetLowering::LowerMemArgument(SDValue Chain,
2441                                     CallingConv::ID CallConv,
2442                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2443                                     SDLoc dl, SelectionDAG &DAG,
2444                                     const CCValAssign &VA,
2445                                     MachineFrameInfo *MFI,
2446                                     unsigned i) const {
2447   // Create the nodes corresponding to a load from this parameter slot.
2448   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2449   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2450       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2451   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2452   EVT ValVT;
2453
2454   // If value is passed by pointer we have address passed instead of the value
2455   // itself.
2456   bool ExtendedInMem = VA.isExtInLoc() &&
2457     VA.getValVT().getScalarType() == MVT::i1;
2458
2459   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2460     ValVT = VA.getLocVT();
2461   else
2462     ValVT = VA.getValVT();
2463
2464   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2465   // changed with more analysis.
2466   // In case of tail call optimization mark all arguments mutable. Since they
2467   // could be overwritten by lowering of arguments in case of a tail call.
2468   if (Flags.isByVal()) {
2469     unsigned Bytes = Flags.getByValSize();
2470     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2471     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2472     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2473   } else {
2474     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2475                                     VA.getLocMemOffset(), isImmutable);
2476     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2477     SDValue Val = DAG.getLoad(
2478         ValVT, dl, Chain, FIN,
2479         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2480         false, false, 0);
2481     return ExtendedInMem ?
2482       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2483   }
2484 }
2485
2486 // FIXME: Get this from tablegen.
2487 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2488                                                 const X86Subtarget *Subtarget) {
2489   assert(Subtarget->is64Bit());
2490
2491   if (Subtarget->isCallingConvWin64(CallConv)) {
2492     static const MCPhysReg GPR64ArgRegsWin64[] = {
2493       X86::RCX, X86::RDX, X86::R8,  X86::R9
2494     };
2495     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2496   }
2497
2498   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2499     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2500   };
2501   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2502 }
2503
2504 // FIXME: Get this from tablegen.
2505 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2506                                                 CallingConv::ID CallConv,
2507                                                 const X86Subtarget *Subtarget) {
2508   assert(Subtarget->is64Bit());
2509   if (Subtarget->isCallingConvWin64(CallConv)) {
2510     // The XMM registers which might contain var arg parameters are shadowed
2511     // in their paired GPR.  So we only need to save the GPR to their home
2512     // slots.
2513     // TODO: __vectorcall will change this.
2514     return None;
2515   }
2516
2517   const Function *Fn = MF.getFunction();
2518   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2519   bool isSoftFloat = Subtarget->useSoftFloat();
2520   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2521          "SSE register cannot be used when SSE is disabled!");
2522   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2523     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2524     // registers.
2525     return None;
2526
2527   static const MCPhysReg XMMArgRegs64Bit[] = {
2528     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2529     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2530   };
2531   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2532 }
2533
2534 SDValue
2535 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2536                                         CallingConv::ID CallConv,
2537                                         bool isVarArg,
2538                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2539                                         SDLoc dl,
2540                                         SelectionDAG &DAG,
2541                                         SmallVectorImpl<SDValue> &InVals)
2542                                           const {
2543   MachineFunction &MF = DAG.getMachineFunction();
2544   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2545   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2546
2547   const Function* Fn = MF.getFunction();
2548   if (Fn->hasExternalLinkage() &&
2549       Subtarget->isTargetCygMing() &&
2550       Fn->getName() == "main")
2551     FuncInfo->setForceFramePointer(true);
2552
2553   MachineFrameInfo *MFI = MF.getFrameInfo();
2554   bool Is64Bit = Subtarget->is64Bit();
2555   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2556
2557   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2558          "Var args not supported with calling convention fastcc, ghc or hipe");
2559
2560   // Assign locations to all of the incoming arguments.
2561   SmallVector<CCValAssign, 16> ArgLocs;
2562   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2563
2564   // Allocate shadow area for Win64
2565   if (IsWin64)
2566     CCInfo.AllocateStack(32, 8);
2567
2568   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2569
2570   unsigned LastVal = ~0U;
2571   SDValue ArgValue;
2572   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2573     CCValAssign &VA = ArgLocs[i];
2574     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2575     // places.
2576     assert(VA.getValNo() != LastVal &&
2577            "Don't support value assigned to multiple locs yet");
2578     (void)LastVal;
2579     LastVal = VA.getValNo();
2580
2581     if (VA.isRegLoc()) {
2582       EVT RegVT = VA.getLocVT();
2583       const TargetRegisterClass *RC;
2584       if (RegVT == MVT::i32)
2585         RC = &X86::GR32RegClass;
2586       else if (Is64Bit && RegVT == MVT::i64)
2587         RC = &X86::GR64RegClass;
2588       else if (RegVT == MVT::f32)
2589         RC = &X86::FR32RegClass;
2590       else if (RegVT == MVT::f64)
2591         RC = &X86::FR64RegClass;
2592       else if (RegVT.is512BitVector())
2593         RC = &X86::VR512RegClass;
2594       else if (RegVT.is256BitVector())
2595         RC = &X86::VR256RegClass;
2596       else if (RegVT.is128BitVector())
2597         RC = &X86::VR128RegClass;
2598       else if (RegVT == MVT::x86mmx)
2599         RC = &X86::VR64RegClass;
2600       else if (RegVT == MVT::i1)
2601         RC = &X86::VK1RegClass;
2602       else if (RegVT == MVT::v8i1)
2603         RC = &X86::VK8RegClass;
2604       else if (RegVT == MVT::v16i1)
2605         RC = &X86::VK16RegClass;
2606       else if (RegVT == MVT::v32i1)
2607         RC = &X86::VK32RegClass;
2608       else if (RegVT == MVT::v64i1)
2609         RC = &X86::VK64RegClass;
2610       else
2611         llvm_unreachable("Unknown argument type!");
2612
2613       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2614       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2615
2616       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2617       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2618       // right size.
2619       if (VA.getLocInfo() == CCValAssign::SExt)
2620         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2621                                DAG.getValueType(VA.getValVT()));
2622       else if (VA.getLocInfo() == CCValAssign::ZExt)
2623         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2624                                DAG.getValueType(VA.getValVT()));
2625       else if (VA.getLocInfo() == CCValAssign::BCvt)
2626         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2627
2628       if (VA.isExtInLoc()) {
2629         // Handle MMX values passed in XMM regs.
2630         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2631           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2632         else
2633           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2634       }
2635     } else {
2636       assert(VA.isMemLoc());
2637       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2638     }
2639
2640     // If value is passed via pointer - do a load.
2641     if (VA.getLocInfo() == CCValAssign::Indirect)
2642       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2643                              MachinePointerInfo(), false, false, false, 0);
2644
2645     InVals.push_back(ArgValue);
2646   }
2647
2648   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2649     // All x86 ABIs require that for returning structs by value we copy the
2650     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2651     // the argument into a virtual register so that we can access it from the
2652     // return points.
2653     if (Ins[i].Flags.isSRet()) {
2654       unsigned Reg = FuncInfo->getSRetReturnReg();
2655       if (!Reg) {
2656         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2657         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2658         FuncInfo->setSRetReturnReg(Reg);
2659       }
2660       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2661       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2662       break;
2663     }
2664   }
2665
2666   unsigned StackSize = CCInfo.getNextStackOffset();
2667   // Align stack specially for tail calls.
2668   if (FuncIsMadeTailCallSafe(CallConv,
2669                              MF.getTarget().Options.GuaranteedTailCallOpt))
2670     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2671
2672   // If the function takes variable number of arguments, make a frame index for
2673   // the start of the first vararg value... for expansion of llvm.va_start. We
2674   // can skip this if there are no va_start calls.
2675   if (MFI->hasVAStart() &&
2676       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2677                    CallConv != CallingConv::X86_ThisCall))) {
2678     FuncInfo->setVarArgsFrameIndex(
2679         MFI->CreateFixedObject(1, StackSize, true));
2680   }
2681
2682   MachineModuleInfo &MMI = MF.getMMI();
2683   const Function *WinEHParent = nullptr;
2684   if (MMI.hasWinEHFuncInfo(Fn))
2685     WinEHParent = MMI.getWinEHParent(Fn);
2686   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2687
2688   // Figure out if XMM registers are in use.
2689   assert(!(Subtarget->useSoftFloat() &&
2690            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2691          "SSE register cannot be used when SSE is disabled!");
2692
2693   // 64-bit calling conventions support varargs and register parameters, so we
2694   // have to do extra work to spill them in the prologue.
2695   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2696     // Find the first unallocated argument registers.
2697     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2698     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2699     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2700     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2701     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2702            "SSE register cannot be used when SSE is disabled!");
2703
2704     // Gather all the live in physical registers.
2705     SmallVector<SDValue, 6> LiveGPRs;
2706     SmallVector<SDValue, 8> LiveXMMRegs;
2707     SDValue ALVal;
2708     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2709       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2710       LiveGPRs.push_back(
2711           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2712     }
2713     if (!ArgXMMs.empty()) {
2714       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2715       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2716       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2717         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2718         LiveXMMRegs.push_back(
2719             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2720       }
2721     }
2722
2723     if (IsWin64) {
2724       // Get to the caller-allocated home save location.  Add 8 to account
2725       // for the return address.
2726       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2727       FuncInfo->setRegSaveFrameIndex(
2728           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2729       // Fixup to set vararg frame on shadow area (4 x i64).
2730       if (NumIntRegs < 4)
2731         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2732     } else {
2733       // For X86-64, if there are vararg parameters that are passed via
2734       // registers, then we must store them to their spots on the stack so
2735       // they may be loaded by deferencing the result of va_next.
2736       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2737       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2738       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2739           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2740     }
2741
2742     // Store the integer parameter registers.
2743     SmallVector<SDValue, 8> MemOps;
2744     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2745                                       getPointerTy(DAG.getDataLayout()));
2746     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2747     for (SDValue Val : LiveGPRs) {
2748       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2749                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2750       SDValue Store =
2751           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2752                        MachinePointerInfo::getFixedStack(
2753                            DAG.getMachineFunction(),
2754                            FuncInfo->getRegSaveFrameIndex(), Offset),
2755                        false, false, 0);
2756       MemOps.push_back(Store);
2757       Offset += 8;
2758     }
2759
2760     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2761       // Now store the XMM (fp + vector) parameter registers.
2762       SmallVector<SDValue, 12> SaveXMMOps;
2763       SaveXMMOps.push_back(Chain);
2764       SaveXMMOps.push_back(ALVal);
2765       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2766                              FuncInfo->getRegSaveFrameIndex(), dl));
2767       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2768                              FuncInfo->getVarArgsFPOffset(), dl));
2769       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2770                         LiveXMMRegs.end());
2771       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2772                                    MVT::Other, SaveXMMOps));
2773     }
2774
2775     if (!MemOps.empty())
2776       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2777   }
2778
2779   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2780     // Find the largest legal vector type.
2781     MVT VecVT = MVT::Other;
2782     // FIXME: Only some x86_32 calling conventions support AVX512.
2783     if (Subtarget->hasAVX512() &&
2784         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2785                      CallConv == CallingConv::Intel_OCL_BI)))
2786       VecVT = MVT::v16f32;
2787     else if (Subtarget->hasAVX())
2788       VecVT = MVT::v8f32;
2789     else if (Subtarget->hasSSE2())
2790       VecVT = MVT::v4f32;
2791
2792     // We forward some GPRs and some vector types.
2793     SmallVector<MVT, 2> RegParmTypes;
2794     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2795     RegParmTypes.push_back(IntVT);
2796     if (VecVT != MVT::Other)
2797       RegParmTypes.push_back(VecVT);
2798
2799     // Compute the set of forwarded registers. The rest are scratch.
2800     SmallVectorImpl<ForwardedRegister> &Forwards =
2801         FuncInfo->getForwardedMustTailRegParms();
2802     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2803
2804     // Conservatively forward AL on x86_64, since it might be used for varargs.
2805     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2806       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2807       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2808     }
2809
2810     // Copy all forwards from physical to virtual registers.
2811     for (ForwardedRegister &F : Forwards) {
2812       // FIXME: Can we use a less constrained schedule?
2813       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2814       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2815       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2816     }
2817   }
2818
2819   // Some CCs need callee pop.
2820   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2821                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2822     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2823   } else {
2824     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2825     // If this is an sret function, the return should pop the hidden pointer.
2826     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2827         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2828         argsAreStructReturn(Ins) == StackStructReturn)
2829       FuncInfo->setBytesToPopOnReturn(4);
2830   }
2831
2832   if (!Is64Bit) {
2833     // RegSaveFrameIndex is X86-64 only.
2834     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2835     if (CallConv == CallingConv::X86_FastCall ||
2836         CallConv == CallingConv::X86_ThisCall)
2837       // fastcc functions can't have varargs.
2838       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2839   }
2840
2841   FuncInfo->setArgumentStackSize(StackSize);
2842
2843   if (IsWinEHParent) {
2844     if (Is64Bit) {
2845       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2846       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2847       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2848       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2849       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2850                            MachinePointerInfo::getFixedStack(
2851                                DAG.getMachineFunction(), UnwindHelpFI),
2852                            /*isVolatile=*/true,
2853                            /*isNonTemporal=*/false, /*Alignment=*/0);
2854     } else {
2855       // Functions using Win32 EH are considered to have opaque SP adjustments
2856       // to force local variables to be addressed from the frame or base
2857       // pointers.
2858       MFI->setHasOpaqueSPAdjustment(true);
2859     }
2860   }
2861
2862   return Chain;
2863 }
2864
2865 SDValue
2866 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2867                                     SDValue StackPtr, SDValue Arg,
2868                                     SDLoc dl, SelectionDAG &DAG,
2869                                     const CCValAssign &VA,
2870                                     ISD::ArgFlagsTy Flags) const {
2871   unsigned LocMemOffset = VA.getLocMemOffset();
2872   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2873   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2874                        StackPtr, PtrOff);
2875   if (Flags.isByVal())
2876     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2877
2878   return DAG.getStore(
2879       Chain, dl, Arg, PtrOff,
2880       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2881       false, false, 0);
2882 }
2883
2884 /// Emit a load of return address if tail call
2885 /// optimization is performed and it is required.
2886 SDValue
2887 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2888                                            SDValue &OutRetAddr, SDValue Chain,
2889                                            bool IsTailCall, bool Is64Bit,
2890                                            int FPDiff, SDLoc dl) const {
2891   // Adjust the Return address stack slot.
2892   EVT VT = getPointerTy(DAG.getDataLayout());
2893   OutRetAddr = getReturnAddressFrameIndex(DAG);
2894
2895   // Load the "old" Return address.
2896   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2897                            false, false, false, 0);
2898   return SDValue(OutRetAddr.getNode(), 1);
2899 }
2900
2901 /// Emit a store of the return address if tail call
2902 /// optimization is performed and it is required (FPDiff!=0).
2903 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2904                                         SDValue Chain, SDValue RetAddrFrIdx,
2905                                         EVT PtrVT, unsigned SlotSize,
2906                                         int FPDiff, SDLoc dl) {
2907   // Store the return address to the appropriate stack slot.
2908   if (!FPDiff) return Chain;
2909   // Calculate the new stack slot for the return address.
2910   int NewReturnAddrFI =
2911     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2912                                          false);
2913   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2914   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2915                        MachinePointerInfo::getFixedStack(
2916                            DAG.getMachineFunction(), NewReturnAddrFI),
2917                        false, false, 0);
2918   return Chain;
2919 }
2920
2921 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2922 /// operation of specified width.
2923 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2924                        SDValue V2) {
2925   unsigned NumElems = VT.getVectorNumElements();
2926   SmallVector<int, 8> Mask;
2927   Mask.push_back(NumElems);
2928   for (unsigned i = 1; i != NumElems; ++i)
2929     Mask.push_back(i);
2930   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2931 }
2932
2933 SDValue
2934 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2935                              SmallVectorImpl<SDValue> &InVals) const {
2936   SelectionDAG &DAG                     = CLI.DAG;
2937   SDLoc &dl                             = CLI.DL;
2938   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2939   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2940   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2941   SDValue Chain                         = CLI.Chain;
2942   SDValue Callee                        = CLI.Callee;
2943   CallingConv::ID CallConv              = CLI.CallConv;
2944   bool &isTailCall                      = CLI.IsTailCall;
2945   bool isVarArg                         = CLI.IsVarArg;
2946
2947   MachineFunction &MF = DAG.getMachineFunction();
2948   bool Is64Bit        = Subtarget->is64Bit();
2949   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2950   StructReturnType SR = callIsStructReturn(Outs);
2951   bool IsSibcall      = false;
2952   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2953   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2954
2955   if (Attr.getValueAsString() == "true")
2956     isTailCall = false;
2957
2958   if (Subtarget->isPICStyleGOT() &&
2959       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2960     // If we are using a GOT, disable tail calls to external symbols with
2961     // default visibility. Tail calling such a symbol requires using a GOT
2962     // relocation, which forces early binding of the symbol. This breaks code
2963     // that require lazy function symbol resolution. Using musttail or
2964     // GuaranteedTailCallOpt will override this.
2965     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2966     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2967                G->getGlobal()->hasDefaultVisibility()))
2968       isTailCall = false;
2969   }
2970
2971   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2972   if (IsMustTail) {
2973     // Force this to be a tail call.  The verifier rules are enough to ensure
2974     // that we can lower this successfully without moving the return address
2975     // around.
2976     isTailCall = true;
2977   } else if (isTailCall) {
2978     // Check if it's really possible to do a tail call.
2979     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2980                     isVarArg, SR != NotStructReturn,
2981                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2982                     Outs, OutVals, Ins, DAG);
2983
2984     // Sibcalls are automatically detected tailcalls which do not require
2985     // ABI changes.
2986     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2987       IsSibcall = true;
2988
2989     if (isTailCall)
2990       ++NumTailCalls;
2991   }
2992
2993   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2994          "Var args not supported with calling convention fastcc, ghc or hipe");
2995
2996   // Analyze operands of the call, assigning locations to each operand.
2997   SmallVector<CCValAssign, 16> ArgLocs;
2998   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2999
3000   // Allocate shadow area for Win64
3001   if (IsWin64)
3002     CCInfo.AllocateStack(32, 8);
3003
3004   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3005
3006   // Get a count of how many bytes are to be pushed on the stack.
3007   unsigned NumBytes = CCInfo.getNextStackOffset();
3008   if (IsSibcall)
3009     // This is a sibcall. The memory operands are available in caller's
3010     // own caller's stack.
3011     NumBytes = 0;
3012   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3013            IsTailCallConvention(CallConv))
3014     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3015
3016   int FPDiff = 0;
3017   if (isTailCall && !IsSibcall && !IsMustTail) {
3018     // Lower arguments at fp - stackoffset + fpdiff.
3019     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3020
3021     FPDiff = NumBytesCallerPushed - NumBytes;
3022
3023     // Set the delta of movement of the returnaddr stackslot.
3024     // But only set if delta is greater than previous delta.
3025     if (FPDiff < X86Info->getTCReturnAddrDelta())
3026       X86Info->setTCReturnAddrDelta(FPDiff);
3027   }
3028
3029   unsigned NumBytesToPush = NumBytes;
3030   unsigned NumBytesToPop = NumBytes;
3031
3032   // If we have an inalloca argument, all stack space has already been allocated
3033   // for us and be right at the top of the stack.  We don't support multiple
3034   // arguments passed in memory when using inalloca.
3035   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3036     NumBytesToPush = 0;
3037     if (!ArgLocs.back().isMemLoc())
3038       report_fatal_error("cannot use inalloca attribute on a register "
3039                          "parameter");
3040     if (ArgLocs.back().getLocMemOffset() != 0)
3041       report_fatal_error("any parameter with the inalloca attribute must be "
3042                          "the only memory argument");
3043   }
3044
3045   if (!IsSibcall)
3046     Chain = DAG.getCALLSEQ_START(
3047         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3048
3049   SDValue RetAddrFrIdx;
3050   // Load return address for tail calls.
3051   if (isTailCall && FPDiff)
3052     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3053                                     Is64Bit, FPDiff, dl);
3054
3055   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3056   SmallVector<SDValue, 8> MemOpChains;
3057   SDValue StackPtr;
3058
3059   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3060   // of tail call optimization arguments are handle later.
3061   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3062   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3063     // Skip inalloca arguments, they have already been written.
3064     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3065     if (Flags.isInAlloca())
3066       continue;
3067
3068     CCValAssign &VA = ArgLocs[i];
3069     EVT RegVT = VA.getLocVT();
3070     SDValue Arg = OutVals[i];
3071     bool isByVal = Flags.isByVal();
3072
3073     // Promote the value if needed.
3074     switch (VA.getLocInfo()) {
3075     default: llvm_unreachable("Unknown loc info!");
3076     case CCValAssign::Full: break;
3077     case CCValAssign::SExt:
3078       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3079       break;
3080     case CCValAssign::ZExt:
3081       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3082       break;
3083     case CCValAssign::AExt:
3084       if (Arg.getValueType().isVector() &&
3085           Arg.getValueType().getScalarType() == MVT::i1)
3086         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3087       else if (RegVT.is128BitVector()) {
3088         // Special case: passing MMX values in XMM registers.
3089         Arg = DAG.getBitcast(MVT::i64, Arg);
3090         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3091         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3092       } else
3093         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3094       break;
3095     case CCValAssign::BCvt:
3096       Arg = DAG.getBitcast(RegVT, Arg);
3097       break;
3098     case CCValAssign::Indirect: {
3099       // Store the argument.
3100       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3101       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3102       Chain = DAG.getStore(
3103           Chain, dl, Arg, SpillSlot,
3104           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3105           false, false, 0);
3106       Arg = SpillSlot;
3107       break;
3108     }
3109     }
3110
3111     if (VA.isRegLoc()) {
3112       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3113       if (isVarArg && IsWin64) {
3114         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3115         // shadow reg if callee is a varargs function.
3116         unsigned ShadowReg = 0;
3117         switch (VA.getLocReg()) {
3118         case X86::XMM0: ShadowReg = X86::RCX; break;
3119         case X86::XMM1: ShadowReg = X86::RDX; break;
3120         case X86::XMM2: ShadowReg = X86::R8; break;
3121         case X86::XMM3: ShadowReg = X86::R9; break;
3122         }
3123         if (ShadowReg)
3124           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3125       }
3126     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3127       assert(VA.isMemLoc());
3128       if (!StackPtr.getNode())
3129         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3130                                       getPointerTy(DAG.getDataLayout()));
3131       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3132                                              dl, DAG, VA, Flags));
3133     }
3134   }
3135
3136   if (!MemOpChains.empty())
3137     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3138
3139   if (Subtarget->isPICStyleGOT()) {
3140     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3141     // GOT pointer.
3142     if (!isTailCall) {
3143       RegsToPass.push_back(std::make_pair(
3144           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3145                                           getPointerTy(DAG.getDataLayout()))));
3146     } else {
3147       // If we are tail calling and generating PIC/GOT style code load the
3148       // address of the callee into ECX. The value in ecx is used as target of
3149       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3150       // for tail calls on PIC/GOT architectures. Normally we would just put the
3151       // address of GOT into ebx and then call target@PLT. But for tail calls
3152       // ebx would be restored (since ebx is callee saved) before jumping to the
3153       // target@PLT.
3154
3155       // Note: The actual moving to ECX is done further down.
3156       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3157       if (G && !G->getGlobal()->hasLocalLinkage() &&
3158           G->getGlobal()->hasDefaultVisibility())
3159         Callee = LowerGlobalAddress(Callee, DAG);
3160       else if (isa<ExternalSymbolSDNode>(Callee))
3161         Callee = LowerExternalSymbol(Callee, DAG);
3162     }
3163   }
3164
3165   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3166     // From AMD64 ABI document:
3167     // For calls that may call functions that use varargs or stdargs
3168     // (prototype-less calls or calls to functions containing ellipsis (...) in
3169     // the declaration) %al is used as hidden argument to specify the number
3170     // of SSE registers used. The contents of %al do not need to match exactly
3171     // the number of registers, but must be an ubound on the number of SSE
3172     // registers used and is in the range 0 - 8 inclusive.
3173
3174     // Count the number of XMM registers allocated.
3175     static const MCPhysReg XMMArgRegs[] = {
3176       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3177       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3178     };
3179     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3180     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3181            && "SSE registers cannot be used when SSE is disabled");
3182
3183     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3184                                         DAG.getConstant(NumXMMRegs, dl,
3185                                                         MVT::i8)));
3186   }
3187
3188   if (isVarArg && IsMustTail) {
3189     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3190     for (const auto &F : Forwards) {
3191       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3192       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3193     }
3194   }
3195
3196   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3197   // don't need this because the eligibility check rejects calls that require
3198   // shuffling arguments passed in memory.
3199   if (!IsSibcall && isTailCall) {
3200     // Force all the incoming stack arguments to be loaded from the stack
3201     // before any new outgoing arguments are stored to the stack, because the
3202     // outgoing stack slots may alias the incoming argument stack slots, and
3203     // the alias isn't otherwise explicit. This is slightly more conservative
3204     // than necessary, because it means that each store effectively depends
3205     // on every argument instead of just those arguments it would clobber.
3206     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3207
3208     SmallVector<SDValue, 8> MemOpChains2;
3209     SDValue FIN;
3210     int FI = 0;
3211     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3212       CCValAssign &VA = ArgLocs[i];
3213       if (VA.isRegLoc())
3214         continue;
3215       assert(VA.isMemLoc());
3216       SDValue Arg = OutVals[i];
3217       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3218       // Skip inalloca arguments.  They don't require any work.
3219       if (Flags.isInAlloca())
3220         continue;
3221       // Create frame index.
3222       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3223       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3224       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3225       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3226
3227       if (Flags.isByVal()) {
3228         // Copy relative to framepointer.
3229         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3230         if (!StackPtr.getNode())
3231           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3232                                         getPointerTy(DAG.getDataLayout()));
3233         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3234                              StackPtr, Source);
3235
3236         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3237                                                          ArgChain,
3238                                                          Flags, DAG, dl));
3239       } else {
3240         // Store relative to framepointer.
3241         MemOpChains2.push_back(DAG.getStore(
3242             ArgChain, dl, Arg, FIN,
3243             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3244             false, false, 0));
3245       }
3246     }
3247
3248     if (!MemOpChains2.empty())
3249       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3250
3251     // Store the return address to the appropriate stack slot.
3252     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3253                                      getPointerTy(DAG.getDataLayout()),
3254                                      RegInfo->getSlotSize(), FPDiff, dl);
3255   }
3256
3257   // Build a sequence of copy-to-reg nodes chained together with token chain
3258   // and flag operands which copy the outgoing args into registers.
3259   SDValue InFlag;
3260   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3261     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3262                              RegsToPass[i].second, InFlag);
3263     InFlag = Chain.getValue(1);
3264   }
3265
3266   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3267     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3268     // In the 64-bit large code model, we have to make all calls
3269     // through a register, since the call instruction's 32-bit
3270     // pc-relative offset may not be large enough to hold the whole
3271     // address.
3272   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3273     // If the callee is a GlobalAddress node (quite common, every direct call
3274     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3275     // it.
3276     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3277
3278     // We should use extra load for direct calls to dllimported functions in
3279     // non-JIT mode.
3280     const GlobalValue *GV = G->getGlobal();
3281     if (!GV->hasDLLImportStorageClass()) {
3282       unsigned char OpFlags = 0;
3283       bool ExtraLoad = false;
3284       unsigned WrapperKind = ISD::DELETED_NODE;
3285
3286       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3287       // external symbols most go through the PLT in PIC mode.  If the symbol
3288       // has hidden or protected visibility, or if it is static or local, then
3289       // we don't need to use the PLT - we can directly call it.
3290       if (Subtarget->isTargetELF() &&
3291           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3292           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3293         OpFlags = X86II::MO_PLT;
3294       } else if (Subtarget->isPICStyleStubAny() &&
3295                  !GV->isStrongDefinitionForLinker() &&
3296                  (!Subtarget->getTargetTriple().isMacOSX() ||
3297                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3298         // PC-relative references to external symbols should go through $stub,
3299         // unless we're building with the leopard linker or later, which
3300         // automatically synthesizes these stubs.
3301         OpFlags = X86II::MO_DARWIN_STUB;
3302       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3303                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3304         // If the function is marked as non-lazy, generate an indirect call
3305         // which loads from the GOT directly. This avoids runtime overhead
3306         // at the cost of eager binding (and one extra byte of encoding).
3307         OpFlags = X86II::MO_GOTPCREL;
3308         WrapperKind = X86ISD::WrapperRIP;
3309         ExtraLoad = true;
3310       }
3311
3312       Callee = DAG.getTargetGlobalAddress(
3313           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3314
3315       // Add a wrapper if needed.
3316       if (WrapperKind != ISD::DELETED_NODE)
3317         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3318                              getPointerTy(DAG.getDataLayout()), Callee);
3319       // Add extra indirection if needed.
3320       if (ExtraLoad)
3321         Callee = DAG.getLoad(
3322             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3323             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3324             false, 0);
3325     }
3326   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3327     unsigned char OpFlags = 0;
3328
3329     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3330     // external symbols should go through the PLT.
3331     if (Subtarget->isTargetELF() &&
3332         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3333       OpFlags = X86II::MO_PLT;
3334     } else if (Subtarget->isPICStyleStubAny() &&
3335                (!Subtarget->getTargetTriple().isMacOSX() ||
3336                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3337       // PC-relative references to external symbols should go through $stub,
3338       // unless we're building with the leopard linker or later, which
3339       // automatically synthesizes these stubs.
3340       OpFlags = X86II::MO_DARWIN_STUB;
3341     }
3342
3343     Callee = DAG.getTargetExternalSymbol(
3344         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3345   } else if (Subtarget->isTarget64BitILP32() &&
3346              Callee->getValueType(0) == MVT::i32) {
3347     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3348     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3349   }
3350
3351   // Returns a chain & a flag for retval copy to use.
3352   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3353   SmallVector<SDValue, 8> Ops;
3354
3355   if (!IsSibcall && isTailCall) {
3356     Chain = DAG.getCALLSEQ_END(Chain,
3357                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3358                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3359     InFlag = Chain.getValue(1);
3360   }
3361
3362   Ops.push_back(Chain);
3363   Ops.push_back(Callee);
3364
3365   if (isTailCall)
3366     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3367
3368   // Add argument registers to the end of the list so that they are known live
3369   // into the call.
3370   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3371     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3372                                   RegsToPass[i].second.getValueType()));
3373
3374   // Add a register mask operand representing the call-preserved registers.
3375   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3376   assert(Mask && "Missing call preserved mask for calling convention");
3377
3378   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3379   // the function clobbers all registers. If an exception is thrown, the runtime
3380   // will not restore CSRs.
3381   // FIXME: Model this more precisely so that we can register allocate across
3382   // the normal edge and spill and fill across the exceptional edge.
3383   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3384     const Function *CallerFn = MF.getFunction();
3385     EHPersonality Pers =
3386         CallerFn->hasPersonalityFn()
3387             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3388             : EHPersonality::Unknown;
3389     if (isMSVCEHPersonality(Pers))
3390       Mask = RegInfo->getNoPreservedMask();
3391   }
3392
3393   Ops.push_back(DAG.getRegisterMask(Mask));
3394
3395   if (InFlag.getNode())
3396     Ops.push_back(InFlag);
3397
3398   if (isTailCall) {
3399     // We used to do:
3400     //// If this is the first return lowered for this function, add the regs
3401     //// to the liveout set for the function.
3402     // This isn't right, although it's probably harmless on x86; liveouts
3403     // should be computed from returns not tail calls.  Consider a void
3404     // function making a tail call to a function returning int.
3405     MF.getFrameInfo()->setHasTailCall();
3406     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3407   }
3408
3409   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3410   InFlag = Chain.getValue(1);
3411
3412   // Create the CALLSEQ_END node.
3413   unsigned NumBytesForCalleeToPop;
3414   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3415                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3416     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3417   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3418            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3419            SR == StackStructReturn)
3420     // If this is a call to a struct-return function, the callee
3421     // pops the hidden struct pointer, so we have to push it back.
3422     // This is common for Darwin/X86, Linux & Mingw32 targets.
3423     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3424     NumBytesForCalleeToPop = 4;
3425   else
3426     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3427
3428   // Returns a flag for retval copy to use.
3429   if (!IsSibcall) {
3430     Chain = DAG.getCALLSEQ_END(Chain,
3431                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3432                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3433                                                      true),
3434                                InFlag, dl);
3435     InFlag = Chain.getValue(1);
3436   }
3437
3438   // Handle result values, copying them out of physregs into vregs that we
3439   // return.
3440   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3441                          Ins, dl, DAG, InVals);
3442 }
3443
3444 //===----------------------------------------------------------------------===//
3445 //                Fast Calling Convention (tail call) implementation
3446 //===----------------------------------------------------------------------===//
3447
3448 //  Like std call, callee cleans arguments, convention except that ECX is
3449 //  reserved for storing the tail called function address. Only 2 registers are
3450 //  free for argument passing (inreg). Tail call optimization is performed
3451 //  provided:
3452 //                * tailcallopt is enabled
3453 //                * caller/callee are fastcc
3454 //  On X86_64 architecture with GOT-style position independent code only local
3455 //  (within module) calls are supported at the moment.
3456 //  To keep the stack aligned according to platform abi the function
3457 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3458 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3459 //  If a tail called function callee has more arguments than the caller the
3460 //  caller needs to make sure that there is room to move the RETADDR to. This is
3461 //  achieved by reserving an area the size of the argument delta right after the
3462 //  original RETADDR, but before the saved framepointer or the spilled registers
3463 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3464 //  stack layout:
3465 //    arg1
3466 //    arg2
3467 //    RETADDR
3468 //    [ new RETADDR
3469 //      move area ]
3470 //    (possible EBP)
3471 //    ESI
3472 //    EDI
3473 //    local1 ..
3474
3475 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3476 /// requirement.
3477 unsigned
3478 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3479                                                SelectionDAG& DAG) const {
3480   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3481   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3482   unsigned StackAlignment = TFI.getStackAlignment();
3483   uint64_t AlignMask = StackAlignment - 1;
3484   int64_t Offset = StackSize;
3485   unsigned SlotSize = RegInfo->getSlotSize();
3486   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3487     // Number smaller than 12 so just add the difference.
3488     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3489   } else {
3490     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3491     Offset = ((~AlignMask) & Offset) + StackAlignment +
3492       (StackAlignment-SlotSize);
3493   }
3494   return Offset;
3495 }
3496
3497 /// Return true if the given stack call argument is already available in the
3498 /// same position (relatively) of the caller's incoming argument stack.
3499 static
3500 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3501                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3502                          const X86InstrInfo *TII) {
3503   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3504   int FI = INT_MAX;
3505   if (Arg.getOpcode() == ISD::CopyFromReg) {
3506     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3507     if (!TargetRegisterInfo::isVirtualRegister(VR))
3508       return false;
3509     MachineInstr *Def = MRI->getVRegDef(VR);
3510     if (!Def)
3511       return false;
3512     if (!Flags.isByVal()) {
3513       if (!TII->isLoadFromStackSlot(Def, FI))
3514         return false;
3515     } else {
3516       unsigned Opcode = Def->getOpcode();
3517       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3518            Opcode == X86::LEA64_32r) &&
3519           Def->getOperand(1).isFI()) {
3520         FI = Def->getOperand(1).getIndex();
3521         Bytes = Flags.getByValSize();
3522       } else
3523         return false;
3524     }
3525   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3526     if (Flags.isByVal())
3527       // ByVal argument is passed in as a pointer but it's now being
3528       // dereferenced. e.g.
3529       // define @foo(%struct.X* %A) {
3530       //   tail call @bar(%struct.X* byval %A)
3531       // }
3532       return false;
3533     SDValue Ptr = Ld->getBasePtr();
3534     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3535     if (!FINode)
3536       return false;
3537     FI = FINode->getIndex();
3538   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3539     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3540     FI = FINode->getIndex();
3541     Bytes = Flags.getByValSize();
3542   } else
3543     return false;
3544
3545   assert(FI != INT_MAX);
3546   if (!MFI->isFixedObjectIndex(FI))
3547     return false;
3548   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3549 }
3550
3551 /// Check whether the call is eligible for tail call optimization. Targets
3552 /// that want to do tail call optimization should implement this function.
3553 bool
3554 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3555                                                      CallingConv::ID CalleeCC,
3556                                                      bool isVarArg,
3557                                                      bool isCalleeStructRet,
3558                                                      bool isCallerStructRet,
3559                                                      Type *RetTy,
3560                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3561                                     const SmallVectorImpl<SDValue> &OutVals,
3562                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3563                                                      SelectionDAG &DAG) const {
3564   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3565     return false;
3566
3567   // If -tailcallopt is specified, make fastcc functions tail-callable.
3568   const MachineFunction &MF = DAG.getMachineFunction();
3569   const Function *CallerF = MF.getFunction();
3570
3571   // If the function return type is x86_fp80 and the callee return type is not,
3572   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3573   // perform a tailcall optimization here.
3574   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3575     return false;
3576
3577   CallingConv::ID CallerCC = CallerF->getCallingConv();
3578   bool CCMatch = CallerCC == CalleeCC;
3579   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3580   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3581
3582   // Win64 functions have extra shadow space for argument homing. Don't do the
3583   // sibcall if the caller and callee have mismatched expectations for this
3584   // space.
3585   if (IsCalleeWin64 != IsCallerWin64)
3586     return false;
3587
3588   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3589     if (IsTailCallConvention(CalleeCC) && CCMatch)
3590       return true;
3591     return false;
3592   }
3593
3594   // Look for obvious safe cases to perform tail call optimization that do not
3595   // require ABI changes. This is what gcc calls sibcall.
3596
3597   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3598   // emit a special epilogue.
3599   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3600   if (RegInfo->needsStackRealignment(MF))
3601     return false;
3602
3603   // Also avoid sibcall optimization if either caller or callee uses struct
3604   // return semantics.
3605   if (isCalleeStructRet || isCallerStructRet)
3606     return false;
3607
3608   // An stdcall/thiscall caller is expected to clean up its arguments; the
3609   // callee isn't going to do that.
3610   // FIXME: this is more restrictive than needed. We could produce a tailcall
3611   // when the stack adjustment matches. For example, with a thiscall that takes
3612   // only one argument.
3613   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3614                    CallerCC == CallingConv::X86_ThisCall))
3615     return false;
3616
3617   // Do not sibcall optimize vararg calls unless all arguments are passed via
3618   // registers.
3619   if (isVarArg && !Outs.empty()) {
3620
3621     // Optimizing for varargs on Win64 is unlikely to be safe without
3622     // additional testing.
3623     if (IsCalleeWin64 || IsCallerWin64)
3624       return false;
3625
3626     SmallVector<CCValAssign, 16> ArgLocs;
3627     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3628                    *DAG.getContext());
3629
3630     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3631     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3632       if (!ArgLocs[i].isRegLoc())
3633         return false;
3634   }
3635
3636   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3637   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3638   // this into a sibcall.
3639   bool Unused = false;
3640   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3641     if (!Ins[i].Used) {
3642       Unused = true;
3643       break;
3644     }
3645   }
3646   if (Unused) {
3647     SmallVector<CCValAssign, 16> RVLocs;
3648     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3649                    *DAG.getContext());
3650     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3651     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3652       CCValAssign &VA = RVLocs[i];
3653       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3654         return false;
3655     }
3656   }
3657
3658   // If the calling conventions do not match, then we'd better make sure the
3659   // results are returned in the same way as what the caller expects.
3660   if (!CCMatch) {
3661     SmallVector<CCValAssign, 16> RVLocs1;
3662     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3663                     *DAG.getContext());
3664     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3665
3666     SmallVector<CCValAssign, 16> RVLocs2;
3667     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3668                     *DAG.getContext());
3669     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3670
3671     if (RVLocs1.size() != RVLocs2.size())
3672       return false;
3673     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3674       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3675         return false;
3676       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3677         return false;
3678       if (RVLocs1[i].isRegLoc()) {
3679         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3680           return false;
3681       } else {
3682         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3683           return false;
3684       }
3685     }
3686   }
3687
3688   // If the callee takes no arguments then go on to check the results of the
3689   // call.
3690   if (!Outs.empty()) {
3691     // Check if stack adjustment is needed. For now, do not do this if any
3692     // argument is passed on the stack.
3693     SmallVector<CCValAssign, 16> ArgLocs;
3694     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3695                    *DAG.getContext());
3696
3697     // Allocate shadow area for Win64
3698     if (IsCalleeWin64)
3699       CCInfo.AllocateStack(32, 8);
3700
3701     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3702     if (CCInfo.getNextStackOffset()) {
3703       MachineFunction &MF = DAG.getMachineFunction();
3704       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3705         return false;
3706
3707       // Check if the arguments are already laid out in the right way as
3708       // the caller's fixed stack objects.
3709       MachineFrameInfo *MFI = MF.getFrameInfo();
3710       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3711       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3712       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3713         CCValAssign &VA = ArgLocs[i];
3714         SDValue Arg = OutVals[i];
3715         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3716         if (VA.getLocInfo() == CCValAssign::Indirect)
3717           return false;
3718         if (!VA.isRegLoc()) {
3719           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3720                                    MFI, MRI, TII))
3721             return false;
3722         }
3723       }
3724     }
3725
3726     // If the tailcall address may be in a register, then make sure it's
3727     // possible to register allocate for it. In 32-bit, the call address can
3728     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3729     // callee-saved registers are restored. These happen to be the same
3730     // registers used to pass 'inreg' arguments so watch out for those.
3731     if (!Subtarget->is64Bit() &&
3732         ((!isa<GlobalAddressSDNode>(Callee) &&
3733           !isa<ExternalSymbolSDNode>(Callee)) ||
3734          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3735       unsigned NumInRegs = 0;
3736       // In PIC we need an extra register to formulate the address computation
3737       // for the callee.
3738       unsigned MaxInRegs =
3739         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3740
3741       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3742         CCValAssign &VA = ArgLocs[i];
3743         if (!VA.isRegLoc())
3744           continue;
3745         unsigned Reg = VA.getLocReg();
3746         switch (Reg) {
3747         default: break;
3748         case X86::EAX: case X86::EDX: case X86::ECX:
3749           if (++NumInRegs == MaxInRegs)
3750             return false;
3751           break;
3752         }
3753       }
3754     }
3755   }
3756
3757   return true;
3758 }
3759
3760 FastISel *
3761 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3762                                   const TargetLibraryInfo *libInfo) const {
3763   return X86::createFastISel(funcInfo, libInfo);
3764 }
3765
3766 //===----------------------------------------------------------------------===//
3767 //                           Other Lowering Hooks
3768 //===----------------------------------------------------------------------===//
3769
3770 static bool MayFoldLoad(SDValue Op) {
3771   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3772 }
3773
3774 static bool MayFoldIntoStore(SDValue Op) {
3775   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3776 }
3777
3778 static bool isTargetShuffle(unsigned Opcode) {
3779   switch(Opcode) {
3780   default: return false;
3781   case X86ISD::BLENDI:
3782   case X86ISD::PSHUFB:
3783   case X86ISD::PSHUFD:
3784   case X86ISD::PSHUFHW:
3785   case X86ISD::PSHUFLW:
3786   case X86ISD::SHUFP:
3787   case X86ISD::PALIGNR:
3788   case X86ISD::MOVLHPS:
3789   case X86ISD::MOVLHPD:
3790   case X86ISD::MOVHLPS:
3791   case X86ISD::MOVLPS:
3792   case X86ISD::MOVLPD:
3793   case X86ISD::MOVSHDUP:
3794   case X86ISD::MOVSLDUP:
3795   case X86ISD::MOVDDUP:
3796   case X86ISD::MOVSS:
3797   case X86ISD::MOVSD:
3798   case X86ISD::UNPCKL:
3799   case X86ISD::UNPCKH:
3800   case X86ISD::VPERMILPI:
3801   case X86ISD::VPERM2X128:
3802   case X86ISD::VPERMI:
3803   case X86ISD::VPERMV:
3804   case X86ISD::VPERMV3:
3805     return true;
3806   }
3807 }
3808
3809 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3810                                     SDValue V1, unsigned TargetMask,
3811                                     SelectionDAG &DAG) {
3812   switch(Opc) {
3813   default: llvm_unreachable("Unknown x86 shuffle node");
3814   case X86ISD::PSHUFD:
3815   case X86ISD::PSHUFHW:
3816   case X86ISD::PSHUFLW:
3817   case X86ISD::VPERMILPI:
3818   case X86ISD::VPERMI:
3819     return DAG.getNode(Opc, dl, VT, V1,
3820                        DAG.getConstant(TargetMask, dl, MVT::i8));
3821   }
3822 }
3823
3824 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3825                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3826   switch(Opc) {
3827   default: llvm_unreachable("Unknown x86 shuffle node");
3828   case X86ISD::MOVLHPS:
3829   case X86ISD::MOVLHPD:
3830   case X86ISD::MOVHLPS:
3831   case X86ISD::MOVLPS:
3832   case X86ISD::MOVLPD:
3833   case X86ISD::MOVSS:
3834   case X86ISD::MOVSD:
3835   case X86ISD::UNPCKL:
3836   case X86ISD::UNPCKH:
3837     return DAG.getNode(Opc, dl, VT, V1, V2);
3838   }
3839 }
3840
3841 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3842   MachineFunction &MF = DAG.getMachineFunction();
3843   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3844   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3845   int ReturnAddrIndex = FuncInfo->getRAIndex();
3846
3847   if (ReturnAddrIndex == 0) {
3848     // Set up a frame object for the return address.
3849     unsigned SlotSize = RegInfo->getSlotSize();
3850     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3851                                                            -(int64_t)SlotSize,
3852                                                            false);
3853     FuncInfo->setRAIndex(ReturnAddrIndex);
3854   }
3855
3856   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3857 }
3858
3859 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3860                                        bool hasSymbolicDisplacement) {
3861   // Offset should fit into 32 bit immediate field.
3862   if (!isInt<32>(Offset))
3863     return false;
3864
3865   // If we don't have a symbolic displacement - we don't have any extra
3866   // restrictions.
3867   if (!hasSymbolicDisplacement)
3868     return true;
3869
3870   // FIXME: Some tweaks might be needed for medium code model.
3871   if (M != CodeModel::Small && M != CodeModel::Kernel)
3872     return false;
3873
3874   // For small code model we assume that latest object is 16MB before end of 31
3875   // bits boundary. We may also accept pretty large negative constants knowing
3876   // that all objects are in the positive half of address space.
3877   if (M == CodeModel::Small && Offset < 16*1024*1024)
3878     return true;
3879
3880   // For kernel code model we know that all object resist in the negative half
3881   // of 32bits address space. We may not accept negative offsets, since they may
3882   // be just off and we may accept pretty large positive ones.
3883   if (M == CodeModel::Kernel && Offset >= 0)
3884     return true;
3885
3886   return false;
3887 }
3888
3889 /// Determines whether the callee is required to pop its own arguments.
3890 /// Callee pop is necessary to support tail calls.
3891 bool X86::isCalleePop(CallingConv::ID CallingConv,
3892                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3893   switch (CallingConv) {
3894   default:
3895     return false;
3896   case CallingConv::X86_StdCall:
3897   case CallingConv::X86_FastCall:
3898   case CallingConv::X86_ThisCall:
3899     return !is64Bit;
3900   case CallingConv::Fast:
3901   case CallingConv::GHC:
3902   case CallingConv::HiPE:
3903     if (IsVarArg)
3904       return false;
3905     return TailCallOpt;
3906   }
3907 }
3908
3909 /// \brief Return true if the condition is an unsigned comparison operation.
3910 static bool isX86CCUnsigned(unsigned X86CC) {
3911   switch (X86CC) {
3912   default: llvm_unreachable("Invalid integer condition!");
3913   case X86::COND_E:     return true;
3914   case X86::COND_G:     return false;
3915   case X86::COND_GE:    return false;
3916   case X86::COND_L:     return false;
3917   case X86::COND_LE:    return false;
3918   case X86::COND_NE:    return true;
3919   case X86::COND_B:     return true;
3920   case X86::COND_A:     return true;
3921   case X86::COND_BE:    return true;
3922   case X86::COND_AE:    return true;
3923   }
3924   llvm_unreachable("covered switch fell through?!");
3925 }
3926
3927 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3928 /// condition code, returning the condition code and the LHS/RHS of the
3929 /// comparison to make.
3930 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3931                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3932   if (!isFP) {
3933     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3934       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3935         // X > -1   -> X == 0, jump !sign.
3936         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3937         return X86::COND_NS;
3938       }
3939       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3940         // X < 0   -> X == 0, jump on sign.
3941         return X86::COND_S;
3942       }
3943       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3944         // X < 1   -> X <= 0
3945         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3946         return X86::COND_LE;
3947       }
3948     }
3949
3950     switch (SetCCOpcode) {
3951     default: llvm_unreachable("Invalid integer condition!");
3952     case ISD::SETEQ:  return X86::COND_E;
3953     case ISD::SETGT:  return X86::COND_G;
3954     case ISD::SETGE:  return X86::COND_GE;
3955     case ISD::SETLT:  return X86::COND_L;
3956     case ISD::SETLE:  return X86::COND_LE;
3957     case ISD::SETNE:  return X86::COND_NE;
3958     case ISD::SETULT: return X86::COND_B;
3959     case ISD::SETUGT: return X86::COND_A;
3960     case ISD::SETULE: return X86::COND_BE;
3961     case ISD::SETUGE: return X86::COND_AE;
3962     }
3963   }
3964
3965   // First determine if it is required or is profitable to flip the operands.
3966
3967   // If LHS is a foldable load, but RHS is not, flip the condition.
3968   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3969       !ISD::isNON_EXTLoad(RHS.getNode())) {
3970     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3971     std::swap(LHS, RHS);
3972   }
3973
3974   switch (SetCCOpcode) {
3975   default: break;
3976   case ISD::SETOLT:
3977   case ISD::SETOLE:
3978   case ISD::SETUGT:
3979   case ISD::SETUGE:
3980     std::swap(LHS, RHS);
3981     break;
3982   }
3983
3984   // On a floating point condition, the flags are set as follows:
3985   // ZF  PF  CF   op
3986   //  0 | 0 | 0 | X > Y
3987   //  0 | 0 | 1 | X < Y
3988   //  1 | 0 | 0 | X == Y
3989   //  1 | 1 | 1 | unordered
3990   switch (SetCCOpcode) {
3991   default: llvm_unreachable("Condcode should be pre-legalized away");
3992   case ISD::SETUEQ:
3993   case ISD::SETEQ:   return X86::COND_E;
3994   case ISD::SETOLT:              // flipped
3995   case ISD::SETOGT:
3996   case ISD::SETGT:   return X86::COND_A;
3997   case ISD::SETOLE:              // flipped
3998   case ISD::SETOGE:
3999   case ISD::SETGE:   return X86::COND_AE;
4000   case ISD::SETUGT:              // flipped
4001   case ISD::SETULT:
4002   case ISD::SETLT:   return X86::COND_B;
4003   case ISD::SETUGE:              // flipped
4004   case ISD::SETULE:
4005   case ISD::SETLE:   return X86::COND_BE;
4006   case ISD::SETONE:
4007   case ISD::SETNE:   return X86::COND_NE;
4008   case ISD::SETUO:   return X86::COND_P;
4009   case ISD::SETO:    return X86::COND_NP;
4010   case ISD::SETOEQ:
4011   case ISD::SETUNE:  return X86::COND_INVALID;
4012   }
4013 }
4014
4015 /// Is there a floating point cmov for the specific X86 condition code?
4016 /// Current x86 isa includes the following FP cmov instructions:
4017 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4018 static bool hasFPCMov(unsigned X86CC) {
4019   switch (X86CC) {
4020   default:
4021     return false;
4022   case X86::COND_B:
4023   case X86::COND_BE:
4024   case X86::COND_E:
4025   case X86::COND_P:
4026   case X86::COND_A:
4027   case X86::COND_AE:
4028   case X86::COND_NE:
4029   case X86::COND_NP:
4030     return true;
4031   }
4032 }
4033
4034 /// Returns true if the target can instruction select the
4035 /// specified FP immediate natively. If false, the legalizer will
4036 /// materialize the FP immediate as a load from a constant pool.
4037 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4038   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4039     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4040       return true;
4041   }
4042   return false;
4043 }
4044
4045 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4046                                               ISD::LoadExtType ExtTy,
4047                                               EVT NewVT) const {
4048   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4049   // relocation target a movq or addq instruction: don't let the load shrink.
4050   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4051   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4052     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4053       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4054   return true;
4055 }
4056
4057 /// \brief Returns true if it is beneficial to convert a load of a constant
4058 /// to just the constant itself.
4059 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4060                                                           Type *Ty) const {
4061   assert(Ty->isIntegerTy());
4062
4063   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4064   if (BitSize == 0 || BitSize > 64)
4065     return false;
4066   return true;
4067 }
4068
4069 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4070                                                 unsigned Index) const {
4071   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4072     return false;
4073
4074   return (Index == 0 || Index == ResVT.getVectorNumElements());
4075 }
4076
4077 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4078   // Speculate cttz only if we can directly use TZCNT.
4079   return Subtarget->hasBMI();
4080 }
4081
4082 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4083   // Speculate ctlz only if we can directly use LZCNT.
4084   return Subtarget->hasLZCNT();
4085 }
4086
4087 /// Return true if every element in Mask, beginning
4088 /// from position Pos and ending in Pos+Size is undef.
4089 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4090   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4091     if (0 <= Mask[i])
4092       return false;
4093   return true;
4094 }
4095
4096 /// Return true if Val is undef or if its value falls within the
4097 /// specified range (L, H].
4098 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4099   return (Val < 0) || (Val >= Low && Val < Hi);
4100 }
4101
4102 /// Val is either less than zero (undef) or equal to the specified value.
4103 static bool isUndefOrEqual(int Val, int CmpVal) {
4104   return (Val < 0 || Val == CmpVal);
4105 }
4106
4107 /// Return true if every element in Mask, beginning
4108 /// from position Pos and ending in Pos+Size, falls within the specified
4109 /// sequential range (Low, Low+Size]. or is undef.
4110 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4111                                        unsigned Pos, unsigned Size, int Low) {
4112   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4113     if (!isUndefOrEqual(Mask[i], Low))
4114       return false;
4115   return true;
4116 }
4117
4118 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4119 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4120 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4121   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4122   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4123     return false;
4124
4125   // The index should be aligned on a vecWidth-bit boundary.
4126   uint64_t Index =
4127     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4128
4129   MVT VT = N->getSimpleValueType(0);
4130   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4131   bool Result = (Index * ElSize) % vecWidth == 0;
4132
4133   return Result;
4134 }
4135
4136 /// Return true if the specified INSERT_SUBVECTOR
4137 /// operand specifies a subvector insert that is suitable for input to
4138 /// insertion of 128 or 256-bit subvectors
4139 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4140   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4141   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4142     return false;
4143   // The index should be aligned on a vecWidth-bit boundary.
4144   uint64_t Index =
4145     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4146
4147   MVT VT = N->getSimpleValueType(0);
4148   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4149   bool Result = (Index * ElSize) % vecWidth == 0;
4150
4151   return Result;
4152 }
4153
4154 bool X86::isVINSERT128Index(SDNode *N) {
4155   return isVINSERTIndex(N, 128);
4156 }
4157
4158 bool X86::isVINSERT256Index(SDNode *N) {
4159   return isVINSERTIndex(N, 256);
4160 }
4161
4162 bool X86::isVEXTRACT128Index(SDNode *N) {
4163   return isVEXTRACTIndex(N, 128);
4164 }
4165
4166 bool X86::isVEXTRACT256Index(SDNode *N) {
4167   return isVEXTRACTIndex(N, 256);
4168 }
4169
4170 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4171   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4172   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4173     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4174
4175   uint64_t Index =
4176     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4177
4178   MVT VecVT = N->getOperand(0).getSimpleValueType();
4179   MVT ElVT = VecVT.getVectorElementType();
4180
4181   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4182   return Index / NumElemsPerChunk;
4183 }
4184
4185 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4186   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4187   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4188     llvm_unreachable("Illegal insert subvector for VINSERT");
4189
4190   uint64_t Index =
4191     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4192
4193   MVT VecVT = N->getSimpleValueType(0);
4194   MVT ElVT = VecVT.getVectorElementType();
4195
4196   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4197   return Index / NumElemsPerChunk;
4198 }
4199
4200 /// Return the appropriate immediate to extract the specified
4201 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4202 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4203   return getExtractVEXTRACTImmediate(N, 128);
4204 }
4205
4206 /// Return the appropriate immediate to extract the specified
4207 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4208 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4209   return getExtractVEXTRACTImmediate(N, 256);
4210 }
4211
4212 /// Return the appropriate immediate to insert at the specified
4213 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4214 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4215   return getInsertVINSERTImmediate(N, 128);
4216 }
4217
4218 /// Return the appropriate immediate to insert at the specified
4219 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4220 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4221   return getInsertVINSERTImmediate(N, 256);
4222 }
4223
4224 /// Returns true if Elt is a constant integer zero
4225 static bool isZero(SDValue V) {
4226   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4227   return C && C->isNullValue();
4228 }
4229
4230 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4231 bool X86::isZeroNode(SDValue Elt) {
4232   if (isZero(Elt))
4233     return true;
4234   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4235     return CFP->getValueAPF().isPosZero();
4236   return false;
4237 }
4238
4239 /// Returns a vector of specified type with all zero elements.
4240 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4241                              SelectionDAG &DAG, SDLoc dl) {
4242   assert(VT.isVector() && "Expected a vector type");
4243
4244   // Always build SSE zero vectors as <4 x i32> bitcasted
4245   // to their dest type. This ensures they get CSE'd.
4246   SDValue Vec;
4247   if (VT.is128BitVector()) {  // SSE
4248     if (Subtarget->hasSSE2()) {  // SSE2
4249       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4250       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4251     } else { // SSE1
4252       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4253       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4254     }
4255   } else if (VT.is256BitVector()) { // AVX
4256     if (Subtarget->hasInt256()) { // AVX2
4257       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4258       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4259       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4260     } else {
4261       // 256-bit logic and arithmetic instructions in AVX are all
4262       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4263       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4264       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4265       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4266     }
4267   } else if (VT.is512BitVector()) { // AVX-512
4268       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4269       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4270                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4271       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4272   } else if (VT.getScalarType() == MVT::i1) {
4273
4274     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4275             && "Unexpected vector type");
4276     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4277             && "Unexpected vector type");
4278     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4279     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4280     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4281   } else
4282     llvm_unreachable("Unexpected vector type");
4283
4284   return DAG.getBitcast(VT, Vec);
4285 }
4286
4287 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4288                                 SelectionDAG &DAG, SDLoc dl,
4289                                 unsigned vectorWidth) {
4290   assert((vectorWidth == 128 || vectorWidth == 256) &&
4291          "Unsupported vector width");
4292   EVT VT = Vec.getValueType();
4293   EVT ElVT = VT.getVectorElementType();
4294   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4295   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4296                                   VT.getVectorNumElements()/Factor);
4297
4298   // Extract from UNDEF is UNDEF.
4299   if (Vec.getOpcode() == ISD::UNDEF)
4300     return DAG.getUNDEF(ResultVT);
4301
4302   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4303   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4304
4305   // This is the index of the first element of the vectorWidth-bit chunk
4306   // we want.
4307   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4308                                * ElemsPerChunk);
4309
4310   // If the input is a buildvector just emit a smaller one.
4311   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4312     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4313                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4314                                     ElemsPerChunk));
4315
4316   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4317   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4318 }
4319
4320 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4321 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4322 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4323 /// instructions or a simple subregister reference. Idx is an index in the
4324 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4325 /// lowering EXTRACT_VECTOR_ELT operations easier.
4326 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4327                                    SelectionDAG &DAG, SDLoc dl) {
4328   assert((Vec.getValueType().is256BitVector() ||
4329           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4330   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4331 }
4332
4333 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4334 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4335                                    SelectionDAG &DAG, SDLoc dl) {
4336   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4337   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4338 }
4339
4340 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4341                                unsigned IdxVal, SelectionDAG &DAG,
4342                                SDLoc dl, unsigned vectorWidth) {
4343   assert((vectorWidth == 128 || vectorWidth == 256) &&
4344          "Unsupported vector width");
4345   // Inserting UNDEF is Result
4346   if (Vec.getOpcode() == ISD::UNDEF)
4347     return Result;
4348   EVT VT = Vec.getValueType();
4349   EVT ElVT = VT.getVectorElementType();
4350   EVT ResultVT = Result.getValueType();
4351
4352   // Insert the relevant vectorWidth bits.
4353   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4354
4355   // This is the index of the first element of the vectorWidth-bit chunk
4356   // we want.
4357   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4358                                * ElemsPerChunk);
4359
4360   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4361   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4362 }
4363
4364 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4365 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4366 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4367 /// simple superregister reference.  Idx is an index in the 128 bits
4368 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4369 /// lowering INSERT_VECTOR_ELT operations easier.
4370 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4371                                   SelectionDAG &DAG, SDLoc dl) {
4372   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4373
4374   // For insertion into the zero index (low half) of a 256-bit vector, it is
4375   // more efficient to generate a blend with immediate instead of an insert*128.
4376   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4377   // extend the subvector to the size of the result vector. Make sure that
4378   // we are not recursing on that node by checking for undef here.
4379   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4380       Result.getOpcode() != ISD::UNDEF) {
4381     EVT ResultVT = Result.getValueType();
4382     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4383     SDValue Undef = DAG.getUNDEF(ResultVT);
4384     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4385                                  Vec, ZeroIndex);
4386
4387     // The blend instruction, and therefore its mask, depend on the data type.
4388     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4389     if (ScalarType.isFloatingPoint()) {
4390       // Choose either vblendps (float) or vblendpd (double).
4391       unsigned ScalarSize = ScalarType.getSizeInBits();
4392       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4393       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4394       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4395       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4396     }
4397
4398     const X86Subtarget &Subtarget =
4399     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4400
4401     // AVX2 is needed for 256-bit integer blend support.
4402     // Integers must be cast to 32-bit because there is only vpblendd;
4403     // vpblendw can't be used for this because it has a handicapped mask.
4404
4405     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4406     // is still more efficient than using the wrong domain vinsertf128 that
4407     // will be created by InsertSubVector().
4408     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4409
4410     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4411     Vec256 = DAG.getBitcast(CastVT, Vec256);
4412     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4413     return DAG.getBitcast(ResultVT, Vec256);
4414   }
4415
4416   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4417 }
4418
4419 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4420                                   SelectionDAG &DAG, SDLoc dl) {
4421   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4422   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4423 }
4424
4425 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4426 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4427 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4428 /// large BUILD_VECTORS.
4429 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4430                                    unsigned NumElems, SelectionDAG &DAG,
4431                                    SDLoc dl) {
4432   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4433   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4434 }
4435
4436 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4437                                    unsigned NumElems, SelectionDAG &DAG,
4438                                    SDLoc dl) {
4439   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4440   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4441 }
4442
4443 /// Returns a vector of specified type with all bits set.
4444 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4445 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4446 /// Then bitcast to their original type, ensuring they get CSE'd.
4447 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4448                              SelectionDAG &DAG, SDLoc dl) {
4449   assert(VT.isVector() && "Expected a vector type");
4450
4451   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4452   SDValue Vec;
4453   if (VT.is512BitVector()) {
4454     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4455                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4456     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4457   } else if (VT.is256BitVector()) {
4458     if (Subtarget->hasInt256()) { // AVX2
4459       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4460       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4461     } else { // AVX
4462       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4463       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4464     }
4465   } else if (VT.is128BitVector()) {
4466     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4467   } else
4468     llvm_unreachable("Unexpected vector type");
4469
4470   return DAG.getBitcast(VT, Vec);
4471 }
4472
4473 /// Returns a vector_shuffle node for an unpackl operation.
4474 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4475                           SDValue V2) {
4476   unsigned NumElems = VT.getVectorNumElements();
4477   SmallVector<int, 8> Mask;
4478   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4479     Mask.push_back(i);
4480     Mask.push_back(i + NumElems);
4481   }
4482   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4483 }
4484
4485 /// Returns a vector_shuffle node for an unpackh operation.
4486 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4487                           SDValue V2) {
4488   unsigned NumElems = VT.getVectorNumElements();
4489   SmallVector<int, 8> Mask;
4490   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4491     Mask.push_back(i + Half);
4492     Mask.push_back(i + NumElems + Half);
4493   }
4494   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4495 }
4496
4497 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4498 /// This produces a shuffle where the low element of V2 is swizzled into the
4499 /// zero/undef vector, landing at element Idx.
4500 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4501 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4502                                            bool IsZero,
4503                                            const X86Subtarget *Subtarget,
4504                                            SelectionDAG &DAG) {
4505   MVT VT = V2.getSimpleValueType();
4506   SDValue V1 = IsZero
4507     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4508   unsigned NumElems = VT.getVectorNumElements();
4509   SmallVector<int, 16> MaskVec;
4510   for (unsigned i = 0; i != NumElems; ++i)
4511     // If this is the insertion idx, put the low elt of V2 here.
4512     MaskVec.push_back(i == Idx ? NumElems : i);
4513   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4514 }
4515
4516 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4517 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4518 /// uses one source. Note that this will set IsUnary for shuffles which use a
4519 /// single input multiple times, and in those cases it will
4520 /// adjust the mask to only have indices within that single input.
4521 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4522 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4523                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4524   unsigned NumElems = VT.getVectorNumElements();
4525   SDValue ImmN;
4526
4527   IsUnary = false;
4528   bool IsFakeUnary = false;
4529   switch(N->getOpcode()) {
4530   case X86ISD::BLENDI:
4531     ImmN = N->getOperand(N->getNumOperands()-1);
4532     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4533     break;
4534   case X86ISD::SHUFP:
4535     ImmN = N->getOperand(N->getNumOperands()-1);
4536     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4537     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4538     break;
4539   case X86ISD::UNPCKH:
4540     DecodeUNPCKHMask(VT, Mask);
4541     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4542     break;
4543   case X86ISD::UNPCKL:
4544     DecodeUNPCKLMask(VT, Mask);
4545     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4546     break;
4547   case X86ISD::MOVHLPS:
4548     DecodeMOVHLPSMask(NumElems, Mask);
4549     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4550     break;
4551   case X86ISD::MOVLHPS:
4552     DecodeMOVLHPSMask(NumElems, Mask);
4553     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4554     break;
4555   case X86ISD::PALIGNR:
4556     ImmN = N->getOperand(N->getNumOperands()-1);
4557     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4558     break;
4559   case X86ISD::PSHUFD:
4560   case X86ISD::VPERMILPI:
4561     ImmN = N->getOperand(N->getNumOperands()-1);
4562     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4563     IsUnary = true;
4564     break;
4565   case X86ISD::PSHUFHW:
4566     ImmN = N->getOperand(N->getNumOperands()-1);
4567     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4568     IsUnary = true;
4569     break;
4570   case X86ISD::PSHUFLW:
4571     ImmN = N->getOperand(N->getNumOperands()-1);
4572     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4573     IsUnary = true;
4574     break;
4575   case X86ISD::PSHUFB: {
4576     IsUnary = true;
4577     SDValue MaskNode = N->getOperand(1);
4578     while (MaskNode->getOpcode() == ISD::BITCAST)
4579       MaskNode = MaskNode->getOperand(0);
4580
4581     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4582       // If we have a build-vector, then things are easy.
4583       EVT VT = MaskNode.getValueType();
4584       assert(VT.isVector() &&
4585              "Can't produce a non-vector with a build_vector!");
4586       if (!VT.isInteger())
4587         return false;
4588
4589       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4590
4591       SmallVector<uint64_t, 32> RawMask;
4592       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4593         SDValue Op = MaskNode->getOperand(i);
4594         if (Op->getOpcode() == ISD::UNDEF) {
4595           RawMask.push_back((uint64_t)SM_SentinelUndef);
4596           continue;
4597         }
4598         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4599         if (!CN)
4600           return false;
4601         APInt MaskElement = CN->getAPIntValue();
4602
4603         // We now have to decode the element which could be any integer size and
4604         // extract each byte of it.
4605         for (int j = 0; j < NumBytesPerElement; ++j) {
4606           // Note that this is x86 and so always little endian: the low byte is
4607           // the first byte of the mask.
4608           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4609           MaskElement = MaskElement.lshr(8);
4610         }
4611       }
4612       DecodePSHUFBMask(RawMask, Mask);
4613       break;
4614     }
4615
4616     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4617     if (!MaskLoad)
4618       return false;
4619
4620     SDValue Ptr = MaskLoad->getBasePtr();
4621     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4622         Ptr->getOpcode() == X86ISD::WrapperRIP)
4623       Ptr = Ptr->getOperand(0);
4624
4625     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4626     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4627       return false;
4628
4629     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4630       DecodePSHUFBMask(C, Mask);
4631       if (Mask.empty())
4632         return false;
4633       break;
4634     }
4635
4636     return false;
4637   }
4638   case X86ISD::VPERMI:
4639     ImmN = N->getOperand(N->getNumOperands()-1);
4640     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4641     IsUnary = true;
4642     break;
4643   case X86ISD::MOVSS:
4644   case X86ISD::MOVSD:
4645     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4646     break;
4647   case X86ISD::VPERM2X128:
4648     ImmN = N->getOperand(N->getNumOperands()-1);
4649     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4650     if (Mask.empty()) return false;
4651     // Mask only contains negative index if an element is zero.
4652     if (std::any_of(Mask.begin(), Mask.end(),
4653                     [](int M){ return M == SM_SentinelZero; }))
4654       return false;
4655     break;
4656   case X86ISD::MOVSLDUP:
4657     DecodeMOVSLDUPMask(VT, Mask);
4658     IsUnary = true;
4659     break;
4660   case X86ISD::MOVSHDUP:
4661     DecodeMOVSHDUPMask(VT, Mask);
4662     IsUnary = true;
4663     break;
4664   case X86ISD::MOVDDUP:
4665     DecodeMOVDDUPMask(VT, Mask);
4666     IsUnary = true;
4667     break;
4668   case X86ISD::MOVLHPD:
4669   case X86ISD::MOVLPD:
4670   case X86ISD::MOVLPS:
4671     // Not yet implemented
4672     return false;
4673   case X86ISD::VPERMV: {
4674     IsUnary = true;
4675     SDValue MaskNode = N->getOperand(0);
4676     while (MaskNode->getOpcode() == ISD::BITCAST)
4677       MaskNode = MaskNode->getOperand(0);
4678
4679     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4680     SmallVector<uint64_t, 32> RawMask;
4681     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4682       // If we have a build-vector, then things are easy.
4683       assert(MaskNode.getValueType().isInteger() &&
4684              MaskNode.getValueType().getVectorNumElements() ==
4685              VT.getVectorNumElements());
4686
4687       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4688         SDValue Op = MaskNode->getOperand(i);
4689         if (Op->getOpcode() == ISD::UNDEF)
4690           RawMask.push_back((uint64_t)SM_SentinelUndef);
4691         else if (isa<ConstantSDNode>(Op)) {
4692           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4693           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4694         } else
4695           return false;
4696       }
4697       DecodeVPERMVMask(RawMask, Mask);
4698       break;
4699     }
4700     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4701       unsigned NumEltsInMask = MaskNode->getNumOperands();
4702       MaskNode = MaskNode->getOperand(0);
4703       auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4704       if (CN) {
4705         APInt MaskEltValue = CN->getAPIntValue();
4706         for (unsigned i = 0; i < NumEltsInMask; ++i)
4707           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4708         DecodeVPERMVMask(RawMask, Mask);
4709         break;
4710       }
4711       // It may be a scalar load
4712     }
4713
4714     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4715     if (!MaskLoad)
4716       return false;
4717
4718     SDValue Ptr = MaskLoad->getBasePtr();
4719     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4720         Ptr->getOpcode() == X86ISD::WrapperRIP)
4721       Ptr = Ptr->getOperand(0);
4722
4723     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4724     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4725       return false;
4726
4727     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4728     if (C) {
4729       DecodeVPERMVMask(C, VT, Mask);
4730       if (Mask.empty())
4731         return false;
4732       break;
4733     }
4734     return false;
4735   }
4736   case X86ISD::VPERMV3: {
4737     IsUnary = false;
4738     SDValue MaskNode = N->getOperand(1);
4739     while (MaskNode->getOpcode() == ISD::BITCAST)
4740       MaskNode = MaskNode->getOperand(1);
4741
4742     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4743       // If we have a build-vector, then things are easy.
4744       assert(MaskNode.getValueType().isInteger() &&
4745              MaskNode.getValueType().getVectorNumElements() ==
4746              VT.getVectorNumElements());
4747
4748       SmallVector<uint64_t, 32> RawMask;
4749       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4750
4751       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4752         SDValue Op = MaskNode->getOperand(i);
4753         if (Op->getOpcode() == ISD::UNDEF)
4754           RawMask.push_back((uint64_t)SM_SentinelUndef);
4755         else {
4756           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4757           if (!CN)
4758             return false;
4759           APInt MaskElement = CN->getAPIntValue();
4760           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4761         }
4762       }
4763       DecodeVPERMV3Mask(RawMask, Mask);
4764       break;
4765     }
4766
4767     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4768     if (!MaskLoad)
4769       return false;
4770
4771     SDValue Ptr = MaskLoad->getBasePtr();
4772     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4773         Ptr->getOpcode() == X86ISD::WrapperRIP)
4774       Ptr = Ptr->getOperand(0);
4775
4776     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4777     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4778       return false;
4779
4780     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4781     if (C) {
4782       DecodeVPERMV3Mask(C, VT, Mask);
4783       if (Mask.empty())
4784         return false;
4785       break;
4786     }
4787     return false;
4788   }
4789   default: llvm_unreachable("unknown target shuffle node");
4790   }
4791
4792   // If we have a fake unary shuffle, the shuffle mask is spread across two
4793   // inputs that are actually the same node. Re-map the mask to always point
4794   // into the first input.
4795   if (IsFakeUnary)
4796     for (int &M : Mask)
4797       if (M >= (int)Mask.size())
4798         M -= Mask.size();
4799
4800   return true;
4801 }
4802
4803 /// Returns the scalar element that will make up the ith
4804 /// element of the result of the vector shuffle.
4805 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4806                                    unsigned Depth) {
4807   if (Depth == 6)
4808     return SDValue();  // Limit search depth.
4809
4810   SDValue V = SDValue(N, 0);
4811   EVT VT = V.getValueType();
4812   unsigned Opcode = V.getOpcode();
4813
4814   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4815   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4816     int Elt = SV->getMaskElt(Index);
4817
4818     if (Elt < 0)
4819       return DAG.getUNDEF(VT.getVectorElementType());
4820
4821     unsigned NumElems = VT.getVectorNumElements();
4822     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4823                                          : SV->getOperand(1);
4824     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4825   }
4826
4827   // Recurse into target specific vector shuffles to find scalars.
4828   if (isTargetShuffle(Opcode)) {
4829     MVT ShufVT = V.getSimpleValueType();
4830     unsigned NumElems = ShufVT.getVectorNumElements();
4831     SmallVector<int, 16> ShuffleMask;
4832     bool IsUnary;
4833
4834     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4835       return SDValue();
4836
4837     int Elt = ShuffleMask[Index];
4838     if (Elt < 0)
4839       return DAG.getUNDEF(ShufVT.getVectorElementType());
4840
4841     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4842                                          : N->getOperand(1);
4843     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4844                                Depth+1);
4845   }
4846
4847   // Actual nodes that may contain scalar elements
4848   if (Opcode == ISD::BITCAST) {
4849     V = V.getOperand(0);
4850     EVT SrcVT = V.getValueType();
4851     unsigned NumElems = VT.getVectorNumElements();
4852
4853     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4854       return SDValue();
4855   }
4856
4857   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4858     return (Index == 0) ? V.getOperand(0)
4859                         : DAG.getUNDEF(VT.getVectorElementType());
4860
4861   if (V.getOpcode() == ISD::BUILD_VECTOR)
4862     return V.getOperand(Index);
4863
4864   return SDValue();
4865 }
4866
4867 /// Custom lower build_vector of v16i8.
4868 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4869                                        unsigned NumNonZero, unsigned NumZero,
4870                                        SelectionDAG &DAG,
4871                                        const X86Subtarget* Subtarget,
4872                                        const TargetLowering &TLI) {
4873   if (NumNonZero > 8)
4874     return SDValue();
4875
4876   SDLoc dl(Op);
4877   SDValue V;
4878   bool First = true;
4879
4880   // SSE4.1 - use PINSRB to insert each byte directly.
4881   if (Subtarget->hasSSE41()) {
4882     for (unsigned i = 0; i < 16; ++i) {
4883       bool isNonZero = (NonZeros & (1 << i)) != 0;
4884       if (isNonZero) {
4885         if (First) {
4886           if (NumZero)
4887             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4888           else
4889             V = DAG.getUNDEF(MVT::v16i8);
4890           First = false;
4891         }
4892         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4893                         MVT::v16i8, V, Op.getOperand(i),
4894                         DAG.getIntPtrConstant(i, dl));
4895       }
4896     }
4897
4898     return V;
4899   }
4900
4901   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4902   for (unsigned i = 0; i < 16; ++i) {
4903     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4904     if (ThisIsNonZero && First) {
4905       if (NumZero)
4906         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4907       else
4908         V = DAG.getUNDEF(MVT::v8i16);
4909       First = false;
4910     }
4911
4912     if ((i & 1) != 0) {
4913       SDValue ThisElt, LastElt;
4914       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4915       if (LastIsNonZero) {
4916         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4917                               MVT::i16, Op.getOperand(i-1));
4918       }
4919       if (ThisIsNonZero) {
4920         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4921         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4922                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4923         if (LastIsNonZero)
4924           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4925       } else
4926         ThisElt = LastElt;
4927
4928       if (ThisElt.getNode())
4929         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4930                         DAG.getIntPtrConstant(i/2, dl));
4931     }
4932   }
4933
4934   return DAG.getBitcast(MVT::v16i8, V);
4935 }
4936
4937 /// Custom lower build_vector of v8i16.
4938 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4939                                      unsigned NumNonZero, unsigned NumZero,
4940                                      SelectionDAG &DAG,
4941                                      const X86Subtarget* Subtarget,
4942                                      const TargetLowering &TLI) {
4943   if (NumNonZero > 4)
4944     return SDValue();
4945
4946   SDLoc dl(Op);
4947   SDValue V;
4948   bool First = true;
4949   for (unsigned i = 0; i < 8; ++i) {
4950     bool isNonZero = (NonZeros & (1 << i)) != 0;
4951     if (isNonZero) {
4952       if (First) {
4953         if (NumZero)
4954           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4955         else
4956           V = DAG.getUNDEF(MVT::v8i16);
4957         First = false;
4958       }
4959       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4960                       MVT::v8i16, V, Op.getOperand(i),
4961                       DAG.getIntPtrConstant(i, dl));
4962     }
4963   }
4964
4965   return V;
4966 }
4967
4968 /// Custom lower build_vector of v4i32 or v4f32.
4969 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4970                                      const X86Subtarget *Subtarget,
4971                                      const TargetLowering &TLI) {
4972   // Find all zeroable elements.
4973   std::bitset<4> Zeroable;
4974   for (int i=0; i < 4; ++i) {
4975     SDValue Elt = Op->getOperand(i);
4976     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4977   }
4978   assert(Zeroable.size() - Zeroable.count() > 1 &&
4979          "We expect at least two non-zero elements!");
4980
4981   // We only know how to deal with build_vector nodes where elements are either
4982   // zeroable or extract_vector_elt with constant index.
4983   SDValue FirstNonZero;
4984   unsigned FirstNonZeroIdx;
4985   for (unsigned i=0; i < 4; ++i) {
4986     if (Zeroable[i])
4987       continue;
4988     SDValue Elt = Op->getOperand(i);
4989     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4990         !isa<ConstantSDNode>(Elt.getOperand(1)))
4991       return SDValue();
4992     // Make sure that this node is extracting from a 128-bit vector.
4993     MVT VT = Elt.getOperand(0).getSimpleValueType();
4994     if (!VT.is128BitVector())
4995       return SDValue();
4996     if (!FirstNonZero.getNode()) {
4997       FirstNonZero = Elt;
4998       FirstNonZeroIdx = i;
4999     }
5000   }
5001
5002   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5003   SDValue V1 = FirstNonZero.getOperand(0);
5004   MVT VT = V1.getSimpleValueType();
5005
5006   // See if this build_vector can be lowered as a blend with zero.
5007   SDValue Elt;
5008   unsigned EltMaskIdx, EltIdx;
5009   int Mask[4];
5010   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5011     if (Zeroable[EltIdx]) {
5012       // The zero vector will be on the right hand side.
5013       Mask[EltIdx] = EltIdx+4;
5014       continue;
5015     }
5016
5017     Elt = Op->getOperand(EltIdx);
5018     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5019     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5020     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5021       break;
5022     Mask[EltIdx] = EltIdx;
5023   }
5024
5025   if (EltIdx == 4) {
5026     // Let the shuffle legalizer deal with blend operations.
5027     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5028     if (V1.getSimpleValueType() != VT)
5029       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5030     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5031   }
5032
5033   // See if we can lower this build_vector to a INSERTPS.
5034   if (!Subtarget->hasSSE41())
5035     return SDValue();
5036
5037   SDValue V2 = Elt.getOperand(0);
5038   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5039     V1 = SDValue();
5040
5041   bool CanFold = true;
5042   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5043     if (Zeroable[i])
5044       continue;
5045
5046     SDValue Current = Op->getOperand(i);
5047     SDValue SrcVector = Current->getOperand(0);
5048     if (!V1.getNode())
5049       V1 = SrcVector;
5050     CanFold = SrcVector == V1 &&
5051       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5052   }
5053
5054   if (!CanFold)
5055     return SDValue();
5056
5057   assert(V1.getNode() && "Expected at least two non-zero elements!");
5058   if (V1.getSimpleValueType() != MVT::v4f32)
5059     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5060   if (V2.getSimpleValueType() != MVT::v4f32)
5061     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5062
5063   // Ok, we can emit an INSERTPS instruction.
5064   unsigned ZMask = Zeroable.to_ulong();
5065
5066   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5067   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5068   SDLoc DL(Op);
5069   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5070                                DAG.getIntPtrConstant(InsertPSMask, DL));
5071   return DAG.getBitcast(VT, Result);
5072 }
5073
5074 /// Return a vector logical shift node.
5075 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5076                          unsigned NumBits, SelectionDAG &DAG,
5077                          const TargetLowering &TLI, SDLoc dl) {
5078   assert(VT.is128BitVector() && "Unknown type for VShift");
5079   MVT ShVT = MVT::v2i64;
5080   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5081   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5082   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5083   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5084   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5085   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5086 }
5087
5088 static SDValue
5089 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5090
5091   // Check if the scalar load can be widened into a vector load. And if
5092   // the address is "base + cst" see if the cst can be "absorbed" into
5093   // the shuffle mask.
5094   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5095     SDValue Ptr = LD->getBasePtr();
5096     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5097       return SDValue();
5098     EVT PVT = LD->getValueType(0);
5099     if (PVT != MVT::i32 && PVT != MVT::f32)
5100       return SDValue();
5101
5102     int FI = -1;
5103     int64_t Offset = 0;
5104     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5105       FI = FINode->getIndex();
5106       Offset = 0;
5107     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5108                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5109       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5110       Offset = Ptr.getConstantOperandVal(1);
5111       Ptr = Ptr.getOperand(0);
5112     } else {
5113       return SDValue();
5114     }
5115
5116     // FIXME: 256-bit vector instructions don't require a strict alignment,
5117     // improve this code to support it better.
5118     unsigned RequiredAlign = VT.getSizeInBits()/8;
5119     SDValue Chain = LD->getChain();
5120     // Make sure the stack object alignment is at least 16 or 32.
5121     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5122     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5123       if (MFI->isFixedObjectIndex(FI)) {
5124         // Can't change the alignment. FIXME: It's possible to compute
5125         // the exact stack offset and reference FI + adjust offset instead.
5126         // If someone *really* cares about this. That's the way to implement it.
5127         return SDValue();
5128       } else {
5129         MFI->setObjectAlignment(FI, RequiredAlign);
5130       }
5131     }
5132
5133     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5134     // Ptr + (Offset & ~15).
5135     if (Offset < 0)
5136       return SDValue();
5137     if ((Offset % RequiredAlign) & 3)
5138       return SDValue();
5139     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5140     if (StartOffset) {
5141       SDLoc DL(Ptr);
5142       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5143                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5144     }
5145
5146     int EltNo = (Offset - StartOffset) >> 2;
5147     unsigned NumElems = VT.getVectorNumElements();
5148
5149     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5150     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5151                              LD->getPointerInfo().getWithOffset(StartOffset),
5152                              false, false, false, 0);
5153
5154     SmallVector<int, 8> Mask(NumElems, EltNo);
5155
5156     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5157   }
5158
5159   return SDValue();
5160 }
5161
5162 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5163 /// elements can be replaced by a single large load which has the same value as
5164 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5165 ///
5166 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5167 ///
5168 /// FIXME: we'd also like to handle the case where the last elements are zero
5169 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5170 /// There's even a handy isZeroNode for that purpose.
5171 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5172                                         SDLoc &DL, SelectionDAG &DAG,
5173                                         bool isAfterLegalize) {
5174   unsigned NumElems = Elts.size();
5175
5176   LoadSDNode *LDBase = nullptr;
5177   unsigned LastLoadedElt = -1U;
5178
5179   // For each element in the initializer, see if we've found a load or an undef.
5180   // If we don't find an initial load element, or later load elements are
5181   // non-consecutive, bail out.
5182   for (unsigned i = 0; i < NumElems; ++i) {
5183     SDValue Elt = Elts[i];
5184     // Look through a bitcast.
5185     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5186       Elt = Elt.getOperand(0);
5187     if (!Elt.getNode() ||
5188         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5189       return SDValue();
5190     if (!LDBase) {
5191       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5192         return SDValue();
5193       LDBase = cast<LoadSDNode>(Elt.getNode());
5194       LastLoadedElt = i;
5195       continue;
5196     }
5197     if (Elt.getOpcode() == ISD::UNDEF)
5198       continue;
5199
5200     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5201     EVT LdVT = Elt.getValueType();
5202     // Each loaded element must be the correct fractional portion of the
5203     // requested vector load.
5204     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5205       return SDValue();
5206     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5207       return SDValue();
5208     LastLoadedElt = i;
5209   }
5210
5211   // If we have found an entire vector of loads and undefs, then return a large
5212   // load of the entire vector width starting at the base pointer.  If we found
5213   // consecutive loads for the low half, generate a vzext_load node.
5214   if (LastLoadedElt == NumElems - 1) {
5215     assert(LDBase && "Did not find base load for merging consecutive loads");
5216     EVT EltVT = LDBase->getValueType(0);
5217     // Ensure that the input vector size for the merged loads matches the
5218     // cumulative size of the input elements.
5219     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5220       return SDValue();
5221
5222     if (isAfterLegalize &&
5223         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5224       return SDValue();
5225
5226     SDValue NewLd = SDValue();
5227
5228     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5229                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5230                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5231                         LDBase->getAlignment());
5232
5233     if (LDBase->hasAnyUseOfValue(1)) {
5234       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5235                                      SDValue(LDBase, 1),
5236                                      SDValue(NewLd.getNode(), 1));
5237       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5238       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5239                              SDValue(NewLd.getNode(), 1));
5240     }
5241
5242     return NewLd;
5243   }
5244
5245   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5246   //of a v4i32 / v4f32. It's probably worth generalizing.
5247   EVT EltVT = VT.getVectorElementType();
5248   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5249       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5250     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5251     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5252     SDValue ResNode =
5253         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5254                                 LDBase->getPointerInfo(),
5255                                 LDBase->getAlignment(),
5256                                 false/*isVolatile*/, true/*ReadMem*/,
5257                                 false/*WriteMem*/);
5258
5259     // Make sure the newly-created LOAD is in the same position as LDBase in
5260     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5261     // update uses of LDBase's output chain to use the TokenFactor.
5262     if (LDBase->hasAnyUseOfValue(1)) {
5263       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5264                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5265       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5266       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5267                              SDValue(ResNode.getNode(), 1));
5268     }
5269
5270     return DAG.getBitcast(VT, ResNode);
5271   }
5272   return SDValue();
5273 }
5274
5275 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5276 /// to generate a splat value for the following cases:
5277 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5278 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5279 /// a scalar load, or a constant.
5280 /// The VBROADCAST node is returned when a pattern is found,
5281 /// or SDValue() otherwise.
5282 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5283                                     SelectionDAG &DAG) {
5284   // VBROADCAST requires AVX.
5285   // TODO: Splats could be generated for non-AVX CPUs using SSE
5286   // instructions, but there's less potential gain for only 128-bit vectors.
5287   if (!Subtarget->hasAVX())
5288     return SDValue();
5289
5290   MVT VT = Op.getSimpleValueType();
5291   SDLoc dl(Op);
5292
5293   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5294          "Unsupported vector type for broadcast.");
5295
5296   SDValue Ld;
5297   bool ConstSplatVal;
5298
5299   switch (Op.getOpcode()) {
5300     default:
5301       // Unknown pattern found.
5302       return SDValue();
5303
5304     case ISD::BUILD_VECTOR: {
5305       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5306       BitVector UndefElements;
5307       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5308
5309       // We need a splat of a single value to use broadcast, and it doesn't
5310       // make any sense if the value is only in one element of the vector.
5311       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5312         return SDValue();
5313
5314       Ld = Splat;
5315       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5316                        Ld.getOpcode() == ISD::ConstantFP);
5317
5318       // Make sure that all of the users of a non-constant load are from the
5319       // BUILD_VECTOR node.
5320       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5321         return SDValue();
5322       break;
5323     }
5324
5325     case ISD::VECTOR_SHUFFLE: {
5326       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5327
5328       // Shuffles must have a splat mask where the first element is
5329       // broadcasted.
5330       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5331         return SDValue();
5332
5333       SDValue Sc = Op.getOperand(0);
5334       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5335           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5336
5337         if (!Subtarget->hasInt256())
5338           return SDValue();
5339
5340         // Use the register form of the broadcast instruction available on AVX2.
5341         if (VT.getSizeInBits() >= 256)
5342           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5343         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5344       }
5345
5346       Ld = Sc.getOperand(0);
5347       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5348                        Ld.getOpcode() == ISD::ConstantFP);
5349
5350       // The scalar_to_vector node and the suspected
5351       // load node must have exactly one user.
5352       // Constants may have multiple users.
5353
5354       // AVX-512 has register version of the broadcast
5355       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5356         Ld.getValueType().getSizeInBits() >= 32;
5357       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5358           !hasRegVer))
5359         return SDValue();
5360       break;
5361     }
5362   }
5363
5364   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5365   bool IsGE256 = (VT.getSizeInBits() >= 256);
5366
5367   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5368   // instruction to save 8 or more bytes of constant pool data.
5369   // TODO: If multiple splats are generated to load the same constant,
5370   // it may be detrimental to overall size. There needs to be a way to detect
5371   // that condition to know if this is truly a size win.
5372   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5373
5374   // Handle broadcasting a single constant scalar from the constant pool
5375   // into a vector.
5376   // On Sandybridge (no AVX2), it is still better to load a constant vector
5377   // from the constant pool and not to broadcast it from a scalar.
5378   // But override that restriction when optimizing for size.
5379   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5380   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5381     EVT CVT = Ld.getValueType();
5382     assert(!CVT.isVector() && "Must not broadcast a vector type");
5383
5384     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5385     // For size optimization, also splat v2f64 and v2i64, and for size opt
5386     // with AVX2, also splat i8 and i16.
5387     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5388     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5389         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5390       const Constant *C = nullptr;
5391       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5392         C = CI->getConstantIntValue();
5393       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5394         C = CF->getConstantFPValue();
5395
5396       assert(C && "Invalid constant type");
5397
5398       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5399       SDValue CP =
5400           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5401       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5402       Ld = DAG.getLoad(
5403           CVT, dl, DAG.getEntryNode(), CP,
5404           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5405           false, false, Alignment);
5406
5407       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5408     }
5409   }
5410
5411   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5412
5413   // Handle AVX2 in-register broadcasts.
5414   if (!IsLoad && Subtarget->hasInt256() &&
5415       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5416     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5417
5418   // The scalar source must be a normal load.
5419   if (!IsLoad)
5420     return SDValue();
5421
5422   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5423       (Subtarget->hasVLX() && ScalarSize == 64))
5424     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5425
5426   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5427   // double since there is no vbroadcastsd xmm
5428   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5429     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5430       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5431   }
5432
5433   // Unsupported broadcast.
5434   return SDValue();
5435 }
5436
5437 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5438 /// underlying vector and index.
5439 ///
5440 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5441 /// index.
5442 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5443                                          SDValue ExtIdx) {
5444   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5445   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5446     return Idx;
5447
5448   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5449   // lowered this:
5450   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5451   // to:
5452   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5453   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5454   //                           undef)
5455   //                       Constant<0>)
5456   // In this case the vector is the extract_subvector expression and the index
5457   // is 2, as specified by the shuffle.
5458   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5459   SDValue ShuffleVec = SVOp->getOperand(0);
5460   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5461   assert(ShuffleVecVT.getVectorElementType() ==
5462          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5463
5464   int ShuffleIdx = SVOp->getMaskElt(Idx);
5465   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5466     ExtractedFromVec = ShuffleVec;
5467     return ShuffleIdx;
5468   }
5469   return Idx;
5470 }
5471
5472 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5473   MVT VT = Op.getSimpleValueType();
5474
5475   // Skip if insert_vec_elt is not supported.
5476   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5477   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5478     return SDValue();
5479
5480   SDLoc DL(Op);
5481   unsigned NumElems = Op.getNumOperands();
5482
5483   SDValue VecIn1;
5484   SDValue VecIn2;
5485   SmallVector<unsigned, 4> InsertIndices;
5486   SmallVector<int, 8> Mask(NumElems, -1);
5487
5488   for (unsigned i = 0; i != NumElems; ++i) {
5489     unsigned Opc = Op.getOperand(i).getOpcode();
5490
5491     if (Opc == ISD::UNDEF)
5492       continue;
5493
5494     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5495       // Quit if more than 1 elements need inserting.
5496       if (InsertIndices.size() > 1)
5497         return SDValue();
5498
5499       InsertIndices.push_back(i);
5500       continue;
5501     }
5502
5503     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5504     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5505     // Quit if non-constant index.
5506     if (!isa<ConstantSDNode>(ExtIdx))
5507       return SDValue();
5508     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5509
5510     // Quit if extracted from vector of different type.
5511     if (ExtractedFromVec.getValueType() != VT)
5512       return SDValue();
5513
5514     if (!VecIn1.getNode())
5515       VecIn1 = ExtractedFromVec;
5516     else if (VecIn1 != ExtractedFromVec) {
5517       if (!VecIn2.getNode())
5518         VecIn2 = ExtractedFromVec;
5519       else if (VecIn2 != ExtractedFromVec)
5520         // Quit if more than 2 vectors to shuffle
5521         return SDValue();
5522     }
5523
5524     if (ExtractedFromVec == VecIn1)
5525       Mask[i] = Idx;
5526     else if (ExtractedFromVec == VecIn2)
5527       Mask[i] = Idx + NumElems;
5528   }
5529
5530   if (!VecIn1.getNode())
5531     return SDValue();
5532
5533   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5534   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5535   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5536     unsigned Idx = InsertIndices[i];
5537     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5538                      DAG.getIntPtrConstant(Idx, DL));
5539   }
5540
5541   return NV;
5542 }
5543
5544 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5545   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5546          Op.getScalarValueSizeInBits() == 1 &&
5547          "Can not convert non-constant vector");
5548   uint64_t Immediate = 0;
5549   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5550     SDValue In = Op.getOperand(idx);
5551     if (In.getOpcode() != ISD::UNDEF)
5552       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5553   }
5554   SDLoc dl(Op);
5555   MVT VT =
5556    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5557   return DAG.getConstant(Immediate, dl, VT);
5558 }
5559 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5560 SDValue
5561 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5562
5563   MVT VT = Op.getSimpleValueType();
5564   assert((VT.getVectorElementType() == MVT::i1) &&
5565          "Unexpected type in LowerBUILD_VECTORvXi1!");
5566
5567   SDLoc dl(Op);
5568   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5569     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5570     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5571     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5572   }
5573
5574   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5575     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5576     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5577     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5578   }
5579
5580   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5581     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5582     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5583       return DAG.getBitcast(VT, Imm);
5584     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5585     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5586                         DAG.getIntPtrConstant(0, dl));
5587   }
5588
5589   // Vector has one or more non-const elements
5590   uint64_t Immediate = 0;
5591   SmallVector<unsigned, 16> NonConstIdx;
5592   bool IsSplat = true;
5593   bool HasConstElts = false;
5594   int SplatIdx = -1;
5595   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5596     SDValue In = Op.getOperand(idx);
5597     if (In.getOpcode() == ISD::UNDEF)
5598       continue;
5599     if (!isa<ConstantSDNode>(In))
5600       NonConstIdx.push_back(idx);
5601     else {
5602       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5603       HasConstElts = true;
5604     }
5605     if (SplatIdx == -1)
5606       SplatIdx = idx;
5607     else if (In != Op.getOperand(SplatIdx))
5608       IsSplat = false;
5609   }
5610
5611   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5612   if (IsSplat)
5613     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5614                        DAG.getConstant(1, dl, VT),
5615                        DAG.getConstant(0, dl, VT));
5616
5617   // insert elements one by one
5618   SDValue DstVec;
5619   SDValue Imm;
5620   if (Immediate) {
5621     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5622     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5623   }
5624   else if (HasConstElts)
5625     Imm = DAG.getConstant(0, dl, VT);
5626   else
5627     Imm = DAG.getUNDEF(VT);
5628   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5629     DstVec = DAG.getBitcast(VT, Imm);
5630   else {
5631     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5632     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5633                          DAG.getIntPtrConstant(0, dl));
5634   }
5635
5636   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5637     unsigned InsertIdx = NonConstIdx[i];
5638     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5639                          Op.getOperand(InsertIdx),
5640                          DAG.getIntPtrConstant(InsertIdx, dl));
5641   }
5642   return DstVec;
5643 }
5644
5645 /// \brief Return true if \p N implements a horizontal binop and return the
5646 /// operands for the horizontal binop into V0 and V1.
5647 ///
5648 /// This is a helper function of LowerToHorizontalOp().
5649 /// This function checks that the build_vector \p N in input implements a
5650 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5651 /// operation to match.
5652 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5653 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5654 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5655 /// arithmetic sub.
5656 ///
5657 /// This function only analyzes elements of \p N whose indices are
5658 /// in range [BaseIdx, LastIdx).
5659 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5660                               SelectionDAG &DAG,
5661                               unsigned BaseIdx, unsigned LastIdx,
5662                               SDValue &V0, SDValue &V1) {
5663   EVT VT = N->getValueType(0);
5664
5665   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5666   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5667          "Invalid Vector in input!");
5668
5669   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5670   bool CanFold = true;
5671   unsigned ExpectedVExtractIdx = BaseIdx;
5672   unsigned NumElts = LastIdx - BaseIdx;
5673   V0 = DAG.getUNDEF(VT);
5674   V1 = DAG.getUNDEF(VT);
5675
5676   // Check if N implements a horizontal binop.
5677   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5678     SDValue Op = N->getOperand(i + BaseIdx);
5679
5680     // Skip UNDEFs.
5681     if (Op->getOpcode() == ISD::UNDEF) {
5682       // Update the expected vector extract index.
5683       if (i * 2 == NumElts)
5684         ExpectedVExtractIdx = BaseIdx;
5685       ExpectedVExtractIdx += 2;
5686       continue;
5687     }
5688
5689     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5690
5691     if (!CanFold)
5692       break;
5693
5694     SDValue Op0 = Op.getOperand(0);
5695     SDValue Op1 = Op.getOperand(1);
5696
5697     // Try to match the following pattern:
5698     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5699     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5700         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5701         Op0.getOperand(0) == Op1.getOperand(0) &&
5702         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5703         isa<ConstantSDNode>(Op1.getOperand(1)));
5704     if (!CanFold)
5705       break;
5706
5707     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5708     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5709
5710     if (i * 2 < NumElts) {
5711       if (V0.getOpcode() == ISD::UNDEF) {
5712         V0 = Op0.getOperand(0);
5713         if (V0.getValueType() != VT)
5714           return false;
5715       }
5716     } else {
5717       if (V1.getOpcode() == ISD::UNDEF) {
5718         V1 = Op0.getOperand(0);
5719         if (V1.getValueType() != VT)
5720           return false;
5721       }
5722       if (i * 2 == NumElts)
5723         ExpectedVExtractIdx = BaseIdx;
5724     }
5725
5726     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5727     if (I0 == ExpectedVExtractIdx)
5728       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5729     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5730       // Try to match the following dag sequence:
5731       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5732       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5733     } else
5734       CanFold = false;
5735
5736     ExpectedVExtractIdx += 2;
5737   }
5738
5739   return CanFold;
5740 }
5741
5742 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5743 /// a concat_vector.
5744 ///
5745 /// This is a helper function of LowerToHorizontalOp().
5746 /// This function expects two 256-bit vectors called V0 and V1.
5747 /// At first, each vector is split into two separate 128-bit vectors.
5748 /// Then, the resulting 128-bit vectors are used to implement two
5749 /// horizontal binary operations.
5750 ///
5751 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5752 ///
5753 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5754 /// the two new horizontal binop.
5755 /// When Mode is set, the first horizontal binop dag node would take as input
5756 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5757 /// horizontal binop dag node would take as input the lower 128-bit of V1
5758 /// and the upper 128-bit of V1.
5759 ///   Example:
5760 ///     HADD V0_LO, V0_HI
5761 ///     HADD V1_LO, V1_HI
5762 ///
5763 /// Otherwise, the first horizontal binop dag node takes as input the lower
5764 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5765 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5766 ///   Example:
5767 ///     HADD V0_LO, V1_LO
5768 ///     HADD V0_HI, V1_HI
5769 ///
5770 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5771 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5772 /// the upper 128-bits of the result.
5773 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5774                                      SDLoc DL, SelectionDAG &DAG,
5775                                      unsigned X86Opcode, bool Mode,
5776                                      bool isUndefLO, bool isUndefHI) {
5777   EVT VT = V0.getValueType();
5778   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5779          "Invalid nodes in input!");
5780
5781   unsigned NumElts = VT.getVectorNumElements();
5782   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5783   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5784   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5785   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5786   EVT NewVT = V0_LO.getValueType();
5787
5788   SDValue LO = DAG.getUNDEF(NewVT);
5789   SDValue HI = DAG.getUNDEF(NewVT);
5790
5791   if (Mode) {
5792     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5793     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5794       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5795     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5796       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5797   } else {
5798     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5799     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5800                        V1_LO->getOpcode() != ISD::UNDEF))
5801       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5802
5803     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5804                        V1_HI->getOpcode() != ISD::UNDEF))
5805       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5806   }
5807
5808   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5809 }
5810
5811 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5812 /// node.
5813 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5814                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5815   EVT VT = BV->getValueType(0);
5816   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5817       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5818     return SDValue();
5819
5820   SDLoc DL(BV);
5821   unsigned NumElts = VT.getVectorNumElements();
5822   SDValue InVec0 = DAG.getUNDEF(VT);
5823   SDValue InVec1 = DAG.getUNDEF(VT);
5824
5825   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5826           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5827
5828   // Odd-numbered elements in the input build vector are obtained from
5829   // adding two integer/float elements.
5830   // Even-numbered elements in the input build vector are obtained from
5831   // subtracting two integer/float elements.
5832   unsigned ExpectedOpcode = ISD::FSUB;
5833   unsigned NextExpectedOpcode = ISD::FADD;
5834   bool AddFound = false;
5835   bool SubFound = false;
5836
5837   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5838     SDValue Op = BV->getOperand(i);
5839
5840     // Skip 'undef' values.
5841     unsigned Opcode = Op.getOpcode();
5842     if (Opcode == ISD::UNDEF) {
5843       std::swap(ExpectedOpcode, NextExpectedOpcode);
5844       continue;
5845     }
5846
5847     // Early exit if we found an unexpected opcode.
5848     if (Opcode != ExpectedOpcode)
5849       return SDValue();
5850
5851     SDValue Op0 = Op.getOperand(0);
5852     SDValue Op1 = Op.getOperand(1);
5853
5854     // Try to match the following pattern:
5855     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5856     // Early exit if we cannot match that sequence.
5857     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5858         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5859         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5860         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5861         Op0.getOperand(1) != Op1.getOperand(1))
5862       return SDValue();
5863
5864     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5865     if (I0 != i)
5866       return SDValue();
5867
5868     // We found a valid add/sub node. Update the information accordingly.
5869     if (i & 1)
5870       AddFound = true;
5871     else
5872       SubFound = true;
5873
5874     // Update InVec0 and InVec1.
5875     if (InVec0.getOpcode() == ISD::UNDEF) {
5876       InVec0 = Op0.getOperand(0);
5877       if (InVec0.getValueType() != VT)
5878         return SDValue();
5879     }
5880     if (InVec1.getOpcode() == ISD::UNDEF) {
5881       InVec1 = Op1.getOperand(0);
5882       if (InVec1.getValueType() != VT)
5883         return SDValue();
5884     }
5885
5886     // Make sure that operands in input to each add/sub node always
5887     // come from a same pair of vectors.
5888     if (InVec0 != Op0.getOperand(0)) {
5889       if (ExpectedOpcode == ISD::FSUB)
5890         return SDValue();
5891
5892       // FADD is commutable. Try to commute the operands
5893       // and then test again.
5894       std::swap(Op0, Op1);
5895       if (InVec0 != Op0.getOperand(0))
5896         return SDValue();
5897     }
5898
5899     if (InVec1 != Op1.getOperand(0))
5900       return SDValue();
5901
5902     // Update the pair of expected opcodes.
5903     std::swap(ExpectedOpcode, NextExpectedOpcode);
5904   }
5905
5906   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5907   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5908       InVec1.getOpcode() != ISD::UNDEF)
5909     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5910
5911   return SDValue();
5912 }
5913
5914 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5915 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5916                                    const X86Subtarget *Subtarget,
5917                                    SelectionDAG &DAG) {
5918   EVT VT = BV->getValueType(0);
5919   unsigned NumElts = VT.getVectorNumElements();
5920   unsigned NumUndefsLO = 0;
5921   unsigned NumUndefsHI = 0;
5922   unsigned Half = NumElts/2;
5923
5924   // Count the number of UNDEF operands in the build_vector in input.
5925   for (unsigned i = 0, e = Half; i != e; ++i)
5926     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5927       NumUndefsLO++;
5928
5929   for (unsigned i = Half, e = NumElts; i != e; ++i)
5930     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5931       NumUndefsHI++;
5932
5933   // Early exit if this is either a build_vector of all UNDEFs or all the
5934   // operands but one are UNDEF.
5935   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5936     return SDValue();
5937
5938   SDLoc DL(BV);
5939   SDValue InVec0, InVec1;
5940   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5941     // Try to match an SSE3 float HADD/HSUB.
5942     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5943       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5944
5945     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5946       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5947   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5948     // Try to match an SSSE3 integer HADD/HSUB.
5949     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5950       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5951
5952     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5953       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5954   }
5955
5956   if (!Subtarget->hasAVX())
5957     return SDValue();
5958
5959   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5960     // Try to match an AVX horizontal add/sub of packed single/double
5961     // precision floating point values from 256-bit vectors.
5962     SDValue InVec2, InVec3;
5963     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5964         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5965         ((InVec0.getOpcode() == ISD::UNDEF ||
5966           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5967         ((InVec1.getOpcode() == ISD::UNDEF ||
5968           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5969       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5970
5971     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5972         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5973         ((InVec0.getOpcode() == ISD::UNDEF ||
5974           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5975         ((InVec1.getOpcode() == ISD::UNDEF ||
5976           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5977       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5978   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5979     // Try to match an AVX2 horizontal add/sub of signed integers.
5980     SDValue InVec2, InVec3;
5981     unsigned X86Opcode;
5982     bool CanFold = true;
5983
5984     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5985         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5986         ((InVec0.getOpcode() == ISD::UNDEF ||
5987           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5988         ((InVec1.getOpcode() == ISD::UNDEF ||
5989           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5990       X86Opcode = X86ISD::HADD;
5991     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5992         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5993         ((InVec0.getOpcode() == ISD::UNDEF ||
5994           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5995         ((InVec1.getOpcode() == ISD::UNDEF ||
5996           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5997       X86Opcode = X86ISD::HSUB;
5998     else
5999       CanFold = false;
6000
6001     if (CanFold) {
6002       // Fold this build_vector into a single horizontal add/sub.
6003       // Do this only if the target has AVX2.
6004       if (Subtarget->hasAVX2())
6005         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6006
6007       // Do not try to expand this build_vector into a pair of horizontal
6008       // add/sub if we can emit a pair of scalar add/sub.
6009       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6010         return SDValue();
6011
6012       // Convert this build_vector into a pair of horizontal binop followed by
6013       // a concat vector.
6014       bool isUndefLO = NumUndefsLO == Half;
6015       bool isUndefHI = NumUndefsHI == Half;
6016       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6017                                    isUndefLO, isUndefHI);
6018     }
6019   }
6020
6021   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6022        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6023     unsigned X86Opcode;
6024     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6025       X86Opcode = X86ISD::HADD;
6026     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6027       X86Opcode = X86ISD::HSUB;
6028     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6029       X86Opcode = X86ISD::FHADD;
6030     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6031       X86Opcode = X86ISD::FHSUB;
6032     else
6033       return SDValue();
6034
6035     // Don't try to expand this build_vector into a pair of horizontal add/sub
6036     // if we can simply emit a pair of scalar add/sub.
6037     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6038       return SDValue();
6039
6040     // Convert this build_vector into two horizontal add/sub followed by
6041     // a concat vector.
6042     bool isUndefLO = NumUndefsLO == Half;
6043     bool isUndefHI = NumUndefsHI == Half;
6044     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6045                                  isUndefLO, isUndefHI);
6046   }
6047
6048   return SDValue();
6049 }
6050
6051 SDValue
6052 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6053   SDLoc dl(Op);
6054
6055   MVT VT = Op.getSimpleValueType();
6056   MVT ExtVT = VT.getVectorElementType();
6057   unsigned NumElems = Op.getNumOperands();
6058
6059   // Generate vectors for predicate vectors.
6060   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6061     return LowerBUILD_VECTORvXi1(Op, DAG);
6062
6063   // Vectors containing all zeros can be matched by pxor and xorps later
6064   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6065     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6066     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6067     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6068       return Op;
6069
6070     return getZeroVector(VT, Subtarget, DAG, dl);
6071   }
6072
6073   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6074   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6075   // vpcmpeqd on 256-bit vectors.
6076   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6077     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6078       return Op;
6079
6080     if (!VT.is512BitVector())
6081       return getOnesVector(VT, Subtarget, DAG, dl);
6082   }
6083
6084   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6085   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6086     return AddSub;
6087   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6088     return HorizontalOp;
6089   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6090     return Broadcast;
6091
6092   unsigned EVTBits = ExtVT.getSizeInBits();
6093
6094   unsigned NumZero  = 0;
6095   unsigned NumNonZero = 0;
6096   unsigned NonZeros = 0;
6097   bool IsAllConstants = true;
6098   SmallSet<SDValue, 8> Values;
6099   for (unsigned i = 0; i < NumElems; ++i) {
6100     SDValue Elt = Op.getOperand(i);
6101     if (Elt.getOpcode() == ISD::UNDEF)
6102       continue;
6103     Values.insert(Elt);
6104     if (Elt.getOpcode() != ISD::Constant &&
6105         Elt.getOpcode() != ISD::ConstantFP)
6106       IsAllConstants = false;
6107     if (X86::isZeroNode(Elt))
6108       NumZero++;
6109     else {
6110       NonZeros |= (1 << i);
6111       NumNonZero++;
6112     }
6113   }
6114
6115   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6116   if (NumNonZero == 0)
6117     return DAG.getUNDEF(VT);
6118
6119   // Special case for single non-zero, non-undef, element.
6120   if (NumNonZero == 1) {
6121     unsigned Idx = countTrailingZeros(NonZeros);
6122     SDValue Item = Op.getOperand(Idx);
6123
6124     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6125     // the value are obviously zero, truncate the value to i32 and do the
6126     // insertion that way.  Only do this if the value is non-constant or if the
6127     // value is a constant being inserted into element 0.  It is cheaper to do
6128     // a constant pool load than it is to do a movd + shuffle.
6129     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6130         (!IsAllConstants || Idx == 0)) {
6131       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6132         // Handle SSE only.
6133         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6134         EVT VecVT = MVT::v4i32;
6135
6136         // Truncate the value (which may itself be a constant) to i32, and
6137         // convert it to a vector with movd (S2V+shuffle to zero extend).
6138         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6139         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6140         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6141                                       Item, Idx * 2, true, Subtarget, DAG));
6142       }
6143     }
6144
6145     // If we have a constant or non-constant insertion into the low element of
6146     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6147     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6148     // depending on what the source datatype is.
6149     if (Idx == 0) {
6150       if (NumZero == 0)
6151         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6152
6153       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6154           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6155         if (VT.is512BitVector()) {
6156           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6157           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6158                              Item, DAG.getIntPtrConstant(0, dl));
6159         }
6160         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6161                "Expected an SSE value type!");
6162         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6163         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6164         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6165       }
6166
6167       // We can't directly insert an i8 or i16 into a vector, so zero extend
6168       // it to i32 first.
6169       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6170         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6171         if (VT.is256BitVector()) {
6172           if (Subtarget->hasAVX()) {
6173             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6174             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6175           } else {
6176             // Without AVX, we need to extend to a 128-bit vector and then
6177             // insert into the 256-bit vector.
6178             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6179             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6180             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6181           }
6182         } else {
6183           assert(VT.is128BitVector() && "Expected an SSE value type!");
6184           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6185           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6186         }
6187         return DAG.getBitcast(VT, Item);
6188       }
6189     }
6190
6191     // Is it a vector logical left shift?
6192     if (NumElems == 2 && Idx == 1 &&
6193         X86::isZeroNode(Op.getOperand(0)) &&
6194         !X86::isZeroNode(Op.getOperand(1))) {
6195       unsigned NumBits = VT.getSizeInBits();
6196       return getVShift(true, VT,
6197                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6198                                    VT, Op.getOperand(1)),
6199                        NumBits/2, DAG, *this, dl);
6200     }
6201
6202     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6203       return SDValue();
6204
6205     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6206     // is a non-constant being inserted into an element other than the low one,
6207     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6208     // movd/movss) to move this into the low element, then shuffle it into
6209     // place.
6210     if (EVTBits == 32) {
6211       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6212       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6213     }
6214   }
6215
6216   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6217   if (Values.size() == 1) {
6218     if (EVTBits == 32) {
6219       // Instead of a shuffle like this:
6220       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6221       // Check if it's possible to issue this instead.
6222       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6223       unsigned Idx = countTrailingZeros(NonZeros);
6224       SDValue Item = Op.getOperand(Idx);
6225       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6226         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6227     }
6228     return SDValue();
6229   }
6230
6231   // A vector full of immediates; various special cases are already
6232   // handled, so this is best done with a single constant-pool load.
6233   if (IsAllConstants)
6234     return SDValue();
6235
6236   // For AVX-length vectors, see if we can use a vector load to get all of the
6237   // elements, otherwise build the individual 128-bit pieces and use
6238   // shuffles to put them in place.
6239   if (VT.is256BitVector() || VT.is512BitVector()) {
6240     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6241
6242     // Check for a build vector of consecutive loads.
6243     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6244       return LD;
6245
6246     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6247
6248     // Build both the lower and upper subvector.
6249     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6250                                 makeArrayRef(&V[0], NumElems/2));
6251     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6252                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6253
6254     // Recreate the wider vector with the lower and upper part.
6255     if (VT.is256BitVector())
6256       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6257     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6258   }
6259
6260   // Let legalizer expand 2-wide build_vectors.
6261   if (EVTBits == 64) {
6262     if (NumNonZero == 1) {
6263       // One half is zero or undef.
6264       unsigned Idx = countTrailingZeros(NonZeros);
6265       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6266                                  Op.getOperand(Idx));
6267       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6268     }
6269     return SDValue();
6270   }
6271
6272   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6273   if (EVTBits == 8 && NumElems == 16)
6274     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6275                                         Subtarget, *this))
6276       return V;
6277
6278   if (EVTBits == 16 && NumElems == 8)
6279     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6280                                       Subtarget, *this))
6281       return V;
6282
6283   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6284   if (EVTBits == 32 && NumElems == 4)
6285     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6286       return V;
6287
6288   // If element VT is == 32 bits, turn it into a number of shuffles.
6289   SmallVector<SDValue, 8> V(NumElems);
6290   if (NumElems == 4 && NumZero > 0) {
6291     for (unsigned i = 0; i < 4; ++i) {
6292       bool isZero = !(NonZeros & (1 << i));
6293       if (isZero)
6294         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6295       else
6296         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6297     }
6298
6299     for (unsigned i = 0; i < 2; ++i) {
6300       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6301         default: break;
6302         case 0:
6303           V[i] = V[i*2];  // Must be a zero vector.
6304           break;
6305         case 1:
6306           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6307           break;
6308         case 2:
6309           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6310           break;
6311         case 3:
6312           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6313           break;
6314       }
6315     }
6316
6317     bool Reverse1 = (NonZeros & 0x3) == 2;
6318     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6319     int MaskVec[] = {
6320       Reverse1 ? 1 : 0,
6321       Reverse1 ? 0 : 1,
6322       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6323       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6324     };
6325     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6326   }
6327
6328   if (Values.size() > 1 && VT.is128BitVector()) {
6329     // Check for a build vector of consecutive loads.
6330     for (unsigned i = 0; i < NumElems; ++i)
6331       V[i] = Op.getOperand(i);
6332
6333     // Check for elements which are consecutive loads.
6334     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6335       return LD;
6336
6337     // Check for a build vector from mostly shuffle plus few inserting.
6338     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6339       return Sh;
6340
6341     // For SSE 4.1, use insertps to put the high elements into the low element.
6342     if (Subtarget->hasSSE41()) {
6343       SDValue Result;
6344       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6345         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6346       else
6347         Result = DAG.getUNDEF(VT);
6348
6349       for (unsigned i = 1; i < NumElems; ++i) {
6350         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6351         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6352                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6353       }
6354       return Result;
6355     }
6356
6357     // Otherwise, expand into a number of unpckl*, start by extending each of
6358     // our (non-undef) elements to the full vector width with the element in the
6359     // bottom slot of the vector (which generates no code for SSE).
6360     for (unsigned i = 0; i < NumElems; ++i) {
6361       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6362         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6363       else
6364         V[i] = DAG.getUNDEF(VT);
6365     }
6366
6367     // Next, we iteratively mix elements, e.g. for v4f32:
6368     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6369     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6370     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6371     unsigned EltStride = NumElems >> 1;
6372     while (EltStride != 0) {
6373       for (unsigned i = 0; i < EltStride; ++i) {
6374         // If V[i+EltStride] is undef and this is the first round of mixing,
6375         // then it is safe to just drop this shuffle: V[i] is already in the
6376         // right place, the one element (since it's the first round) being
6377         // inserted as undef can be dropped.  This isn't safe for successive
6378         // rounds because they will permute elements within both vectors.
6379         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6380             EltStride == NumElems/2)
6381           continue;
6382
6383         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6384       }
6385       EltStride >>= 1;
6386     }
6387     return V[0];
6388   }
6389   return SDValue();
6390 }
6391
6392 // 256-bit AVX can use the vinsertf128 instruction
6393 // to create 256-bit vectors from two other 128-bit ones.
6394 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6395   SDLoc dl(Op);
6396   MVT ResVT = Op.getSimpleValueType();
6397
6398   assert((ResVT.is256BitVector() ||
6399           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6400
6401   SDValue V1 = Op.getOperand(0);
6402   SDValue V2 = Op.getOperand(1);
6403   unsigned NumElems = ResVT.getVectorNumElements();
6404   if (ResVT.is256BitVector())
6405     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6406
6407   if (Op.getNumOperands() == 4) {
6408     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6409                                 ResVT.getVectorNumElements()/2);
6410     SDValue V3 = Op.getOperand(2);
6411     SDValue V4 = Op.getOperand(3);
6412     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6413       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6414   }
6415   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6416 }
6417
6418 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6419                                        const X86Subtarget *Subtarget,
6420                                        SelectionDAG & DAG) {
6421   SDLoc dl(Op);
6422   MVT ResVT = Op.getSimpleValueType();
6423   unsigned NumOfOperands = Op.getNumOperands();
6424
6425   assert(isPowerOf2_32(NumOfOperands) &&
6426          "Unexpected number of operands in CONCAT_VECTORS");
6427
6428   if (NumOfOperands > 2) {
6429     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6430                                   ResVT.getVectorNumElements()/2);
6431     SmallVector<SDValue, 2> Ops;
6432     for (unsigned i = 0; i < NumOfOperands/2; i++)
6433       Ops.push_back(Op.getOperand(i));
6434     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6435     Ops.clear();
6436     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6437       Ops.push_back(Op.getOperand(i));
6438     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6439     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6440   }
6441
6442   SDValue V1 = Op.getOperand(0);
6443   SDValue V2 = Op.getOperand(1);
6444   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6445   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6446
6447   if (IsZeroV1 && IsZeroV2)
6448     return getZeroVector(ResVT, Subtarget, DAG, dl);
6449
6450   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6451   SDValue Undef = DAG.getUNDEF(ResVT);
6452   unsigned NumElems = ResVT.getVectorNumElements();
6453   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6454
6455   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6456   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6457   if (IsZeroV1)
6458     return V2;
6459
6460   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6461   // Zero the upper bits of V1
6462   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6463   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6464   if (IsZeroV2)
6465     return V1;
6466   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6467 }
6468
6469 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6470                                    const X86Subtarget *Subtarget,
6471                                    SelectionDAG &DAG) {
6472   MVT VT = Op.getSimpleValueType();
6473   if (VT.getVectorElementType() == MVT::i1)
6474     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6475
6476   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6477          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6478           Op.getNumOperands() == 4)));
6479
6480   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6481   // from two other 128-bit ones.
6482
6483   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6484   return LowerAVXCONCAT_VECTORS(Op, DAG);
6485 }
6486
6487
6488 //===----------------------------------------------------------------------===//
6489 // Vector shuffle lowering
6490 //
6491 // This is an experimental code path for lowering vector shuffles on x86. It is
6492 // designed to handle arbitrary vector shuffles and blends, gracefully
6493 // degrading performance as necessary. It works hard to recognize idiomatic
6494 // shuffles and lower them to optimal instruction patterns without leaving
6495 // a framework that allows reasonably efficient handling of all vector shuffle
6496 // patterns.
6497 //===----------------------------------------------------------------------===//
6498
6499 /// \brief Tiny helper function to identify a no-op mask.
6500 ///
6501 /// This is a somewhat boring predicate function. It checks whether the mask
6502 /// array input, which is assumed to be a single-input shuffle mask of the kind
6503 /// used by the X86 shuffle instructions (not a fully general
6504 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6505 /// in-place shuffle are 'no-op's.
6506 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6507   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6508     if (Mask[i] != -1 && Mask[i] != i)
6509       return false;
6510   return true;
6511 }
6512
6513 /// \brief Helper function to classify a mask as a single-input mask.
6514 ///
6515 /// This isn't a generic single-input test because in the vector shuffle
6516 /// lowering we canonicalize single inputs to be the first input operand. This
6517 /// means we can more quickly test for a single input by only checking whether
6518 /// an input from the second operand exists. We also assume that the size of
6519 /// mask corresponds to the size of the input vectors which isn't true in the
6520 /// fully general case.
6521 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6522   for (int M : Mask)
6523     if (M >= (int)Mask.size())
6524       return false;
6525   return true;
6526 }
6527
6528 /// \brief Test whether there are elements crossing 128-bit lanes in this
6529 /// shuffle mask.
6530 ///
6531 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6532 /// and we routinely test for these.
6533 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6534   int LaneSize = 128 / VT.getScalarSizeInBits();
6535   int Size = Mask.size();
6536   for (int i = 0; i < Size; ++i)
6537     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6538       return true;
6539   return false;
6540 }
6541
6542 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6543 ///
6544 /// This checks a shuffle mask to see if it is performing the same
6545 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6546 /// that it is also not lane-crossing. It may however involve a blend from the
6547 /// same lane of a second vector.
6548 ///
6549 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6550 /// non-trivial to compute in the face of undef lanes. The representation is
6551 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6552 /// entries from both V1 and V2 inputs to the wider mask.
6553 static bool
6554 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6555                                 SmallVectorImpl<int> &RepeatedMask) {
6556   int LaneSize = 128 / VT.getScalarSizeInBits();
6557   RepeatedMask.resize(LaneSize, -1);
6558   int Size = Mask.size();
6559   for (int i = 0; i < Size; ++i) {
6560     if (Mask[i] < 0)
6561       continue;
6562     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6563       // This entry crosses lanes, so there is no way to model this shuffle.
6564       return false;
6565
6566     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6567     if (RepeatedMask[i % LaneSize] == -1)
6568       // This is the first non-undef entry in this slot of a 128-bit lane.
6569       RepeatedMask[i % LaneSize] =
6570           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6571     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6572       // Found a mismatch with the repeated mask.
6573       return false;
6574   }
6575   return true;
6576 }
6577
6578 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6579 /// arguments.
6580 ///
6581 /// This is a fast way to test a shuffle mask against a fixed pattern:
6582 ///
6583 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6584 ///
6585 /// It returns true if the mask is exactly as wide as the argument list, and
6586 /// each element of the mask is either -1 (signifying undef) or the value given
6587 /// in the argument.
6588 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6589                                 ArrayRef<int> ExpectedMask) {
6590   if (Mask.size() != ExpectedMask.size())
6591     return false;
6592
6593   int Size = Mask.size();
6594
6595   // If the values are build vectors, we can look through them to find
6596   // equivalent inputs that make the shuffles equivalent.
6597   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6598   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6599
6600   for (int i = 0; i < Size; ++i)
6601     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6602       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6603       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6604       if (!MaskBV || !ExpectedBV ||
6605           MaskBV->getOperand(Mask[i] % Size) !=
6606               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6607         return false;
6608     }
6609
6610   return true;
6611 }
6612
6613 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6614 ///
6615 /// This helper function produces an 8-bit shuffle immediate corresponding to
6616 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6617 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6618 /// example.
6619 ///
6620 /// NB: We rely heavily on "undef" masks preserving the input lane.
6621 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6622                                           SelectionDAG &DAG) {
6623   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6624   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6625   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6626   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6627   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6628
6629   unsigned Imm = 0;
6630   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6631   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6632   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6633   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6634   return DAG.getConstant(Imm, DL, MVT::i8);
6635 }
6636
6637 /// \brief Compute whether each element of a shuffle is zeroable.
6638 ///
6639 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6640 /// Either it is an undef element in the shuffle mask, the element of the input
6641 /// referenced is undef, or the element of the input referenced is known to be
6642 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6643 /// as many lanes with this technique as possible to simplify the remaining
6644 /// shuffle.
6645 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6646                                                      SDValue V1, SDValue V2) {
6647   SmallBitVector Zeroable(Mask.size(), false);
6648
6649   while (V1.getOpcode() == ISD::BITCAST)
6650     V1 = V1->getOperand(0);
6651   while (V2.getOpcode() == ISD::BITCAST)
6652     V2 = V2->getOperand(0);
6653
6654   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6655   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6656
6657   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6658     int M = Mask[i];
6659     // Handle the easy cases.
6660     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6661       Zeroable[i] = true;
6662       continue;
6663     }
6664
6665     // If this is an index into a build_vector node (which has the same number
6666     // of elements), dig out the input value and use it.
6667     SDValue V = M < Size ? V1 : V2;
6668     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6669       continue;
6670
6671     SDValue Input = V.getOperand(M % Size);
6672     // The UNDEF opcode check really should be dead code here, but not quite
6673     // worth asserting on (it isn't invalid, just unexpected).
6674     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6675       Zeroable[i] = true;
6676   }
6677
6678   return Zeroable;
6679 }
6680
6681 // X86 has dedicated unpack instructions that can handle specific blend
6682 // operations: UNPCKH and UNPCKL.
6683 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6684                                            SDValue V1, SDValue V2,
6685                                            SelectionDAG &DAG) {
6686   int NumElts = VT.getVectorNumElements();
6687   bool Unpckl = true;
6688   bool Unpckh = true;
6689   bool UnpcklSwapped = true;
6690   bool UnpckhSwapped = true;
6691   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6692
6693   for (int i = 0; i < NumElts; ++i) {
6694     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6695
6696     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6697     int HiPos = LoPos + NumEltsInLane / 2;
6698     int LoPosSwapped = (LoPos + NumElts) % (NumElts * 2);
6699     int HiPosSwapped = (HiPos + NumElts) % (NumElts * 2);
6700
6701     if (Mask[i] == -1)
6702       continue;
6703     if (Mask[i] != LoPos)
6704       Unpckl = false;
6705     if (Mask[i] != HiPos)
6706       Unpckh = false;
6707     if (Mask[i] != LoPosSwapped)
6708       UnpcklSwapped = false;
6709     if (Mask[i] != HiPosSwapped)
6710       UnpckhSwapped = false;
6711     if (!Unpckl && !Unpckh && !UnpcklSwapped && !UnpckhSwapped)
6712       return SDValue();
6713   }
6714   if (Unpckl)
6715     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6716   if (Unpckh)
6717     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6718   if (UnpcklSwapped)
6719     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6720   if (UnpckhSwapped)
6721     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6722
6723   llvm_unreachable("Unexpected result of UNPCK mask analysis");
6724   return SDValue();
6725 }
6726
6727 /// \brief Try to emit a bitmask instruction for a shuffle.
6728 ///
6729 /// This handles cases where we can model a blend exactly as a bitmask due to
6730 /// one of the inputs being zeroable.
6731 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6732                                            SDValue V2, ArrayRef<int> Mask,
6733                                            SelectionDAG &DAG) {
6734   MVT EltVT = VT.getScalarType();
6735   int NumEltBits = EltVT.getSizeInBits();
6736   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6737   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6738   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6739                                     IntEltVT);
6740   if (EltVT.isFloatingPoint()) {
6741     Zero = DAG.getBitcast(EltVT, Zero);
6742     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6743   }
6744   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6745   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6746   SDValue V;
6747   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6748     if (Zeroable[i])
6749       continue;
6750     if (Mask[i] % Size != i)
6751       return SDValue(); // Not a blend.
6752     if (!V)
6753       V = Mask[i] < Size ? V1 : V2;
6754     else if (V != (Mask[i] < Size ? V1 : V2))
6755       return SDValue(); // Can only let one input through the mask.
6756
6757     VMaskOps[i] = AllOnes;
6758   }
6759   if (!V)
6760     return SDValue(); // No non-zeroable elements!
6761
6762   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6763   V = DAG.getNode(VT.isFloatingPoint()
6764                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6765                   DL, VT, V, VMask);
6766   return V;
6767 }
6768
6769 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6770 ///
6771 /// This is used as a fallback approach when first class blend instructions are
6772 /// unavailable. Currently it is only suitable for integer vectors, but could
6773 /// be generalized for floating point vectors if desirable.
6774 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6775                                             SDValue V2, ArrayRef<int> Mask,
6776                                             SelectionDAG &DAG) {
6777   assert(VT.isInteger() && "Only supports integer vector types!");
6778   MVT EltVT = VT.getScalarType();
6779   int NumEltBits = EltVT.getSizeInBits();
6780   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6781   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6782                                     EltVT);
6783   SmallVector<SDValue, 16> MaskOps;
6784   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6785     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6786       return SDValue(); // Shuffled input!
6787     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6788   }
6789
6790   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6791   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6792   // We have to cast V2 around.
6793   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6794   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6795                                       DAG.getBitcast(MaskVT, V1Mask),
6796                                       DAG.getBitcast(MaskVT, V2)));
6797   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6798 }
6799
6800 /// \brief Try to emit a blend instruction for a shuffle.
6801 ///
6802 /// This doesn't do any checks for the availability of instructions for blending
6803 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6804 /// be matched in the backend with the type given. What it does check for is
6805 /// that the shuffle mask is in fact a blend.
6806 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6807                                          SDValue V2, ArrayRef<int> Mask,
6808                                          const X86Subtarget *Subtarget,
6809                                          SelectionDAG &DAG) {
6810   unsigned BlendMask = 0;
6811   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6812     if (Mask[i] >= Size) {
6813       if (Mask[i] != i + Size)
6814         return SDValue(); // Shuffled V2 input!
6815       BlendMask |= 1u << i;
6816       continue;
6817     }
6818     if (Mask[i] >= 0 && Mask[i] != i)
6819       return SDValue(); // Shuffled V1 input!
6820   }
6821   switch (VT.SimpleTy) {
6822   case MVT::v2f64:
6823   case MVT::v4f32:
6824   case MVT::v4f64:
6825   case MVT::v8f32:
6826     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6827                        DAG.getConstant(BlendMask, DL, MVT::i8));
6828
6829   case MVT::v4i64:
6830   case MVT::v8i32:
6831     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6832     // FALLTHROUGH
6833   case MVT::v2i64:
6834   case MVT::v4i32:
6835     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6836     // that instruction.
6837     if (Subtarget->hasAVX2()) {
6838       // Scale the blend by the number of 32-bit dwords per element.
6839       int Scale =  VT.getScalarSizeInBits() / 32;
6840       BlendMask = 0;
6841       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6842         if (Mask[i] >= Size)
6843           for (int j = 0; j < Scale; ++j)
6844             BlendMask |= 1u << (i * Scale + j);
6845
6846       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6847       V1 = DAG.getBitcast(BlendVT, V1);
6848       V2 = DAG.getBitcast(BlendVT, V2);
6849       return DAG.getBitcast(
6850           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6851                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6852     }
6853     // FALLTHROUGH
6854   case MVT::v8i16: {
6855     // For integer shuffles we need to expand the mask and cast the inputs to
6856     // v8i16s prior to blending.
6857     int Scale = 8 / VT.getVectorNumElements();
6858     BlendMask = 0;
6859     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6860       if (Mask[i] >= Size)
6861         for (int j = 0; j < Scale; ++j)
6862           BlendMask |= 1u << (i * Scale + j);
6863
6864     V1 = DAG.getBitcast(MVT::v8i16, V1);
6865     V2 = DAG.getBitcast(MVT::v8i16, V2);
6866     return DAG.getBitcast(VT,
6867                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6868                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6869   }
6870
6871   case MVT::v16i16: {
6872     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6873     SmallVector<int, 8> RepeatedMask;
6874     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6875       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6876       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6877       BlendMask = 0;
6878       for (int i = 0; i < 8; ++i)
6879         if (RepeatedMask[i] >= 16)
6880           BlendMask |= 1u << i;
6881       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6882                          DAG.getConstant(BlendMask, DL, MVT::i8));
6883     }
6884   }
6885     // FALLTHROUGH
6886   case MVT::v16i8:
6887   case MVT::v32i8: {
6888     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6889            "256-bit byte-blends require AVX2 support!");
6890
6891     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6892     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6893       return Masked;
6894
6895     // Scale the blend by the number of bytes per element.
6896     int Scale = VT.getScalarSizeInBits() / 8;
6897
6898     // This form of blend is always done on bytes. Compute the byte vector
6899     // type.
6900     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6901
6902     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6903     // mix of LLVM's code generator and the x86 backend. We tell the code
6904     // generator that boolean values in the elements of an x86 vector register
6905     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6906     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6907     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6908     // of the element (the remaining are ignored) and 0 in that high bit would
6909     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6910     // the LLVM model for boolean values in vector elements gets the relevant
6911     // bit set, it is set backwards and over constrained relative to x86's
6912     // actual model.
6913     SmallVector<SDValue, 32> VSELECTMask;
6914     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6915       for (int j = 0; j < Scale; ++j)
6916         VSELECTMask.push_back(
6917             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6918                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6919                                           MVT::i8));
6920
6921     V1 = DAG.getBitcast(BlendVT, V1);
6922     V2 = DAG.getBitcast(BlendVT, V2);
6923     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6924                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6925                                                       BlendVT, VSELECTMask),
6926                                           V1, V2));
6927   }
6928
6929   default:
6930     llvm_unreachable("Not a supported integer vector type!");
6931   }
6932 }
6933
6934 /// \brief Try to lower as a blend of elements from two inputs followed by
6935 /// a single-input permutation.
6936 ///
6937 /// This matches the pattern where we can blend elements from two inputs and
6938 /// then reduce the shuffle to a single-input permutation.
6939 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6940                                                    SDValue V2,
6941                                                    ArrayRef<int> Mask,
6942                                                    SelectionDAG &DAG) {
6943   // We build up the blend mask while checking whether a blend is a viable way
6944   // to reduce the shuffle.
6945   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6946   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6947
6948   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6949     if (Mask[i] < 0)
6950       continue;
6951
6952     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6953
6954     if (BlendMask[Mask[i] % Size] == -1)
6955       BlendMask[Mask[i] % Size] = Mask[i];
6956     else if (BlendMask[Mask[i] % Size] != Mask[i])
6957       return SDValue(); // Can't blend in the needed input!
6958
6959     PermuteMask[i] = Mask[i] % Size;
6960   }
6961
6962   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6963   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6964 }
6965
6966 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6967 /// blends and permutes.
6968 ///
6969 /// This matches the extremely common pattern for handling combined
6970 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6971 /// operations. It will try to pick the best arrangement of shuffles and
6972 /// blends.
6973 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6974                                                           SDValue V1,
6975                                                           SDValue V2,
6976                                                           ArrayRef<int> Mask,
6977                                                           SelectionDAG &DAG) {
6978   // Shuffle the input elements into the desired positions in V1 and V2 and
6979   // blend them together.
6980   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6981   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6982   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6983   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6984     if (Mask[i] >= 0 && Mask[i] < Size) {
6985       V1Mask[i] = Mask[i];
6986       BlendMask[i] = i;
6987     } else if (Mask[i] >= Size) {
6988       V2Mask[i] = Mask[i] - Size;
6989       BlendMask[i] = i + Size;
6990     }
6991
6992   // Try to lower with the simpler initial blend strategy unless one of the
6993   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6994   // shuffle may be able to fold with a load or other benefit. However, when
6995   // we'll have to do 2x as many shuffles in order to achieve this, blending
6996   // first is a better strategy.
6997   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6998     if (SDValue BlendPerm =
6999             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7000       return BlendPerm;
7001
7002   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7003   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7004   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7005 }
7006
7007 /// \brief Try to lower a vector shuffle as a byte rotation.
7008 ///
7009 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7010 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7011 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7012 /// try to generically lower a vector shuffle through such an pattern. It
7013 /// does not check for the profitability of lowering either as PALIGNR or
7014 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7015 /// This matches shuffle vectors that look like:
7016 ///
7017 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7018 ///
7019 /// Essentially it concatenates V1 and V2, shifts right by some number of
7020 /// elements, and takes the low elements as the result. Note that while this is
7021 /// specified as a *right shift* because x86 is little-endian, it is a *left
7022 /// rotate* of the vector lanes.
7023 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7024                                               SDValue V2,
7025                                               ArrayRef<int> Mask,
7026                                               const X86Subtarget *Subtarget,
7027                                               SelectionDAG &DAG) {
7028   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7029
7030   int NumElts = Mask.size();
7031   int NumLanes = VT.getSizeInBits() / 128;
7032   int NumLaneElts = NumElts / NumLanes;
7033
7034   // We need to detect various ways of spelling a rotation:
7035   //   [11, 12, 13, 14, 15,  0,  1,  2]
7036   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7037   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7038   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7039   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7040   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7041   int Rotation = 0;
7042   SDValue Lo, Hi;
7043   for (int l = 0; l < NumElts; l += NumLaneElts) {
7044     for (int i = 0; i < NumLaneElts; ++i) {
7045       if (Mask[l + i] == -1)
7046         continue;
7047       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7048
7049       // Get the mod-Size index and lane correct it.
7050       int LaneIdx = (Mask[l + i] % NumElts) - l;
7051       // Make sure it was in this lane.
7052       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7053         return SDValue();
7054
7055       // Determine where a rotated vector would have started.
7056       int StartIdx = i - LaneIdx;
7057       if (StartIdx == 0)
7058         // The identity rotation isn't interesting, stop.
7059         return SDValue();
7060
7061       // If we found the tail of a vector the rotation must be the missing
7062       // front. If we found the head of a vector, it must be how much of the
7063       // head.
7064       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7065
7066       if (Rotation == 0)
7067         Rotation = CandidateRotation;
7068       else if (Rotation != CandidateRotation)
7069         // The rotations don't match, so we can't match this mask.
7070         return SDValue();
7071
7072       // Compute which value this mask is pointing at.
7073       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7074
7075       // Compute which of the two target values this index should be assigned
7076       // to. This reflects whether the high elements are remaining or the low
7077       // elements are remaining.
7078       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7079
7080       // Either set up this value if we've not encountered it before, or check
7081       // that it remains consistent.
7082       if (!TargetV)
7083         TargetV = MaskV;
7084       else if (TargetV != MaskV)
7085         // This may be a rotation, but it pulls from the inputs in some
7086         // unsupported interleaving.
7087         return SDValue();
7088     }
7089   }
7090
7091   // Check that we successfully analyzed the mask, and normalize the results.
7092   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7093   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7094   if (!Lo)
7095     Lo = Hi;
7096   else if (!Hi)
7097     Hi = Lo;
7098
7099   // The actual rotate instruction rotates bytes, so we need to scale the
7100   // rotation based on how many bytes are in the vector lane.
7101   int Scale = 16 / NumLaneElts;
7102
7103   // SSSE3 targets can use the palignr instruction.
7104   if (Subtarget->hasSSSE3()) {
7105     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7106     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7107     Lo = DAG.getBitcast(AlignVT, Lo);
7108     Hi = DAG.getBitcast(AlignVT, Hi);
7109
7110     return DAG.getBitcast(
7111         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7112                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7113   }
7114
7115   assert(VT.getSizeInBits() == 128 &&
7116          "Rotate-based lowering only supports 128-bit lowering!");
7117   assert(Mask.size() <= 16 &&
7118          "Can shuffle at most 16 bytes in a 128-bit vector!");
7119
7120   // Default SSE2 implementation
7121   int LoByteShift = 16 - Rotation * Scale;
7122   int HiByteShift = Rotation * Scale;
7123
7124   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7125   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7126   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7127
7128   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7129                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7130   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7131                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7132   return DAG.getBitcast(VT,
7133                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7134 }
7135
7136 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7137 ///
7138 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7139 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7140 /// matches elements from one of the input vectors shuffled to the left or
7141 /// right with zeroable elements 'shifted in'. It handles both the strictly
7142 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7143 /// quad word lane.
7144 ///
7145 /// PSHL : (little-endian) left bit shift.
7146 /// [ zz, 0, zz,  2 ]
7147 /// [ -1, 4, zz, -1 ]
7148 /// PSRL : (little-endian) right bit shift.
7149 /// [  1, zz,  3, zz]
7150 /// [ -1, -1,  7, zz]
7151 /// PSLLDQ : (little-endian) left byte shift
7152 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7153 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7154 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7155 /// PSRLDQ : (little-endian) right byte shift
7156 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7157 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7158 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7159 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7160                                          SDValue V2, ArrayRef<int> Mask,
7161                                          SelectionDAG &DAG) {
7162   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7163
7164   int Size = Mask.size();
7165   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7166
7167   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7168     for (int i = 0; i < Size; i += Scale)
7169       for (int j = 0; j < Shift; ++j)
7170         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7171           return false;
7172
7173     return true;
7174   };
7175
7176   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7177     for (int i = 0; i != Size; i += Scale) {
7178       unsigned Pos = Left ? i + Shift : i;
7179       unsigned Low = Left ? i : i + Shift;
7180       unsigned Len = Scale - Shift;
7181       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7182                                       Low + (V == V1 ? 0 : Size)))
7183         return SDValue();
7184     }
7185
7186     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7187     bool ByteShift = ShiftEltBits > 64;
7188     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7189                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7190     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7191
7192     // Normalize the scale for byte shifts to still produce an i64 element
7193     // type.
7194     Scale = ByteShift ? Scale / 2 : Scale;
7195
7196     // We need to round trip through the appropriate type for the shift.
7197     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7198     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7199     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7200            "Illegal integer vector type");
7201     V = DAG.getBitcast(ShiftVT, V);
7202
7203     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7204                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7205     return DAG.getBitcast(VT, V);
7206   };
7207
7208   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7209   // keep doubling the size of the integer elements up to that. We can
7210   // then shift the elements of the integer vector by whole multiples of
7211   // their width within the elements of the larger integer vector. Test each
7212   // multiple to see if we can find a match with the moved element indices
7213   // and that the shifted in elements are all zeroable.
7214   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7215     for (int Shift = 1; Shift != Scale; ++Shift)
7216       for (bool Left : {true, false})
7217         if (CheckZeros(Shift, Scale, Left))
7218           for (SDValue V : {V1, V2})
7219             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7220               return Match;
7221
7222   // no match
7223   return SDValue();
7224 }
7225
7226 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7227 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7228                                            SDValue V2, ArrayRef<int> Mask,
7229                                            SelectionDAG &DAG) {
7230   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7231   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7232
7233   int Size = Mask.size();
7234   int HalfSize = Size / 2;
7235   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7236
7237   // Upper half must be undefined.
7238   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7239     return SDValue();
7240
7241   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7242   // Remainder of lower half result is zero and upper half is all undef.
7243   auto LowerAsEXTRQ = [&]() {
7244     // Determine the extraction length from the part of the
7245     // lower half that isn't zeroable.
7246     int Len = HalfSize;
7247     for (; Len >= 0; --Len)
7248       if (!Zeroable[Len - 1])
7249         break;
7250     assert(Len > 0 && "Zeroable shuffle mask");
7251
7252     // Attempt to match first Len sequential elements from the lower half.
7253     SDValue Src;
7254     int Idx = -1;
7255     for (int i = 0; i != Len; ++i) {
7256       int M = Mask[i];
7257       if (M < 0)
7258         continue;
7259       SDValue &V = (M < Size ? V1 : V2);
7260       M = M % Size;
7261
7262       // All mask elements must be in the lower half.
7263       if (M > HalfSize)
7264         return SDValue();
7265
7266       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7267         Src = V;
7268         Idx = M - i;
7269         continue;
7270       }
7271       return SDValue();
7272     }
7273
7274     if (Idx < 0)
7275       return SDValue();
7276
7277     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7278     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7279     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7280     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7281                        DAG.getConstant(BitLen, DL, MVT::i8),
7282                        DAG.getConstant(BitIdx, DL, MVT::i8));
7283   };
7284
7285   if (SDValue ExtrQ = LowerAsEXTRQ())
7286     return ExtrQ;
7287
7288   // INSERTQ: Extract lowest Len elements from lower half of second source and
7289   // insert over first source, starting at Idx.
7290   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7291   auto LowerAsInsertQ = [&]() {
7292     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7293       SDValue Base;
7294
7295       // Attempt to match first source from mask before insertion point.
7296       if (isUndefInRange(Mask, 0, Idx)) {
7297         /* EMPTY */
7298       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7299         Base = V1;
7300       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7301         Base = V2;
7302       } else {
7303         continue;
7304       }
7305
7306       // Extend the extraction length looking to match both the insertion of
7307       // the second source and the remaining elements of the first.
7308       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7309         SDValue Insert;
7310         int Len = Hi - Idx;
7311
7312         // Match insertion.
7313         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7314           Insert = V1;
7315         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7316           Insert = V2;
7317         } else {
7318           continue;
7319         }
7320
7321         // Match the remaining elements of the lower half.
7322         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7323           /* EMPTY */
7324         } else if ((!Base || (Base == V1)) &&
7325                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7326           Base = V1;
7327         } else if ((!Base || (Base == V2)) &&
7328                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7329                                               Size + Hi)) {
7330           Base = V2;
7331         } else {
7332           continue;
7333         }
7334
7335         // We may not have a base (first source) - this can safely be undefined.
7336         if (!Base)
7337           Base = DAG.getUNDEF(VT);
7338
7339         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7340         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7341         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7342                            DAG.getConstant(BitLen, DL, MVT::i8),
7343                            DAG.getConstant(BitIdx, DL, MVT::i8));
7344       }
7345     }
7346
7347     return SDValue();
7348   };
7349
7350   if (SDValue InsertQ = LowerAsInsertQ())
7351     return InsertQ;
7352
7353   return SDValue();
7354 }
7355
7356 /// \brief Lower a vector shuffle as a zero or any extension.
7357 ///
7358 /// Given a specific number of elements, element bit width, and extension
7359 /// stride, produce either a zero or any extension based on the available
7360 /// features of the subtarget.
7361 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7362     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7363     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7364   assert(Scale > 1 && "Need a scale to extend.");
7365   int NumElements = VT.getVectorNumElements();
7366   int EltBits = VT.getScalarSizeInBits();
7367   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7368          "Only 8, 16, and 32 bit elements can be extended.");
7369   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7370
7371   // Found a valid zext mask! Try various lowering strategies based on the
7372   // input type and available ISA extensions.
7373   if (Subtarget->hasSSE41()) {
7374     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7375                                  NumElements / Scale);
7376     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7377   }
7378
7379   // For any extends we can cheat for larger element sizes and use shuffle
7380   // instructions that can fold with a load and/or copy.
7381   if (AnyExt && EltBits == 32) {
7382     int PSHUFDMask[4] = {0, -1, 1, -1};
7383     return DAG.getBitcast(
7384         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7385                         DAG.getBitcast(MVT::v4i32, InputV),
7386                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7387   }
7388   if (AnyExt && EltBits == 16 && Scale > 2) {
7389     int PSHUFDMask[4] = {0, -1, 0, -1};
7390     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7391                          DAG.getBitcast(MVT::v4i32, InputV),
7392                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7393     int PSHUFHWMask[4] = {1, -1, -1, -1};
7394     return DAG.getBitcast(
7395         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7396                         DAG.getBitcast(MVT::v8i16, InputV),
7397                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7398   }
7399
7400   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7401   // to 64-bits.
7402   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7403     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7404     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7405
7406     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7407                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7408                                          DAG.getConstant(EltBits, DL, MVT::i8),
7409                                          DAG.getConstant(0, DL, MVT::i8)));
7410     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7411       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7412
7413     SDValue Hi =
7414         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7415                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7416                                 DAG.getConstant(EltBits, DL, MVT::i8),
7417                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7418     return DAG.getNode(ISD::BITCAST, DL, VT,
7419                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7420   }
7421
7422   // If this would require more than 2 unpack instructions to expand, use
7423   // pshufb when available. We can only use more than 2 unpack instructions
7424   // when zero extending i8 elements which also makes it easier to use pshufb.
7425   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7426     assert(NumElements == 16 && "Unexpected byte vector width!");
7427     SDValue PSHUFBMask[16];
7428     for (int i = 0; i < 16; ++i)
7429       PSHUFBMask[i] =
7430           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7431     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7432     return DAG.getBitcast(VT,
7433                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7434                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7435                                                   MVT::v16i8, PSHUFBMask)));
7436   }
7437
7438   // Otherwise emit a sequence of unpacks.
7439   do {
7440     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7441     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7442                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7443     InputV = DAG.getBitcast(InputVT, InputV);
7444     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7445     Scale /= 2;
7446     EltBits *= 2;
7447     NumElements /= 2;
7448   } while (Scale > 1);
7449   return DAG.getBitcast(VT, InputV);
7450 }
7451
7452 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7453 ///
7454 /// This routine will try to do everything in its power to cleverly lower
7455 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7456 /// check for the profitability of this lowering,  it tries to aggressively
7457 /// match this pattern. It will use all of the micro-architectural details it
7458 /// can to emit an efficient lowering. It handles both blends with all-zero
7459 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7460 /// masking out later).
7461 ///
7462 /// The reason we have dedicated lowering for zext-style shuffles is that they
7463 /// are both incredibly common and often quite performance sensitive.
7464 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7465     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7466     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7467   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7468
7469   int Bits = VT.getSizeInBits();
7470   int NumElements = VT.getVectorNumElements();
7471   assert(VT.getScalarSizeInBits() <= 32 &&
7472          "Exceeds 32-bit integer zero extension limit");
7473   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7474
7475   // Define a helper function to check a particular ext-scale and lower to it if
7476   // valid.
7477   auto Lower = [&](int Scale) -> SDValue {
7478     SDValue InputV;
7479     bool AnyExt = true;
7480     for (int i = 0; i < NumElements; ++i) {
7481       if (Mask[i] == -1)
7482         continue; // Valid anywhere but doesn't tell us anything.
7483       if (i % Scale != 0) {
7484         // Each of the extended elements need to be zeroable.
7485         if (!Zeroable[i])
7486           return SDValue();
7487
7488         // We no longer are in the anyext case.
7489         AnyExt = false;
7490         continue;
7491       }
7492
7493       // Each of the base elements needs to be consecutive indices into the
7494       // same input vector.
7495       SDValue V = Mask[i] < NumElements ? V1 : V2;
7496       if (!InputV)
7497         InputV = V;
7498       else if (InputV != V)
7499         return SDValue(); // Flip-flopping inputs.
7500
7501       if (Mask[i] % NumElements != i / Scale)
7502         return SDValue(); // Non-consecutive strided elements.
7503     }
7504
7505     // If we fail to find an input, we have a zero-shuffle which should always
7506     // have already been handled.
7507     // FIXME: Maybe handle this here in case during blending we end up with one?
7508     if (!InputV)
7509       return SDValue();
7510
7511     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7512         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7513   };
7514
7515   // The widest scale possible for extending is to a 64-bit integer.
7516   assert(Bits % 64 == 0 &&
7517          "The number of bits in a vector must be divisible by 64 on x86!");
7518   int NumExtElements = Bits / 64;
7519
7520   // Each iteration, try extending the elements half as much, but into twice as
7521   // many elements.
7522   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7523     assert(NumElements % NumExtElements == 0 &&
7524            "The input vector size must be divisible by the extended size.");
7525     if (SDValue V = Lower(NumElements / NumExtElements))
7526       return V;
7527   }
7528
7529   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7530   if (Bits != 128)
7531     return SDValue();
7532
7533   // Returns one of the source operands if the shuffle can be reduced to a
7534   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7535   auto CanZExtLowHalf = [&]() {
7536     for (int i = NumElements / 2; i != NumElements; ++i)
7537       if (!Zeroable[i])
7538         return SDValue();
7539     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7540       return V1;
7541     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7542       return V2;
7543     return SDValue();
7544   };
7545
7546   if (SDValue V = CanZExtLowHalf()) {
7547     V = DAG.getBitcast(MVT::v2i64, V);
7548     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7549     return DAG.getBitcast(VT, V);
7550   }
7551
7552   // No viable ext lowering found.
7553   return SDValue();
7554 }
7555
7556 /// \brief Try to get a scalar value for a specific element of a vector.
7557 ///
7558 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7559 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7560                                               SelectionDAG &DAG) {
7561   MVT VT = V.getSimpleValueType();
7562   MVT EltVT = VT.getVectorElementType();
7563   while (V.getOpcode() == ISD::BITCAST)
7564     V = V.getOperand(0);
7565   // If the bitcasts shift the element size, we can't extract an equivalent
7566   // element from it.
7567   MVT NewVT = V.getSimpleValueType();
7568   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7569     return SDValue();
7570
7571   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7572       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7573     // Ensure the scalar operand is the same size as the destination.
7574     // FIXME: Add support for scalar truncation where possible.
7575     SDValue S = V.getOperand(Idx);
7576     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7577       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7578   }
7579
7580   return SDValue();
7581 }
7582
7583 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7584 ///
7585 /// This is particularly important because the set of instructions varies
7586 /// significantly based on whether the operand is a load or not.
7587 static bool isShuffleFoldableLoad(SDValue V) {
7588   while (V.getOpcode() == ISD::BITCAST)
7589     V = V.getOperand(0);
7590
7591   return ISD::isNON_EXTLoad(V.getNode());
7592 }
7593
7594 /// \brief Try to lower insertion of a single element into a zero vector.
7595 ///
7596 /// This is a common pattern that we have especially efficient patterns to lower
7597 /// across all subtarget feature sets.
7598 static SDValue lowerVectorShuffleAsElementInsertion(
7599     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7600     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7601   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7602   MVT ExtVT = VT;
7603   MVT EltVT = VT.getVectorElementType();
7604
7605   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7606                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7607                 Mask.begin();
7608   bool IsV1Zeroable = true;
7609   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7610     if (i != V2Index && !Zeroable[i]) {
7611       IsV1Zeroable = false;
7612       break;
7613     }
7614
7615   // Check for a single input from a SCALAR_TO_VECTOR node.
7616   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7617   // all the smarts here sunk into that routine. However, the current
7618   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7619   // vector shuffle lowering is dead.
7620   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7621                                                DAG);
7622   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7623     // We need to zext the scalar if it is smaller than an i32.
7624     V2S = DAG.getBitcast(EltVT, V2S);
7625     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7626       // Using zext to expand a narrow element won't work for non-zero
7627       // insertions.
7628       if (!IsV1Zeroable)
7629         return SDValue();
7630
7631       // Zero-extend directly to i32.
7632       ExtVT = MVT::v4i32;
7633       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7634     }
7635     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7636   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7637              EltVT == MVT::i16) {
7638     // Either not inserting from the low element of the input or the input
7639     // element size is too small to use VZEXT_MOVL to clear the high bits.
7640     return SDValue();
7641   }
7642
7643   if (!IsV1Zeroable) {
7644     // If V1 can't be treated as a zero vector we have fewer options to lower
7645     // this. We can't support integer vectors or non-zero targets cheaply, and
7646     // the V1 elements can't be permuted in any way.
7647     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7648     if (!VT.isFloatingPoint() || V2Index != 0)
7649       return SDValue();
7650     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7651     V1Mask[V2Index] = -1;
7652     if (!isNoopShuffleMask(V1Mask))
7653       return SDValue();
7654     // This is essentially a special case blend operation, but if we have
7655     // general purpose blend operations, they are always faster. Bail and let
7656     // the rest of the lowering handle these as blends.
7657     if (Subtarget->hasSSE41())
7658       return SDValue();
7659
7660     // Otherwise, use MOVSD or MOVSS.
7661     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7662            "Only two types of floating point element types to handle!");
7663     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7664                        ExtVT, V1, V2);
7665   }
7666
7667   // This lowering only works for the low element with floating point vectors.
7668   if (VT.isFloatingPoint() && V2Index != 0)
7669     return SDValue();
7670
7671   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7672   if (ExtVT != VT)
7673     V2 = DAG.getBitcast(VT, V2);
7674
7675   if (V2Index != 0) {
7676     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7677     // the desired position. Otherwise it is more efficient to do a vector
7678     // shift left. We know that we can do a vector shift left because all
7679     // the inputs are zero.
7680     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7681       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7682       V2Shuffle[V2Index] = 0;
7683       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7684     } else {
7685       V2 = DAG.getBitcast(MVT::v2i64, V2);
7686       V2 = DAG.getNode(
7687           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7688           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7689                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7690                               DAG.getDataLayout(), VT)));
7691       V2 = DAG.getBitcast(VT, V2);
7692     }
7693   }
7694   return V2;
7695 }
7696
7697 /// \brief Try to lower broadcast of a single element.
7698 ///
7699 /// For convenience, this code also bundles all of the subtarget feature set
7700 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7701 /// a convenient way to factor it out.
7702 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7703                                              ArrayRef<int> Mask,
7704                                              const X86Subtarget *Subtarget,
7705                                              SelectionDAG &DAG) {
7706   if (!Subtarget->hasAVX())
7707     return SDValue();
7708   if (VT.isInteger() && !Subtarget->hasAVX2())
7709     return SDValue();
7710
7711   // Check that the mask is a broadcast.
7712   int BroadcastIdx = -1;
7713   for (int M : Mask)
7714     if (M >= 0 && BroadcastIdx == -1)
7715       BroadcastIdx = M;
7716     else if (M >= 0 && M != BroadcastIdx)
7717       return SDValue();
7718
7719   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7720                                             "a sorted mask where the broadcast "
7721                                             "comes from V1.");
7722
7723   // Go up the chain of (vector) values to find a scalar load that we can
7724   // combine with the broadcast.
7725   for (;;) {
7726     switch (V.getOpcode()) {
7727     case ISD::CONCAT_VECTORS: {
7728       int OperandSize = Mask.size() / V.getNumOperands();
7729       V = V.getOperand(BroadcastIdx / OperandSize);
7730       BroadcastIdx %= OperandSize;
7731       continue;
7732     }
7733
7734     case ISD::INSERT_SUBVECTOR: {
7735       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7736       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7737       if (!ConstantIdx)
7738         break;
7739
7740       int BeginIdx = (int)ConstantIdx->getZExtValue();
7741       int EndIdx =
7742           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7743       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7744         BroadcastIdx -= BeginIdx;
7745         V = VInner;
7746       } else {
7747         V = VOuter;
7748       }
7749       continue;
7750     }
7751     }
7752     break;
7753   }
7754
7755   // Check if this is a broadcast of a scalar. We special case lowering
7756   // for scalars so that we can more effectively fold with loads.
7757   // First, look through bitcast: if the original value has a larger element
7758   // type than the shuffle, the broadcast element is in essence truncated.
7759   // Make that explicit to ease folding.
7760   if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7761     EVT EltVT = VT.getVectorElementType();
7762     SDValue V0 = V.getOperand(0);
7763     EVT V0VT = V0.getValueType();
7764
7765     if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7766         ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7767          (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7768       V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7769       BroadcastIdx = 0;
7770     }
7771   }
7772
7773   // Also check the simpler case, where we can directly reuse the scalar.
7774   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7775       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7776     V = V.getOperand(BroadcastIdx);
7777
7778     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7779     // Only AVX2 has register broadcasts.
7780     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7781       return SDValue();
7782   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7783     // We can't broadcast from a vector register without AVX2, and we can only
7784     // broadcast from the zero-element of a vector register.
7785     return SDValue();
7786   }
7787
7788   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7789 }
7790
7791 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7792 // INSERTPS when the V1 elements are already in the correct locations
7793 // because otherwise we can just always use two SHUFPS instructions which
7794 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7795 // perform INSERTPS if a single V1 element is out of place and all V2
7796 // elements are zeroable.
7797 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7798                                             ArrayRef<int> Mask,
7799                                             SelectionDAG &DAG) {
7800   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7801   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7802   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7803   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7804
7805   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7806
7807   unsigned ZMask = 0;
7808   int V1DstIndex = -1;
7809   int V2DstIndex = -1;
7810   bool V1UsedInPlace = false;
7811
7812   for (int i = 0; i < 4; ++i) {
7813     // Synthesize a zero mask from the zeroable elements (includes undefs).
7814     if (Zeroable[i]) {
7815       ZMask |= 1 << i;
7816       continue;
7817     }
7818
7819     // Flag if we use any V1 inputs in place.
7820     if (i == Mask[i]) {
7821       V1UsedInPlace = true;
7822       continue;
7823     }
7824
7825     // We can only insert a single non-zeroable element.
7826     if (V1DstIndex != -1 || V2DstIndex != -1)
7827       return SDValue();
7828
7829     if (Mask[i] < 4) {
7830       // V1 input out of place for insertion.
7831       V1DstIndex = i;
7832     } else {
7833       // V2 input for insertion.
7834       V2DstIndex = i;
7835     }
7836   }
7837
7838   // Don't bother if we have no (non-zeroable) element for insertion.
7839   if (V1DstIndex == -1 && V2DstIndex == -1)
7840     return SDValue();
7841
7842   // Determine element insertion src/dst indices. The src index is from the
7843   // start of the inserted vector, not the start of the concatenated vector.
7844   unsigned V2SrcIndex = 0;
7845   if (V1DstIndex != -1) {
7846     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7847     // and don't use the original V2 at all.
7848     V2SrcIndex = Mask[V1DstIndex];
7849     V2DstIndex = V1DstIndex;
7850     V2 = V1;
7851   } else {
7852     V2SrcIndex = Mask[V2DstIndex] - 4;
7853   }
7854
7855   // If no V1 inputs are used in place, then the result is created only from
7856   // the zero mask and the V2 insertion - so remove V1 dependency.
7857   if (!V1UsedInPlace)
7858     V1 = DAG.getUNDEF(MVT::v4f32);
7859
7860   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7861   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7862
7863   // Insert the V2 element into the desired position.
7864   SDLoc DL(Op);
7865   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7866                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7867 }
7868
7869 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7870 /// UNPCK instruction.
7871 ///
7872 /// This specifically targets cases where we end up with alternating between
7873 /// the two inputs, and so can permute them into something that feeds a single
7874 /// UNPCK instruction. Note that this routine only targets integer vectors
7875 /// because for floating point vectors we have a generalized SHUFPS lowering
7876 /// strategy that handles everything that doesn't *exactly* match an unpack,
7877 /// making this clever lowering unnecessary.
7878 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
7879                                                     SDValue V1, SDValue V2,
7880                                                     ArrayRef<int> Mask,
7881                                                     SelectionDAG &DAG) {
7882   assert(!VT.isFloatingPoint() &&
7883          "This routine only supports integer vectors.");
7884   assert(!isSingleInputShuffleMask(Mask) &&
7885          "This routine should only be used when blending two inputs.");
7886   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7887
7888   int Size = Mask.size();
7889
7890   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7891     return M >= 0 && M % Size < Size / 2;
7892   });
7893   int NumHiInputs = std::count_if(
7894       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7895
7896   bool UnpackLo = NumLoInputs >= NumHiInputs;
7897
7898   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7899     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7900     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7901
7902     for (int i = 0; i < Size; ++i) {
7903       if (Mask[i] < 0)
7904         continue;
7905
7906       // Each element of the unpack contains Scale elements from this mask.
7907       int UnpackIdx = i / Scale;
7908
7909       // We only handle the case where V1 feeds the first slots of the unpack.
7910       // We rely on canonicalization to ensure this is the case.
7911       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7912         return SDValue();
7913
7914       // Setup the mask for this input. The indexing is tricky as we have to
7915       // handle the unpack stride.
7916       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7917       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7918           Mask[i] % Size;
7919     }
7920
7921     // If we will have to shuffle both inputs to use the unpack, check whether
7922     // we can just unpack first and shuffle the result. If so, skip this unpack.
7923     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7924         !isNoopShuffleMask(V2Mask))
7925       return SDValue();
7926
7927     // Shuffle the inputs into place.
7928     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7929     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7930
7931     // Cast the inputs to the type we will use to unpack them.
7932     V1 = DAG.getBitcast(UnpackVT, V1);
7933     V2 = DAG.getBitcast(UnpackVT, V2);
7934
7935     // Unpack the inputs and cast the result back to the desired type.
7936     return DAG.getBitcast(
7937         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7938                         UnpackVT, V1, V2));
7939   };
7940
7941   // We try each unpack from the largest to the smallest to try and find one
7942   // that fits this mask.
7943   int OrigNumElements = VT.getVectorNumElements();
7944   int OrigScalarSize = VT.getScalarSizeInBits();
7945   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7946     int Scale = ScalarSize / OrigScalarSize;
7947     int NumElements = OrigNumElements / Scale;
7948     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7949     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7950       return Unpack;
7951   }
7952
7953   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7954   // initial unpack.
7955   if (NumLoInputs == 0 || NumHiInputs == 0) {
7956     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7957            "We have to have *some* inputs!");
7958     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7959
7960     // FIXME: We could consider the total complexity of the permute of each
7961     // possible unpacking. Or at the least we should consider how many
7962     // half-crossings are created.
7963     // FIXME: We could consider commuting the unpacks.
7964
7965     SmallVector<int, 32> PermMask;
7966     PermMask.assign(Size, -1);
7967     for (int i = 0; i < Size; ++i) {
7968       if (Mask[i] < 0)
7969         continue;
7970
7971       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7972
7973       PermMask[i] =
7974           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7975     }
7976     return DAG.getVectorShuffle(
7977         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7978                             DL, VT, V1, V2),
7979         DAG.getUNDEF(VT), PermMask);
7980   }
7981
7982   return SDValue();
7983 }
7984
7985 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7986 ///
7987 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7988 /// support for floating point shuffles but not integer shuffles. These
7989 /// instructions will incur a domain crossing penalty on some chips though so
7990 /// it is better to avoid lowering through this for integer vectors where
7991 /// possible.
7992 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7993                                        const X86Subtarget *Subtarget,
7994                                        SelectionDAG &DAG) {
7995   SDLoc DL(Op);
7996   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7997   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7998   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7999   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8000   ArrayRef<int> Mask = SVOp->getMask();
8001   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8002
8003   if (isSingleInputShuffleMask(Mask)) {
8004     // Use low duplicate instructions for masks that match their pattern.
8005     if (Subtarget->hasSSE3())
8006       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8007         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8008
8009     // Straight shuffle of a single input vector. Simulate this by using the
8010     // single input as both of the "inputs" to this instruction..
8011     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8012
8013     if (Subtarget->hasAVX()) {
8014       // If we have AVX, we can use VPERMILPS which will allow folding a load
8015       // into the shuffle.
8016       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8017                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8018     }
8019
8020     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8021                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8022   }
8023   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8024   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8025
8026   // If we have a single input, insert that into V1 if we can do so cheaply.
8027   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8028     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8029             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8030       return Insertion;
8031     // Try inverting the insertion since for v2 masks it is easy to do and we
8032     // can't reliably sort the mask one way or the other.
8033     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8034                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8035     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8036             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8037       return Insertion;
8038   }
8039
8040   // Try to use one of the special instruction patterns to handle two common
8041   // blend patterns if a zero-blend above didn't work.
8042   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8043       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8044     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8045       // We can either use a special instruction to load over the low double or
8046       // to move just the low double.
8047       return DAG.getNode(
8048           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8049           DL, MVT::v2f64, V2,
8050           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8051
8052   if (Subtarget->hasSSE41())
8053     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8054                                                   Subtarget, DAG))
8055       return Blend;
8056
8057   // Use dedicated unpack instructions for masks that match their pattern.
8058   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8059     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
8060   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8061     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
8062
8063   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8064   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8065                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8066 }
8067
8068 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8069 ///
8070 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8071 /// the integer unit to minimize domain crossing penalties. However, for blends
8072 /// it falls back to the floating point shuffle operation with appropriate bit
8073 /// casting.
8074 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8075                                        const X86Subtarget *Subtarget,
8076                                        SelectionDAG &DAG) {
8077   SDLoc DL(Op);
8078   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8079   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8080   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8081   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8082   ArrayRef<int> Mask = SVOp->getMask();
8083   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8084
8085   if (isSingleInputShuffleMask(Mask)) {
8086     // Check for being able to broadcast a single element.
8087     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8088                                                           Mask, Subtarget, DAG))
8089       return Broadcast;
8090
8091     // Straight shuffle of a single input vector. For everything from SSE2
8092     // onward this has a single fast instruction with no scary immediates.
8093     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8094     V1 = DAG.getBitcast(MVT::v4i32, V1);
8095     int WidenedMask[4] = {
8096         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8097         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8098     return DAG.getBitcast(
8099         MVT::v2i64,
8100         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8101                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8102   }
8103   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8104   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8105   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8106   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8107
8108   // If we have a blend of two PACKUS operations an the blend aligns with the
8109   // low and half halves, we can just merge the PACKUS operations. This is
8110   // particularly important as it lets us merge shuffles that this routine itself
8111   // creates.
8112   auto GetPackNode = [](SDValue V) {
8113     while (V.getOpcode() == ISD::BITCAST)
8114       V = V.getOperand(0);
8115
8116     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8117   };
8118   if (SDValue V1Pack = GetPackNode(V1))
8119     if (SDValue V2Pack = GetPackNode(V2))
8120       return DAG.getBitcast(MVT::v2i64,
8121                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8122                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8123                                                      : V1Pack.getOperand(1),
8124                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8125                                                      : V2Pack.getOperand(1)));
8126
8127   // Try to use shift instructions.
8128   if (SDValue Shift =
8129           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8130     return Shift;
8131
8132   // When loading a scalar and then shuffling it into a vector we can often do
8133   // the insertion cheaply.
8134   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8135           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8136     return Insertion;
8137   // Try inverting the insertion since for v2 masks it is easy to do and we
8138   // can't reliably sort the mask one way or the other.
8139   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8140   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8141           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8142     return Insertion;
8143
8144   // We have different paths for blend lowering, but they all must use the
8145   // *exact* same predicate.
8146   bool IsBlendSupported = Subtarget->hasSSE41();
8147   if (IsBlendSupported)
8148     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8149                                                   Subtarget, DAG))
8150       return Blend;
8151
8152   // Use dedicated unpack instructions for masks that match their pattern.
8153   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8154     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8155   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8156     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8157
8158   // Try to use byte rotation instructions.
8159   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8160   if (Subtarget->hasSSSE3())
8161     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8162             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8163       return Rotate;
8164
8165   // If we have direct support for blends, we should lower by decomposing into
8166   // a permute. That will be faster than the domain cross.
8167   if (IsBlendSupported)
8168     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8169                                                       Mask, DAG);
8170
8171   // We implement this with SHUFPD which is pretty lame because it will likely
8172   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8173   // However, all the alternatives are still more cycles and newer chips don't
8174   // have this problem. It would be really nice if x86 had better shuffles here.
8175   V1 = DAG.getBitcast(MVT::v2f64, V1);
8176   V2 = DAG.getBitcast(MVT::v2f64, V2);
8177   return DAG.getBitcast(MVT::v2i64,
8178                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8179 }
8180
8181 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8182 ///
8183 /// This is used to disable more specialized lowerings when the shufps lowering
8184 /// will happen to be efficient.
8185 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8186   // This routine only handles 128-bit shufps.
8187   assert(Mask.size() == 4 && "Unsupported mask size!");
8188
8189   // To lower with a single SHUFPS we need to have the low half and high half
8190   // each requiring a single input.
8191   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8192     return false;
8193   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8194     return false;
8195
8196   return true;
8197 }
8198
8199 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8200 ///
8201 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8202 /// It makes no assumptions about whether this is the *best* lowering, it simply
8203 /// uses it.
8204 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8205                                             ArrayRef<int> Mask, SDValue V1,
8206                                             SDValue V2, SelectionDAG &DAG) {
8207   SDValue LowV = V1, HighV = V2;
8208   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8209
8210   int NumV2Elements =
8211       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8212
8213   if (NumV2Elements == 1) {
8214     int V2Index =
8215         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8216         Mask.begin();
8217
8218     // Compute the index adjacent to V2Index and in the same half by toggling
8219     // the low bit.
8220     int V2AdjIndex = V2Index ^ 1;
8221
8222     if (Mask[V2AdjIndex] == -1) {
8223       // Handles all the cases where we have a single V2 element and an undef.
8224       // This will only ever happen in the high lanes because we commute the
8225       // vector otherwise.
8226       if (V2Index < 2)
8227         std::swap(LowV, HighV);
8228       NewMask[V2Index] -= 4;
8229     } else {
8230       // Handle the case where the V2 element ends up adjacent to a V1 element.
8231       // To make this work, blend them together as the first step.
8232       int V1Index = V2AdjIndex;
8233       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8234       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8235                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8236
8237       // Now proceed to reconstruct the final blend as we have the necessary
8238       // high or low half formed.
8239       if (V2Index < 2) {
8240         LowV = V2;
8241         HighV = V1;
8242       } else {
8243         HighV = V2;
8244       }
8245       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8246       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8247     }
8248   } else if (NumV2Elements == 2) {
8249     if (Mask[0] < 4 && Mask[1] < 4) {
8250       // Handle the easy case where we have V1 in the low lanes and V2 in the
8251       // high lanes.
8252       NewMask[2] -= 4;
8253       NewMask[3] -= 4;
8254     } else if (Mask[2] < 4 && Mask[3] < 4) {
8255       // We also handle the reversed case because this utility may get called
8256       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8257       // arrange things in the right direction.
8258       NewMask[0] -= 4;
8259       NewMask[1] -= 4;
8260       HighV = V1;
8261       LowV = V2;
8262     } else {
8263       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8264       // trying to place elements directly, just blend them and set up the final
8265       // shuffle to place them.
8266
8267       // The first two blend mask elements are for V1, the second two are for
8268       // V2.
8269       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8270                           Mask[2] < 4 ? Mask[2] : Mask[3],
8271                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8272                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8273       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8274                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8275
8276       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8277       // a blend.
8278       LowV = HighV = V1;
8279       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8280       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8281       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8282       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8283     }
8284   }
8285   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8286                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8287 }
8288
8289 /// \brief Lower 4-lane 32-bit floating point shuffles.
8290 ///
8291 /// Uses instructions exclusively from the floating point unit to minimize
8292 /// domain crossing penalties, as these are sufficient to implement all v4f32
8293 /// shuffles.
8294 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8295                                        const X86Subtarget *Subtarget,
8296                                        SelectionDAG &DAG) {
8297   SDLoc DL(Op);
8298   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8299   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8300   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8301   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8302   ArrayRef<int> Mask = SVOp->getMask();
8303   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8304
8305   int NumV2Elements =
8306       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8307
8308   if (NumV2Elements == 0) {
8309     // Check for being able to broadcast a single element.
8310     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8311                                                           Mask, Subtarget, DAG))
8312       return Broadcast;
8313
8314     // Use even/odd duplicate instructions for masks that match their pattern.
8315     if (Subtarget->hasSSE3()) {
8316       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8317         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8318       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8319         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8320     }
8321
8322     if (Subtarget->hasAVX()) {
8323       // If we have AVX, we can use VPERMILPS which will allow folding a load
8324       // into the shuffle.
8325       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8326                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8327     }
8328
8329     // Otherwise, use a straight shuffle of a single input vector. We pass the
8330     // input vector to both operands to simulate this with a SHUFPS.
8331     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8332                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8333   }
8334
8335   // There are special ways we can lower some single-element blends. However, we
8336   // have custom ways we can lower more complex single-element blends below that
8337   // we defer to if both this and BLENDPS fail to match, so restrict this to
8338   // when the V2 input is targeting element 0 of the mask -- that is the fast
8339   // case here.
8340   if (NumV2Elements == 1 && Mask[0] >= 4)
8341     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8342                                                          Mask, Subtarget, DAG))
8343       return V;
8344
8345   if (Subtarget->hasSSE41()) {
8346     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8347                                                   Subtarget, DAG))
8348       return Blend;
8349
8350     // Use INSERTPS if we can complete the shuffle efficiently.
8351     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8352       return V;
8353
8354     if (!isSingleSHUFPSMask(Mask))
8355       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8356               DL, MVT::v4f32, V1, V2, Mask, DAG))
8357         return BlendPerm;
8358   }
8359
8360   // Use dedicated unpack instructions for masks that match their pattern.
8361   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8362     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8363   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8364     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8365   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8366     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8367   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8368     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8369
8370   // Otherwise fall back to a SHUFPS lowering strategy.
8371   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8372 }
8373
8374 /// \brief Lower 4-lane i32 vector shuffles.
8375 ///
8376 /// We try to handle these with integer-domain shuffles where we can, but for
8377 /// blends we use the floating point domain blend instructions.
8378 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8379                                        const X86Subtarget *Subtarget,
8380                                        SelectionDAG &DAG) {
8381   SDLoc DL(Op);
8382   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8383   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8384   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8385   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8386   ArrayRef<int> Mask = SVOp->getMask();
8387   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8388
8389   // Whenever we can lower this as a zext, that instruction is strictly faster
8390   // than any alternative. It also allows us to fold memory operands into the
8391   // shuffle in many cases.
8392   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8393                                                          Mask, Subtarget, DAG))
8394     return ZExt;
8395
8396   int NumV2Elements =
8397       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8398
8399   if (NumV2Elements == 0) {
8400     // Check for being able to broadcast a single element.
8401     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8402                                                           Mask, Subtarget, DAG))
8403       return Broadcast;
8404
8405     // Straight shuffle of a single input vector. For everything from SSE2
8406     // onward this has a single fast instruction with no scary immediates.
8407     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8408     // but we aren't actually going to use the UNPCK instruction because doing
8409     // so prevents folding a load into this instruction or making a copy.
8410     const int UnpackLoMask[] = {0, 0, 1, 1};
8411     const int UnpackHiMask[] = {2, 2, 3, 3};
8412     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8413       Mask = UnpackLoMask;
8414     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8415       Mask = UnpackHiMask;
8416
8417     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8418                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8419   }
8420
8421   // Try to use shift instructions.
8422   if (SDValue Shift =
8423           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8424     return Shift;
8425
8426   // There are special ways we can lower some single-element blends.
8427   if (NumV2Elements == 1)
8428     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8429                                                          Mask, Subtarget, DAG))
8430       return V;
8431
8432   // We have different paths for blend lowering, but they all must use the
8433   // *exact* same predicate.
8434   bool IsBlendSupported = Subtarget->hasSSE41();
8435   if (IsBlendSupported)
8436     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8437                                                   Subtarget, DAG))
8438       return Blend;
8439
8440   if (SDValue Masked =
8441           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8442     return Masked;
8443
8444   // Use dedicated unpack instructions for masks that match their pattern.
8445   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8446     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8447   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8448     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8449   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8450     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8451   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8452     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8453
8454   // Try to use byte rotation instructions.
8455   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8456   if (Subtarget->hasSSSE3())
8457     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8458             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8459       return Rotate;
8460
8461   // If we have direct support for blends, we should lower by decomposing into
8462   // a permute. That will be faster than the domain cross.
8463   if (IsBlendSupported)
8464     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8465                                                       Mask, DAG);
8466
8467   // Try to lower by permuting the inputs into an unpack instruction.
8468   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8469                                                             V2, Mask, DAG))
8470     return Unpack;
8471
8472   // We implement this with SHUFPS because it can blend from two vectors.
8473   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8474   // up the inputs, bypassing domain shift penalties that we would encur if we
8475   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8476   // relevant.
8477   return DAG.getBitcast(
8478       MVT::v4i32,
8479       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8480                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8481 }
8482
8483 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8484 /// shuffle lowering, and the most complex part.
8485 ///
8486 /// The lowering strategy is to try to form pairs of input lanes which are
8487 /// targeted at the same half of the final vector, and then use a dword shuffle
8488 /// to place them onto the right half, and finally unpack the paired lanes into
8489 /// their final position.
8490 ///
8491 /// The exact breakdown of how to form these dword pairs and align them on the
8492 /// correct sides is really tricky. See the comments within the function for
8493 /// more of the details.
8494 ///
8495 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8496 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8497 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8498 /// vector, form the analogous 128-bit 8-element Mask.
8499 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8500     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8501     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8502   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8503   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8504
8505   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8506   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8507   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8508
8509   SmallVector<int, 4> LoInputs;
8510   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8511                [](int M) { return M >= 0; });
8512   std::sort(LoInputs.begin(), LoInputs.end());
8513   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8514   SmallVector<int, 4> HiInputs;
8515   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8516                [](int M) { return M >= 0; });
8517   std::sort(HiInputs.begin(), HiInputs.end());
8518   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8519   int NumLToL =
8520       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8521   int NumHToL = LoInputs.size() - NumLToL;
8522   int NumLToH =
8523       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8524   int NumHToH = HiInputs.size() - NumLToH;
8525   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8526   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8527   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8528   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8529
8530   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8531   // such inputs we can swap two of the dwords across the half mark and end up
8532   // with <=2 inputs to each half in each half. Once there, we can fall through
8533   // to the generic code below. For example:
8534   //
8535   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8536   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8537   //
8538   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8539   // and an existing 2-into-2 on the other half. In this case we may have to
8540   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8541   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8542   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8543   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8544   // half than the one we target for fixing) will be fixed when we re-enter this
8545   // path. We will also combine away any sequence of PSHUFD instructions that
8546   // result into a single instruction. Here is an example of the tricky case:
8547   //
8548   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8549   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8550   //
8551   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8552   //
8553   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8554   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8555   //
8556   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8557   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8558   //
8559   // The result is fine to be handled by the generic logic.
8560   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8561                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8562                           int AOffset, int BOffset) {
8563     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8564            "Must call this with A having 3 or 1 inputs from the A half.");
8565     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8566            "Must call this with B having 1 or 3 inputs from the B half.");
8567     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8568            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8569
8570     bool ThreeAInputs = AToAInputs.size() == 3;
8571
8572     // Compute the index of dword with only one word among the three inputs in
8573     // a half by taking the sum of the half with three inputs and subtracting
8574     // the sum of the actual three inputs. The difference is the remaining
8575     // slot.
8576     int ADWord, BDWord;
8577     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8578     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8579     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8580     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8581     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8582     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8583     int TripleNonInputIdx =
8584         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8585     TripleDWord = TripleNonInputIdx / 2;
8586
8587     // We use xor with one to compute the adjacent DWord to whichever one the
8588     // OneInput is in.
8589     OneInputDWord = (OneInput / 2) ^ 1;
8590
8591     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8592     // and BToA inputs. If there is also such a problem with the BToB and AToB
8593     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8594     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8595     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8596     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8597       // Compute how many inputs will be flipped by swapping these DWords. We
8598       // need
8599       // to balance this to ensure we don't form a 3-1 shuffle in the other
8600       // half.
8601       int NumFlippedAToBInputs =
8602           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8603           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8604       int NumFlippedBToBInputs =
8605           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8606           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8607       if ((NumFlippedAToBInputs == 1 &&
8608            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8609           (NumFlippedBToBInputs == 1 &&
8610            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8611         // We choose whether to fix the A half or B half based on whether that
8612         // half has zero flipped inputs. At zero, we may not be able to fix it
8613         // with that half. We also bias towards fixing the B half because that
8614         // will more commonly be the high half, and we have to bias one way.
8615         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8616                                                        ArrayRef<int> Inputs) {
8617           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8618           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8619                                          PinnedIdx ^ 1) != Inputs.end();
8620           // Determine whether the free index is in the flipped dword or the
8621           // unflipped dword based on where the pinned index is. We use this bit
8622           // in an xor to conditionally select the adjacent dword.
8623           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8624           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8625                                              FixFreeIdx) != Inputs.end();
8626           if (IsFixIdxInput == IsFixFreeIdxInput)
8627             FixFreeIdx += 1;
8628           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8629                                         FixFreeIdx) != Inputs.end();
8630           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8631                  "We need to be changing the number of flipped inputs!");
8632           int PSHUFHalfMask[] = {0, 1, 2, 3};
8633           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8634           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8635                           MVT::v8i16, V,
8636                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8637
8638           for (int &M : Mask)
8639             if (M != -1 && M == FixIdx)
8640               M = FixFreeIdx;
8641             else if (M != -1 && M == FixFreeIdx)
8642               M = FixIdx;
8643         };
8644         if (NumFlippedBToBInputs != 0) {
8645           int BPinnedIdx =
8646               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8647           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8648         } else {
8649           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8650           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8651           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8652         }
8653       }
8654     }
8655
8656     int PSHUFDMask[] = {0, 1, 2, 3};
8657     PSHUFDMask[ADWord] = BDWord;
8658     PSHUFDMask[BDWord] = ADWord;
8659     V = DAG.getBitcast(
8660         VT,
8661         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8662                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8663
8664     // Adjust the mask to match the new locations of A and B.
8665     for (int &M : Mask)
8666       if (M != -1 && M/2 == ADWord)
8667         M = 2 * BDWord + M % 2;
8668       else if (M != -1 && M/2 == BDWord)
8669         M = 2 * ADWord + M % 2;
8670
8671     // Recurse back into this routine to re-compute state now that this isn't
8672     // a 3 and 1 problem.
8673     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8674                                                      DAG);
8675   };
8676   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8677     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8678   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8679     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8680
8681   // At this point there are at most two inputs to the low and high halves from
8682   // each half. That means the inputs can always be grouped into dwords and
8683   // those dwords can then be moved to the correct half with a dword shuffle.
8684   // We use at most one low and one high word shuffle to collect these paired
8685   // inputs into dwords, and finally a dword shuffle to place them.
8686   int PSHUFLMask[4] = {-1, -1, -1, -1};
8687   int PSHUFHMask[4] = {-1, -1, -1, -1};
8688   int PSHUFDMask[4] = {-1, -1, -1, -1};
8689
8690   // First fix the masks for all the inputs that are staying in their
8691   // original halves. This will then dictate the targets of the cross-half
8692   // shuffles.
8693   auto fixInPlaceInputs =
8694       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8695                     MutableArrayRef<int> SourceHalfMask,
8696                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8697     if (InPlaceInputs.empty())
8698       return;
8699     if (InPlaceInputs.size() == 1) {
8700       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8701           InPlaceInputs[0] - HalfOffset;
8702       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8703       return;
8704     }
8705     if (IncomingInputs.empty()) {
8706       // Just fix all of the in place inputs.
8707       for (int Input : InPlaceInputs) {
8708         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8709         PSHUFDMask[Input / 2] = Input / 2;
8710       }
8711       return;
8712     }
8713
8714     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8715     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8716         InPlaceInputs[0] - HalfOffset;
8717     // Put the second input next to the first so that they are packed into
8718     // a dword. We find the adjacent index by toggling the low bit.
8719     int AdjIndex = InPlaceInputs[0] ^ 1;
8720     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8721     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8722     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8723   };
8724   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8725   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8726
8727   // Now gather the cross-half inputs and place them into a free dword of
8728   // their target half.
8729   // FIXME: This operation could almost certainly be simplified dramatically to
8730   // look more like the 3-1 fixing operation.
8731   auto moveInputsToRightHalf = [&PSHUFDMask](
8732       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8733       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8734       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8735       int DestOffset) {
8736     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8737       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8738     };
8739     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8740                                                int Word) {
8741       int LowWord = Word & ~1;
8742       int HighWord = Word | 1;
8743       return isWordClobbered(SourceHalfMask, LowWord) ||
8744              isWordClobbered(SourceHalfMask, HighWord);
8745     };
8746
8747     if (IncomingInputs.empty())
8748       return;
8749
8750     if (ExistingInputs.empty()) {
8751       // Map any dwords with inputs from them into the right half.
8752       for (int Input : IncomingInputs) {
8753         // If the source half mask maps over the inputs, turn those into
8754         // swaps and use the swapped lane.
8755         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8756           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8757             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8758                 Input - SourceOffset;
8759             // We have to swap the uses in our half mask in one sweep.
8760             for (int &M : HalfMask)
8761               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8762                 M = Input;
8763               else if (M == Input)
8764                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8765           } else {
8766             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8767                        Input - SourceOffset &&
8768                    "Previous placement doesn't match!");
8769           }
8770           // Note that this correctly re-maps both when we do a swap and when
8771           // we observe the other side of the swap above. We rely on that to
8772           // avoid swapping the members of the input list directly.
8773           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8774         }
8775
8776         // Map the input's dword into the correct half.
8777         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8778           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8779         else
8780           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8781                      Input / 2 &&
8782                  "Previous placement doesn't match!");
8783       }
8784
8785       // And just directly shift any other-half mask elements to be same-half
8786       // as we will have mirrored the dword containing the element into the
8787       // same position within that half.
8788       for (int &M : HalfMask)
8789         if (M >= SourceOffset && M < SourceOffset + 4) {
8790           M = M - SourceOffset + DestOffset;
8791           assert(M >= 0 && "This should never wrap below zero!");
8792         }
8793       return;
8794     }
8795
8796     // Ensure we have the input in a viable dword of its current half. This
8797     // is particularly tricky because the original position may be clobbered
8798     // by inputs being moved and *staying* in that half.
8799     if (IncomingInputs.size() == 1) {
8800       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8801         int InputFixed = std::find(std::begin(SourceHalfMask),
8802                                    std::end(SourceHalfMask), -1) -
8803                          std::begin(SourceHalfMask) + SourceOffset;
8804         SourceHalfMask[InputFixed - SourceOffset] =
8805             IncomingInputs[0] - SourceOffset;
8806         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8807                      InputFixed);
8808         IncomingInputs[0] = InputFixed;
8809       }
8810     } else if (IncomingInputs.size() == 2) {
8811       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8812           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8813         // We have two non-adjacent or clobbered inputs we need to extract from
8814         // the source half. To do this, we need to map them into some adjacent
8815         // dword slot in the source mask.
8816         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8817                               IncomingInputs[1] - SourceOffset};
8818
8819         // If there is a free slot in the source half mask adjacent to one of
8820         // the inputs, place the other input in it. We use (Index XOR 1) to
8821         // compute an adjacent index.
8822         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8823             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8824           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8825           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8826           InputsFixed[1] = InputsFixed[0] ^ 1;
8827         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8828                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8829           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8830           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8831           InputsFixed[0] = InputsFixed[1] ^ 1;
8832         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8833                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8834           // The two inputs are in the same DWord but it is clobbered and the
8835           // adjacent DWord isn't used at all. Move both inputs to the free
8836           // slot.
8837           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8838           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8839           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8840           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8841         } else {
8842           // The only way we hit this point is if there is no clobbering
8843           // (because there are no off-half inputs to this half) and there is no
8844           // free slot adjacent to one of the inputs. In this case, we have to
8845           // swap an input with a non-input.
8846           for (int i = 0; i < 4; ++i)
8847             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8848                    "We can't handle any clobbers here!");
8849           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8850                  "Cannot have adjacent inputs here!");
8851
8852           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8853           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8854
8855           // We also have to update the final source mask in this case because
8856           // it may need to undo the above swap.
8857           for (int &M : FinalSourceHalfMask)
8858             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8859               M = InputsFixed[1] + SourceOffset;
8860             else if (M == InputsFixed[1] + SourceOffset)
8861               M = (InputsFixed[0] ^ 1) + SourceOffset;
8862
8863           InputsFixed[1] = InputsFixed[0] ^ 1;
8864         }
8865
8866         // Point everything at the fixed inputs.
8867         for (int &M : HalfMask)
8868           if (M == IncomingInputs[0])
8869             M = InputsFixed[0] + SourceOffset;
8870           else if (M == IncomingInputs[1])
8871             M = InputsFixed[1] + SourceOffset;
8872
8873         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8874         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8875       }
8876     } else {
8877       llvm_unreachable("Unhandled input size!");
8878     }
8879
8880     // Now hoist the DWord down to the right half.
8881     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8882     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8883     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8884     for (int &M : HalfMask)
8885       for (int Input : IncomingInputs)
8886         if (M == Input)
8887           M = FreeDWord * 2 + Input % 2;
8888   };
8889   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8890                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8891   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8892                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8893
8894   // Now enact all the shuffles we've computed to move the inputs into their
8895   // target half.
8896   if (!isNoopShuffleMask(PSHUFLMask))
8897     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8898                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8899   if (!isNoopShuffleMask(PSHUFHMask))
8900     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8901                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8902   if (!isNoopShuffleMask(PSHUFDMask))
8903     V = DAG.getBitcast(
8904         VT,
8905         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8906                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8907
8908   // At this point, each half should contain all its inputs, and we can then
8909   // just shuffle them into their final position.
8910   assert(std::count_if(LoMask.begin(), LoMask.end(),
8911                        [](int M) { return M >= 4; }) == 0 &&
8912          "Failed to lift all the high half inputs to the low mask!");
8913   assert(std::count_if(HiMask.begin(), HiMask.end(),
8914                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8915          "Failed to lift all the low half inputs to the high mask!");
8916
8917   // Do a half shuffle for the low mask.
8918   if (!isNoopShuffleMask(LoMask))
8919     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8920                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8921
8922   // Do a half shuffle with the high mask after shifting its values down.
8923   for (int &M : HiMask)
8924     if (M >= 0)
8925       M -= 4;
8926   if (!isNoopShuffleMask(HiMask))
8927     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8928                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8929
8930   return V;
8931 }
8932
8933 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8934 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8935                                           SDValue V2, ArrayRef<int> Mask,
8936                                           SelectionDAG &DAG, bool &V1InUse,
8937                                           bool &V2InUse) {
8938   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8939   SDValue V1Mask[16];
8940   SDValue V2Mask[16];
8941   V1InUse = false;
8942   V2InUse = false;
8943
8944   int Size = Mask.size();
8945   int Scale = 16 / Size;
8946   for (int i = 0; i < 16; ++i) {
8947     if (Mask[i / Scale] == -1) {
8948       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8949     } else {
8950       const int ZeroMask = 0x80;
8951       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8952                                           : ZeroMask;
8953       int V2Idx = Mask[i / Scale] < Size
8954                       ? ZeroMask
8955                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8956       if (Zeroable[i / Scale])
8957         V1Idx = V2Idx = ZeroMask;
8958       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8959       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8960       V1InUse |= (ZeroMask != V1Idx);
8961       V2InUse |= (ZeroMask != V2Idx);
8962     }
8963   }
8964
8965   if (V1InUse)
8966     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8967                      DAG.getBitcast(MVT::v16i8, V1),
8968                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8969   if (V2InUse)
8970     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8971                      DAG.getBitcast(MVT::v16i8, V2),
8972                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8973
8974   // If we need shuffled inputs from both, blend the two.
8975   SDValue V;
8976   if (V1InUse && V2InUse)
8977     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8978   else
8979     V = V1InUse ? V1 : V2;
8980
8981   // Cast the result back to the correct type.
8982   return DAG.getBitcast(VT, V);
8983 }
8984
8985 /// \brief Generic lowering of 8-lane i16 shuffles.
8986 ///
8987 /// This handles both single-input shuffles and combined shuffle/blends with
8988 /// two inputs. The single input shuffles are immediately delegated to
8989 /// a dedicated lowering routine.
8990 ///
8991 /// The blends are lowered in one of three fundamental ways. If there are few
8992 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8993 /// of the input is significantly cheaper when lowered as an interleaving of
8994 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8995 /// halves of the inputs separately (making them have relatively few inputs)
8996 /// and then concatenate them.
8997 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8998                                        const X86Subtarget *Subtarget,
8999                                        SelectionDAG &DAG) {
9000   SDLoc DL(Op);
9001   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9002   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9003   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9004   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9005   ArrayRef<int> OrigMask = SVOp->getMask();
9006   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9007                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9008   MutableArrayRef<int> Mask(MaskStorage);
9009
9010   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9011
9012   // Whenever we can lower this as a zext, that instruction is strictly faster
9013   // than any alternative.
9014   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9015           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9016     return ZExt;
9017
9018   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9019   (void)isV1;
9020   auto isV2 = [](int M) { return M >= 8; };
9021
9022   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9023
9024   if (NumV2Inputs == 0) {
9025     // Check for being able to broadcast a single element.
9026     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9027                                                           Mask, Subtarget, DAG))
9028       return Broadcast;
9029
9030     // Try to use shift instructions.
9031     if (SDValue Shift =
9032             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9033       return Shift;
9034
9035     // Use dedicated unpack instructions for masks that match their pattern.
9036     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
9037       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
9038     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
9039       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
9040
9041     // Try to use byte rotation instructions.
9042     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9043                                                         Mask, Subtarget, DAG))
9044       return Rotate;
9045
9046     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9047                                                      Subtarget, DAG);
9048   }
9049
9050   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9051          "All single-input shuffles should be canonicalized to be V1-input "
9052          "shuffles.");
9053
9054   // Try to use shift instructions.
9055   if (SDValue Shift =
9056           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9057     return Shift;
9058
9059   // See if we can use SSE4A Extraction / Insertion.
9060   if (Subtarget->hasSSE4A())
9061     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9062       return V;
9063
9064   // There are special ways we can lower some single-element blends.
9065   if (NumV2Inputs == 1)
9066     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9067                                                          Mask, Subtarget, DAG))
9068       return V;
9069
9070   // We have different paths for blend lowering, but they all must use the
9071   // *exact* same predicate.
9072   bool IsBlendSupported = Subtarget->hasSSE41();
9073   if (IsBlendSupported)
9074     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9075                                                   Subtarget, DAG))
9076       return Blend;
9077
9078   if (SDValue Masked =
9079           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9080     return Masked;
9081
9082   // Use dedicated unpack instructions for masks that match their pattern.
9083   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
9084     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9085   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
9086     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9087
9088   // Try to use byte rotation instructions.
9089   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9090           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9091     return Rotate;
9092
9093   if (SDValue BitBlend =
9094           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9095     return BitBlend;
9096
9097   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9098                                                             V2, Mask, DAG))
9099     return Unpack;
9100
9101   // If we can't directly blend but can use PSHUFB, that will be better as it
9102   // can both shuffle and set up the inefficient blend.
9103   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9104     bool V1InUse, V2InUse;
9105     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9106                                       V1InUse, V2InUse);
9107   }
9108
9109   // We can always bit-blend if we have to so the fallback strategy is to
9110   // decompose into single-input permutes and blends.
9111   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9112                                                       Mask, DAG);
9113 }
9114
9115 /// \brief Check whether a compaction lowering can be done by dropping even
9116 /// elements and compute how many times even elements must be dropped.
9117 ///
9118 /// This handles shuffles which take every Nth element where N is a power of
9119 /// two. Example shuffle masks:
9120 ///
9121 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9122 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9123 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9124 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9125 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9126 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9127 ///
9128 /// Any of these lanes can of course be undef.
9129 ///
9130 /// This routine only supports N <= 3.
9131 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9132 /// for larger N.
9133 ///
9134 /// \returns N above, or the number of times even elements must be dropped if
9135 /// there is such a number. Otherwise returns zero.
9136 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9137   // Figure out whether we're looping over two inputs or just one.
9138   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9139
9140   // The modulus for the shuffle vector entries is based on whether this is
9141   // a single input or not.
9142   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9143   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9144          "We should only be called with masks with a power-of-2 size!");
9145
9146   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9147
9148   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9149   // and 2^3 simultaneously. This is because we may have ambiguity with
9150   // partially undef inputs.
9151   bool ViableForN[3] = {true, true, true};
9152
9153   for (int i = 0, e = Mask.size(); i < e; ++i) {
9154     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9155     // want.
9156     if (Mask[i] == -1)
9157       continue;
9158
9159     bool IsAnyViable = false;
9160     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9161       if (ViableForN[j]) {
9162         uint64_t N = j + 1;
9163
9164         // The shuffle mask must be equal to (i * 2^N) % M.
9165         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9166           IsAnyViable = true;
9167         else
9168           ViableForN[j] = false;
9169       }
9170     // Early exit if we exhaust the possible powers of two.
9171     if (!IsAnyViable)
9172       break;
9173   }
9174
9175   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9176     if (ViableForN[j])
9177       return j + 1;
9178
9179   // Return 0 as there is no viable power of two.
9180   return 0;
9181 }
9182
9183 /// \brief Generic lowering of v16i8 shuffles.
9184 ///
9185 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9186 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9187 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9188 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9189 /// back together.
9190 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9191                                        const X86Subtarget *Subtarget,
9192                                        SelectionDAG &DAG) {
9193   SDLoc DL(Op);
9194   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9195   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9196   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9197   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9198   ArrayRef<int> Mask = SVOp->getMask();
9199   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9200
9201   // Try to use shift instructions.
9202   if (SDValue Shift =
9203           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9204     return Shift;
9205
9206   // Try to use byte rotation instructions.
9207   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9208           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9209     return Rotate;
9210
9211   // Try to use a zext lowering.
9212   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9213           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9214     return ZExt;
9215
9216   // See if we can use SSE4A Extraction / Insertion.
9217   if (Subtarget->hasSSE4A())
9218     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9219       return V;
9220
9221   int NumV2Elements =
9222       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9223
9224   // For single-input shuffles, there are some nicer lowering tricks we can use.
9225   if (NumV2Elements == 0) {
9226     // Check for being able to broadcast a single element.
9227     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9228                                                           Mask, Subtarget, DAG))
9229       return Broadcast;
9230
9231     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9232     // Notably, this handles splat and partial-splat shuffles more efficiently.
9233     // However, it only makes sense if the pre-duplication shuffle simplifies
9234     // things significantly. Currently, this means we need to be able to
9235     // express the pre-duplication shuffle as an i16 shuffle.
9236     //
9237     // FIXME: We should check for other patterns which can be widened into an
9238     // i16 shuffle as well.
9239     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9240       for (int i = 0; i < 16; i += 2)
9241         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9242           return false;
9243
9244       return true;
9245     };
9246     auto tryToWidenViaDuplication = [&]() -> SDValue {
9247       if (!canWidenViaDuplication(Mask))
9248         return SDValue();
9249       SmallVector<int, 4> LoInputs;
9250       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9251                    [](int M) { return M >= 0 && M < 8; });
9252       std::sort(LoInputs.begin(), LoInputs.end());
9253       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9254                      LoInputs.end());
9255       SmallVector<int, 4> HiInputs;
9256       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9257                    [](int M) { return M >= 8; });
9258       std::sort(HiInputs.begin(), HiInputs.end());
9259       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9260                      HiInputs.end());
9261
9262       bool TargetLo = LoInputs.size() >= HiInputs.size();
9263       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9264       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9265
9266       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9267       SmallDenseMap<int, int, 8> LaneMap;
9268       for (int I : InPlaceInputs) {
9269         PreDupI16Shuffle[I/2] = I/2;
9270         LaneMap[I] = I;
9271       }
9272       int j = TargetLo ? 0 : 4, je = j + 4;
9273       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9274         // Check if j is already a shuffle of this input. This happens when
9275         // there are two adjacent bytes after we move the low one.
9276         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9277           // If we haven't yet mapped the input, search for a slot into which
9278           // we can map it.
9279           while (j < je && PreDupI16Shuffle[j] != -1)
9280             ++j;
9281
9282           if (j == je)
9283             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9284             return SDValue();
9285
9286           // Map this input with the i16 shuffle.
9287           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9288         }
9289
9290         // Update the lane map based on the mapping we ended up with.
9291         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9292       }
9293       V1 = DAG.getBitcast(
9294           MVT::v16i8,
9295           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9296                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9297
9298       // Unpack the bytes to form the i16s that will be shuffled into place.
9299       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9300                        MVT::v16i8, V1, V1);
9301
9302       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9303       for (int i = 0; i < 16; ++i)
9304         if (Mask[i] != -1) {
9305           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9306           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9307           if (PostDupI16Shuffle[i / 2] == -1)
9308             PostDupI16Shuffle[i / 2] = MappedMask;
9309           else
9310             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9311                    "Conflicting entrties in the original shuffle!");
9312         }
9313       return DAG.getBitcast(
9314           MVT::v16i8,
9315           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9316                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9317     };
9318     if (SDValue V = tryToWidenViaDuplication())
9319       return V;
9320   }
9321
9322   if (SDValue Masked =
9323           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9324     return Masked;
9325
9326   // Use dedicated unpack instructions for masks that match their pattern.
9327   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9328                                          0, 16, 1, 17, 2, 18, 3, 19,
9329                                          // High half.
9330                                          4, 20, 5, 21, 6, 22, 7, 23}))
9331     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9332   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9333                                          8, 24, 9, 25, 10, 26, 11, 27,
9334                                          // High half.
9335                                          12, 28, 13, 29, 14, 30, 15, 31}))
9336     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9337
9338   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9339   // with PSHUFB. It is important to do this before we attempt to generate any
9340   // blends but after all of the single-input lowerings. If the single input
9341   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9342   // want to preserve that and we can DAG combine any longer sequences into
9343   // a PSHUFB in the end. But once we start blending from multiple inputs,
9344   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9345   // and there are *very* few patterns that would actually be faster than the
9346   // PSHUFB approach because of its ability to zero lanes.
9347   //
9348   // FIXME: The only exceptions to the above are blends which are exact
9349   // interleavings with direct instructions supporting them. We currently don't
9350   // handle those well here.
9351   if (Subtarget->hasSSSE3()) {
9352     bool V1InUse = false;
9353     bool V2InUse = false;
9354
9355     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9356                                                 DAG, V1InUse, V2InUse);
9357
9358     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9359     // do so. This avoids using them to handle blends-with-zero which is
9360     // important as a single pshufb is significantly faster for that.
9361     if (V1InUse && V2InUse) {
9362       if (Subtarget->hasSSE41())
9363         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9364                                                       Mask, Subtarget, DAG))
9365           return Blend;
9366
9367       // We can use an unpack to do the blending rather than an or in some
9368       // cases. Even though the or may be (very minorly) more efficient, we
9369       // preference this lowering because there are common cases where part of
9370       // the complexity of the shuffles goes away when we do the final blend as
9371       // an unpack.
9372       // FIXME: It might be worth trying to detect if the unpack-feeding
9373       // shuffles will both be pshufb, in which case we shouldn't bother with
9374       // this.
9375       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9376               DL, MVT::v16i8, V1, V2, Mask, DAG))
9377         return Unpack;
9378     }
9379
9380     return PSHUFB;
9381   }
9382
9383   // There are special ways we can lower some single-element blends.
9384   if (NumV2Elements == 1)
9385     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9386                                                          Mask, Subtarget, DAG))
9387       return V;
9388
9389   if (SDValue BitBlend =
9390           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9391     return BitBlend;
9392
9393   // Check whether a compaction lowering can be done. This handles shuffles
9394   // which take every Nth element for some even N. See the helper function for
9395   // details.
9396   //
9397   // We special case these as they can be particularly efficiently handled with
9398   // the PACKUSB instruction on x86 and they show up in common patterns of
9399   // rearranging bytes to truncate wide elements.
9400   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9401     // NumEvenDrops is the power of two stride of the elements. Another way of
9402     // thinking about it is that we need to drop the even elements this many
9403     // times to get the original input.
9404     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9405
9406     // First we need to zero all the dropped bytes.
9407     assert(NumEvenDrops <= 3 &&
9408            "No support for dropping even elements more than 3 times.");
9409     // We use the mask type to pick which bytes are preserved based on how many
9410     // elements are dropped.
9411     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9412     SDValue ByteClearMask = DAG.getBitcast(
9413         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9414     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9415     if (!IsSingleInput)
9416       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9417
9418     // Now pack things back together.
9419     V1 = DAG.getBitcast(MVT::v8i16, V1);
9420     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9421     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9422     for (int i = 1; i < NumEvenDrops; ++i) {
9423       Result = DAG.getBitcast(MVT::v8i16, Result);
9424       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9425     }
9426
9427     return Result;
9428   }
9429
9430   // Handle multi-input cases by blending single-input shuffles.
9431   if (NumV2Elements > 0)
9432     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9433                                                       Mask, DAG);
9434
9435   // The fallback path for single-input shuffles widens this into two v8i16
9436   // vectors with unpacks, shuffles those, and then pulls them back together
9437   // with a pack.
9438   SDValue V = V1;
9439
9440   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9441   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9442   for (int i = 0; i < 16; ++i)
9443     if (Mask[i] >= 0)
9444       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9445
9446   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9447
9448   SDValue VLoHalf, VHiHalf;
9449   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9450   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9451   // i16s.
9452   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9453                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9454       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9455                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9456     // Use a mask to drop the high bytes.
9457     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9458     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9459                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9460
9461     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9462     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9463
9464     // Squash the masks to point directly into VLoHalf.
9465     for (int &M : LoBlendMask)
9466       if (M >= 0)
9467         M /= 2;
9468     for (int &M : HiBlendMask)
9469       if (M >= 0)
9470         M /= 2;
9471   } else {
9472     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9473     // VHiHalf so that we can blend them as i16s.
9474     VLoHalf = DAG.getBitcast(
9475         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9476     VHiHalf = DAG.getBitcast(
9477         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9478   }
9479
9480   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9481   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9482
9483   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9484 }
9485
9486 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9487 ///
9488 /// This routine breaks down the specific type of 128-bit shuffle and
9489 /// dispatches to the lowering routines accordingly.
9490 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9491                                         MVT VT, const X86Subtarget *Subtarget,
9492                                         SelectionDAG &DAG) {
9493   switch (VT.SimpleTy) {
9494   case MVT::v2i64:
9495     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9496   case MVT::v2f64:
9497     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9498   case MVT::v4i32:
9499     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9500   case MVT::v4f32:
9501     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9502   case MVT::v8i16:
9503     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9504   case MVT::v16i8:
9505     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9506
9507   default:
9508     llvm_unreachable("Unimplemented!");
9509   }
9510 }
9511
9512 /// \brief Helper function to test whether a shuffle mask could be
9513 /// simplified by widening the elements being shuffled.
9514 ///
9515 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9516 /// leaves it in an unspecified state.
9517 ///
9518 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9519 /// shuffle masks. The latter have the special property of a '-2' representing
9520 /// a zero-ed lane of a vector.
9521 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9522                                     SmallVectorImpl<int> &WidenedMask) {
9523   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9524     // If both elements are undef, its trivial.
9525     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9526       WidenedMask.push_back(SM_SentinelUndef);
9527       continue;
9528     }
9529
9530     // Check for an undef mask and a mask value properly aligned to fit with
9531     // a pair of values. If we find such a case, use the non-undef mask's value.
9532     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9533       WidenedMask.push_back(Mask[i + 1] / 2);
9534       continue;
9535     }
9536     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9537       WidenedMask.push_back(Mask[i] / 2);
9538       continue;
9539     }
9540
9541     // When zeroing, we need to spread the zeroing across both lanes to widen.
9542     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9543       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9544           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9545         WidenedMask.push_back(SM_SentinelZero);
9546         continue;
9547       }
9548       return false;
9549     }
9550
9551     // Finally check if the two mask values are adjacent and aligned with
9552     // a pair.
9553     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9554       WidenedMask.push_back(Mask[i] / 2);
9555       continue;
9556     }
9557
9558     // Otherwise we can't safely widen the elements used in this shuffle.
9559     return false;
9560   }
9561   assert(WidenedMask.size() == Mask.size() / 2 &&
9562          "Incorrect size of mask after widening the elements!");
9563
9564   return true;
9565 }
9566
9567 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9568 ///
9569 /// This routine just extracts two subvectors, shuffles them independently, and
9570 /// then concatenates them back together. This should work effectively with all
9571 /// AVX vector shuffle types.
9572 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9573                                           SDValue V2, ArrayRef<int> Mask,
9574                                           SelectionDAG &DAG) {
9575   assert(VT.getSizeInBits() >= 256 &&
9576          "Only for 256-bit or wider vector shuffles!");
9577   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9578   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9579
9580   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9581   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9582
9583   int NumElements = VT.getVectorNumElements();
9584   int SplitNumElements = NumElements / 2;
9585   MVT ScalarVT = VT.getScalarType();
9586   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9587
9588   // Rather than splitting build-vectors, just build two narrower build
9589   // vectors. This helps shuffling with splats and zeros.
9590   auto SplitVector = [&](SDValue V) {
9591     while (V.getOpcode() == ISD::BITCAST)
9592       V = V->getOperand(0);
9593
9594     MVT OrigVT = V.getSimpleValueType();
9595     int OrigNumElements = OrigVT.getVectorNumElements();
9596     int OrigSplitNumElements = OrigNumElements / 2;
9597     MVT OrigScalarVT = OrigVT.getScalarType();
9598     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9599
9600     SDValue LoV, HiV;
9601
9602     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9603     if (!BV) {
9604       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9605                         DAG.getIntPtrConstant(0, DL));
9606       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9607                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9608     } else {
9609
9610       SmallVector<SDValue, 16> LoOps, HiOps;
9611       for (int i = 0; i < OrigSplitNumElements; ++i) {
9612         LoOps.push_back(BV->getOperand(i));
9613         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9614       }
9615       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9616       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9617     }
9618     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9619                           DAG.getBitcast(SplitVT, HiV));
9620   };
9621
9622   SDValue LoV1, HiV1, LoV2, HiV2;
9623   std::tie(LoV1, HiV1) = SplitVector(V1);
9624   std::tie(LoV2, HiV2) = SplitVector(V2);
9625
9626   // Now create two 4-way blends of these half-width vectors.
9627   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9628     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9629     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9630     for (int i = 0; i < SplitNumElements; ++i) {
9631       int M = HalfMask[i];
9632       if (M >= NumElements) {
9633         if (M >= NumElements + SplitNumElements)
9634           UseHiV2 = true;
9635         else
9636           UseLoV2 = true;
9637         V2BlendMask.push_back(M - NumElements);
9638         V1BlendMask.push_back(-1);
9639         BlendMask.push_back(SplitNumElements + i);
9640       } else if (M >= 0) {
9641         if (M >= SplitNumElements)
9642           UseHiV1 = true;
9643         else
9644           UseLoV1 = true;
9645         V2BlendMask.push_back(-1);
9646         V1BlendMask.push_back(M);
9647         BlendMask.push_back(i);
9648       } else {
9649         V2BlendMask.push_back(-1);
9650         V1BlendMask.push_back(-1);
9651         BlendMask.push_back(-1);
9652       }
9653     }
9654
9655     // Because the lowering happens after all combining takes place, we need to
9656     // manually combine these blend masks as much as possible so that we create
9657     // a minimal number of high-level vector shuffle nodes.
9658
9659     // First try just blending the halves of V1 or V2.
9660     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9661       return DAG.getUNDEF(SplitVT);
9662     if (!UseLoV2 && !UseHiV2)
9663       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9664     if (!UseLoV1 && !UseHiV1)
9665       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9666
9667     SDValue V1Blend, V2Blend;
9668     if (UseLoV1 && UseHiV1) {
9669       V1Blend =
9670         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9671     } else {
9672       // We only use half of V1 so map the usage down into the final blend mask.
9673       V1Blend = UseLoV1 ? LoV1 : HiV1;
9674       for (int i = 0; i < SplitNumElements; ++i)
9675         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9676           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9677     }
9678     if (UseLoV2 && UseHiV2) {
9679       V2Blend =
9680         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9681     } else {
9682       // We only use half of V2 so map the usage down into the final blend mask.
9683       V2Blend = UseLoV2 ? LoV2 : HiV2;
9684       for (int i = 0; i < SplitNumElements; ++i)
9685         if (BlendMask[i] >= SplitNumElements)
9686           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9687     }
9688     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9689   };
9690   SDValue Lo = HalfBlend(LoMask);
9691   SDValue Hi = HalfBlend(HiMask);
9692   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9693 }
9694
9695 /// \brief Either split a vector in halves or decompose the shuffles and the
9696 /// blend.
9697 ///
9698 /// This is provided as a good fallback for many lowerings of non-single-input
9699 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9700 /// between splitting the shuffle into 128-bit components and stitching those
9701 /// back together vs. extracting the single-input shuffles and blending those
9702 /// results.
9703 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9704                                                 SDValue V2, ArrayRef<int> Mask,
9705                                                 SelectionDAG &DAG) {
9706   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9707                                             "lower single-input shuffles as it "
9708                                             "could then recurse on itself.");
9709   int Size = Mask.size();
9710
9711   // If this can be modeled as a broadcast of two elements followed by a blend,
9712   // prefer that lowering. This is especially important because broadcasts can
9713   // often fold with memory operands.
9714   auto DoBothBroadcast = [&] {
9715     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9716     for (int M : Mask)
9717       if (M >= Size) {
9718         if (V2BroadcastIdx == -1)
9719           V2BroadcastIdx = M - Size;
9720         else if (M - Size != V2BroadcastIdx)
9721           return false;
9722       } else if (M >= 0) {
9723         if (V1BroadcastIdx == -1)
9724           V1BroadcastIdx = M;
9725         else if (M != V1BroadcastIdx)
9726           return false;
9727       }
9728     return true;
9729   };
9730   if (DoBothBroadcast())
9731     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9732                                                       DAG);
9733
9734   // If the inputs all stem from a single 128-bit lane of each input, then we
9735   // split them rather than blending because the split will decompose to
9736   // unusually few instructions.
9737   int LaneCount = VT.getSizeInBits() / 128;
9738   int LaneSize = Size / LaneCount;
9739   SmallBitVector LaneInputs[2];
9740   LaneInputs[0].resize(LaneCount, false);
9741   LaneInputs[1].resize(LaneCount, false);
9742   for (int i = 0; i < Size; ++i)
9743     if (Mask[i] >= 0)
9744       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9745   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9746     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9747
9748   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9749   // that the decomposed single-input shuffles don't end up here.
9750   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9751 }
9752
9753 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9754 /// a permutation and blend of those lanes.
9755 ///
9756 /// This essentially blends the out-of-lane inputs to each lane into the lane
9757 /// from a permuted copy of the vector. This lowering strategy results in four
9758 /// instructions in the worst case for a single-input cross lane shuffle which
9759 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9760 /// of. Special cases for each particular shuffle pattern should be handled
9761 /// prior to trying this lowering.
9762 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9763                                                        SDValue V1, SDValue V2,
9764                                                        ArrayRef<int> Mask,
9765                                                        SelectionDAG &DAG) {
9766   // FIXME: This should probably be generalized for 512-bit vectors as well.
9767   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9768   int LaneSize = Mask.size() / 2;
9769
9770   // If there are only inputs from one 128-bit lane, splitting will in fact be
9771   // less expensive. The flags track whether the given lane contains an element
9772   // that crosses to another lane.
9773   bool LaneCrossing[2] = {false, false};
9774   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9775     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9776       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9777   if (!LaneCrossing[0] || !LaneCrossing[1])
9778     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9779
9780   if (isSingleInputShuffleMask(Mask)) {
9781     SmallVector<int, 32> FlippedBlendMask;
9782     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9783       FlippedBlendMask.push_back(
9784           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9785                                   ? Mask[i]
9786                                   : Mask[i] % LaneSize +
9787                                         (i / LaneSize) * LaneSize + Size));
9788
9789     // Flip the vector, and blend the results which should now be in-lane. The
9790     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9791     // 5 for the high source. The value 3 selects the high half of source 2 and
9792     // the value 2 selects the low half of source 2. We only use source 2 to
9793     // allow folding it into a memory operand.
9794     unsigned PERMMask = 3 | 2 << 4;
9795     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9796                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9797     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9798   }
9799
9800   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9801   // will be handled by the above logic and a blend of the results, much like
9802   // other patterns in AVX.
9803   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9804 }
9805
9806 /// \brief Handle lowering 2-lane 128-bit shuffles.
9807 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9808                                         SDValue V2, ArrayRef<int> Mask,
9809                                         const X86Subtarget *Subtarget,
9810                                         SelectionDAG &DAG) {
9811   // TODO: If minimizing size and one of the inputs is a zero vector and the
9812   // the zero vector has only one use, we could use a VPERM2X128 to save the
9813   // instruction bytes needed to explicitly generate the zero vector.
9814
9815   // Blends are faster and handle all the non-lane-crossing cases.
9816   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9817                                                 Subtarget, DAG))
9818     return Blend;
9819
9820   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9821   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9822
9823   // If either input operand is a zero vector, use VPERM2X128 because its mask
9824   // allows us to replace the zero input with an implicit zero.
9825   if (!IsV1Zero && !IsV2Zero) {
9826     // Check for patterns which can be matched with a single insert of a 128-bit
9827     // subvector.
9828     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9829     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9830       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9831                                    VT.getVectorNumElements() / 2);
9832       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9833                                 DAG.getIntPtrConstant(0, DL));
9834       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9835                                 OnlyUsesV1 ? V1 : V2,
9836                                 DAG.getIntPtrConstant(0, DL));
9837       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9838     }
9839   }
9840
9841   // Otherwise form a 128-bit permutation. After accounting for undefs,
9842   // convert the 64-bit shuffle mask selection values into 128-bit
9843   // selection bits by dividing the indexes by 2 and shifting into positions
9844   // defined by a vperm2*128 instruction's immediate control byte.
9845
9846   // The immediate permute control byte looks like this:
9847   //    [1:0] - select 128 bits from sources for low half of destination
9848   //    [2]   - ignore
9849   //    [3]   - zero low half of destination
9850   //    [5:4] - select 128 bits from sources for high half of destination
9851   //    [6]   - ignore
9852   //    [7]   - zero high half of destination
9853
9854   int MaskLO = Mask[0];
9855   if (MaskLO == SM_SentinelUndef)
9856     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9857
9858   int MaskHI = Mask[2];
9859   if (MaskHI == SM_SentinelUndef)
9860     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9861
9862   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9863
9864   // If either input is a zero vector, replace it with an undef input.
9865   // Shuffle mask values <  4 are selecting elements of V1.
9866   // Shuffle mask values >= 4 are selecting elements of V2.
9867   // Adjust each half of the permute mask by clearing the half that was
9868   // selecting the zero vector and setting the zero mask bit.
9869   if (IsV1Zero) {
9870     V1 = DAG.getUNDEF(VT);
9871     if (MaskLO < 4)
9872       PermMask = (PermMask & 0xf0) | 0x08;
9873     if (MaskHI < 4)
9874       PermMask = (PermMask & 0x0f) | 0x80;
9875   }
9876   if (IsV2Zero) {
9877     V2 = DAG.getUNDEF(VT);
9878     if (MaskLO >= 4)
9879       PermMask = (PermMask & 0xf0) | 0x08;
9880     if (MaskHI >= 4)
9881       PermMask = (PermMask & 0x0f) | 0x80;
9882   }
9883
9884   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9885                      DAG.getConstant(PermMask, DL, MVT::i8));
9886 }
9887
9888 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9889 /// shuffling each lane.
9890 ///
9891 /// This will only succeed when the result of fixing the 128-bit lanes results
9892 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9893 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9894 /// the lane crosses early and then use simpler shuffles within each lane.
9895 ///
9896 /// FIXME: It might be worthwhile at some point to support this without
9897 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9898 /// in x86 only floating point has interesting non-repeating shuffles, and even
9899 /// those are still *marginally* more expensive.
9900 static SDValue lowerVectorShuffleByMerging128BitLanes(
9901     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9902     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9903   assert(!isSingleInputShuffleMask(Mask) &&
9904          "This is only useful with multiple inputs.");
9905
9906   int Size = Mask.size();
9907   int LaneSize = 128 / VT.getScalarSizeInBits();
9908   int NumLanes = Size / LaneSize;
9909   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9910
9911   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9912   // check whether the in-128-bit lane shuffles share a repeating pattern.
9913   SmallVector<int, 4> Lanes;
9914   Lanes.resize(NumLanes, -1);
9915   SmallVector<int, 4> InLaneMask;
9916   InLaneMask.resize(LaneSize, -1);
9917   for (int i = 0; i < Size; ++i) {
9918     if (Mask[i] < 0)
9919       continue;
9920
9921     int j = i / LaneSize;
9922
9923     if (Lanes[j] < 0) {
9924       // First entry we've seen for this lane.
9925       Lanes[j] = Mask[i] / LaneSize;
9926     } else if (Lanes[j] != Mask[i] / LaneSize) {
9927       // This doesn't match the lane selected previously!
9928       return SDValue();
9929     }
9930
9931     // Check that within each lane we have a consistent shuffle mask.
9932     int k = i % LaneSize;
9933     if (InLaneMask[k] < 0) {
9934       InLaneMask[k] = Mask[i] % LaneSize;
9935     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9936       // This doesn't fit a repeating in-lane mask.
9937       return SDValue();
9938     }
9939   }
9940
9941   // First shuffle the lanes into place.
9942   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9943                                 VT.getSizeInBits() / 64);
9944   SmallVector<int, 8> LaneMask;
9945   LaneMask.resize(NumLanes * 2, -1);
9946   for (int i = 0; i < NumLanes; ++i)
9947     if (Lanes[i] >= 0) {
9948       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9949       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9950     }
9951
9952   V1 = DAG.getBitcast(LaneVT, V1);
9953   V2 = DAG.getBitcast(LaneVT, V2);
9954   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9955
9956   // Cast it back to the type we actually want.
9957   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9958
9959   // Now do a simple shuffle that isn't lane crossing.
9960   SmallVector<int, 8> NewMask;
9961   NewMask.resize(Size, -1);
9962   for (int i = 0; i < Size; ++i)
9963     if (Mask[i] >= 0)
9964       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9965   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9966          "Must not introduce lane crosses at this point!");
9967
9968   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9969 }
9970
9971 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9972 /// given mask.
9973 ///
9974 /// This returns true if the elements from a particular input are already in the
9975 /// slot required by the given mask and require no permutation.
9976 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9977   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9978   int Size = Mask.size();
9979   for (int i = 0; i < Size; ++i)
9980     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9981       return false;
9982
9983   return true;
9984 }
9985
9986 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9987                                             ArrayRef<int> Mask, SDValue V1,
9988                                             SDValue V2, SelectionDAG &DAG) {
9989
9990   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9991   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9992   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9993   int NumElts = VT.getVectorNumElements();
9994   bool ShufpdMask = true;
9995   bool CommutableMask = true;
9996   unsigned Immediate = 0;
9997   for (int i = 0; i < NumElts; ++i) {
9998     if (Mask[i] < 0)
9999       continue;
10000     int Val = (i & 6) + NumElts * (i & 1);
10001     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10002     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10003       ShufpdMask = false;
10004     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10005       CommutableMask = false;
10006     Immediate |= (Mask[i] % 2) << i;
10007   }
10008   if (ShufpdMask)
10009     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10010                        DAG.getConstant(Immediate, DL, MVT::i8));
10011   if (CommutableMask)
10012     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10013                        DAG.getConstant(Immediate, DL, MVT::i8));
10014   return SDValue();
10015 }
10016
10017 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10018 ///
10019 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10020 /// isn't available.
10021 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10022                                        const X86Subtarget *Subtarget,
10023                                        SelectionDAG &DAG) {
10024   SDLoc DL(Op);
10025   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10026   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10027   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10028   ArrayRef<int> Mask = SVOp->getMask();
10029   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10030
10031   SmallVector<int, 4> WidenedMask;
10032   if (canWidenShuffleElements(Mask, WidenedMask))
10033     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10034                                     DAG);
10035
10036   if (isSingleInputShuffleMask(Mask)) {
10037     // Check for being able to broadcast a single element.
10038     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10039                                                           Mask, Subtarget, DAG))
10040       return Broadcast;
10041
10042     // Use low duplicate instructions for masks that match their pattern.
10043     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10044       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10045
10046     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10047       // Non-half-crossing single input shuffles can be lowerid with an
10048       // interleaved permutation.
10049       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10050                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10051       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10052                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10053     }
10054
10055     // With AVX2 we have direct support for this permutation.
10056     if (Subtarget->hasAVX2())
10057       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10058                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10059
10060     // Otherwise, fall back.
10061     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10062                                                    DAG);
10063   }
10064
10065   // X86 has dedicated unpack instructions that can handle specific blend
10066   // operations: UNPCKH and UNPCKL.
10067   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10068     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
10069   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10070     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
10071   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10072     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
10073   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10074     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
10075
10076   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10077                                                 Subtarget, DAG))
10078     return Blend;
10079
10080   // Check if the blend happens to exactly fit that of SHUFPD.
10081   if (SDValue Op =
10082       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10083     return Op;
10084
10085   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10086   // shuffle. However, if we have AVX2 and either inputs are already in place,
10087   // we will be able to shuffle even across lanes the other input in a single
10088   // instruction so skip this pattern.
10089   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10090                                  isShuffleMaskInputInPlace(1, Mask))))
10091     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10092             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10093       return Result;
10094
10095   // If we have AVX2 then we always want to lower with a blend because an v4 we
10096   // can fully permute the elements.
10097   if (Subtarget->hasAVX2())
10098     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10099                                                       Mask, DAG);
10100
10101   // Otherwise fall back on generic lowering.
10102   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10103 }
10104
10105 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10106 ///
10107 /// This routine is only called when we have AVX2 and thus a reasonable
10108 /// instruction set for v4i64 shuffling..
10109 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10110                                        const X86Subtarget *Subtarget,
10111                                        SelectionDAG &DAG) {
10112   SDLoc DL(Op);
10113   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10114   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10115   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10116   ArrayRef<int> Mask = SVOp->getMask();
10117   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10118   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10119
10120   SmallVector<int, 4> WidenedMask;
10121   if (canWidenShuffleElements(Mask, WidenedMask))
10122     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10123                                     DAG);
10124
10125   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10126                                                 Subtarget, DAG))
10127     return Blend;
10128
10129   // Check for being able to broadcast a single element.
10130   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10131                                                         Mask, Subtarget, DAG))
10132     return Broadcast;
10133
10134   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10135   // use lower latency instructions that will operate on both 128-bit lanes.
10136   SmallVector<int, 2> RepeatedMask;
10137   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10138     if (isSingleInputShuffleMask(Mask)) {
10139       int PSHUFDMask[] = {-1, -1, -1, -1};
10140       for (int i = 0; i < 2; ++i)
10141         if (RepeatedMask[i] >= 0) {
10142           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10143           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10144         }
10145       return DAG.getBitcast(
10146           MVT::v4i64,
10147           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10148                       DAG.getBitcast(MVT::v8i32, V1),
10149                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10150     }
10151   }
10152
10153   // AVX2 provides a direct instruction for permuting a single input across
10154   // lanes.
10155   if (isSingleInputShuffleMask(Mask))
10156     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10157                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10158
10159   // Try to use shift instructions.
10160   if (SDValue Shift =
10161           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10162     return Shift;
10163
10164   // Use dedicated unpack instructions for masks that match their pattern.
10165   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10166     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
10167   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10168     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
10169   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10170     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
10171   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10172     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
10173
10174   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10175   // shuffle. However, if we have AVX2 and either inputs are already in place,
10176   // we will be able to shuffle even across lanes the other input in a single
10177   // instruction so skip this pattern.
10178   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10179                                  isShuffleMaskInputInPlace(1, Mask))))
10180     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10181             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10182       return Result;
10183
10184   // Otherwise fall back on generic blend lowering.
10185   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10186                                                     Mask, DAG);
10187 }
10188
10189 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10190 ///
10191 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10192 /// isn't available.
10193 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10194                                        const X86Subtarget *Subtarget,
10195                                        SelectionDAG &DAG) {
10196   SDLoc DL(Op);
10197   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10198   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10199   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10200   ArrayRef<int> Mask = SVOp->getMask();
10201   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10202
10203   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10204                                                 Subtarget, DAG))
10205     return Blend;
10206
10207   // Check for being able to broadcast a single element.
10208   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10209                                                         Mask, Subtarget, DAG))
10210     return Broadcast;
10211
10212   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10213   // options to efficiently lower the shuffle.
10214   SmallVector<int, 4> RepeatedMask;
10215   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10216     assert(RepeatedMask.size() == 4 &&
10217            "Repeated masks must be half the mask width!");
10218
10219     // Use even/odd duplicate instructions for masks that match their pattern.
10220     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10221       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10222     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10223       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10224
10225     if (isSingleInputShuffleMask(Mask))
10226       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10227                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10228
10229     // Use dedicated unpack instructions for masks that match their pattern.
10230     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10231       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10232     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10233       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10234     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10235       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10236     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10237       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10238
10239     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10240     // have already handled any direct blends. We also need to squash the
10241     // repeated mask into a simulated v4f32 mask.
10242     for (int i = 0; i < 4; ++i)
10243       if (RepeatedMask[i] >= 8)
10244         RepeatedMask[i] -= 4;
10245     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10246   }
10247
10248   // If we have a single input shuffle with different shuffle patterns in the
10249   // two 128-bit lanes use the variable mask to VPERMILPS.
10250   if (isSingleInputShuffleMask(Mask)) {
10251     SDValue VPermMask[8];
10252     for (int i = 0; i < 8; ++i)
10253       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10254                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10255     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10256       return DAG.getNode(
10257           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10258           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10259
10260     if (Subtarget->hasAVX2())
10261       return DAG.getNode(
10262           X86ISD::VPERMV, DL, MVT::v8f32,
10263           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10264                                                  MVT::v8i32, VPermMask)),
10265           V1);
10266
10267     // Otherwise, fall back.
10268     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10269                                                    DAG);
10270   }
10271
10272   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10273   // shuffle.
10274   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10275           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10276     return Result;
10277
10278   // If we have AVX2 then we always want to lower with a blend because at v8 we
10279   // can fully permute the elements.
10280   if (Subtarget->hasAVX2())
10281     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10282                                                       Mask, DAG);
10283
10284   // Otherwise fall back on generic lowering.
10285   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10286 }
10287
10288 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10289 ///
10290 /// This routine is only called when we have AVX2 and thus a reasonable
10291 /// instruction set for v8i32 shuffling..
10292 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10293                                        const X86Subtarget *Subtarget,
10294                                        SelectionDAG &DAG) {
10295   SDLoc DL(Op);
10296   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10297   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10298   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10299   ArrayRef<int> Mask = SVOp->getMask();
10300   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10301   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10302
10303   // Whenever we can lower this as a zext, that instruction is strictly faster
10304   // than any alternative. It also allows us to fold memory operands into the
10305   // shuffle in many cases.
10306   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10307                                                          Mask, Subtarget, DAG))
10308     return ZExt;
10309
10310   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10311                                                 Subtarget, DAG))
10312     return Blend;
10313
10314   // Check for being able to broadcast a single element.
10315   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10316                                                         Mask, Subtarget, DAG))
10317     return Broadcast;
10318
10319   // If the shuffle mask is repeated in each 128-bit lane we can use more
10320   // efficient instructions that mirror the shuffles across the two 128-bit
10321   // lanes.
10322   SmallVector<int, 4> RepeatedMask;
10323   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10324     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10325     if (isSingleInputShuffleMask(Mask))
10326       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10327                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10328
10329     // Use dedicated unpack instructions for masks that match their pattern.
10330     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10331       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10332     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10333       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10334     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10335       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10336     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10337       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10338   }
10339
10340   // Try to use shift instructions.
10341   if (SDValue Shift =
10342           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10343     return Shift;
10344
10345   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10346           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10347     return Rotate;
10348
10349   // If the shuffle patterns aren't repeated but it is a single input, directly
10350   // generate a cross-lane VPERMD instruction.
10351   if (isSingleInputShuffleMask(Mask)) {
10352     SDValue VPermMask[8];
10353     for (int i = 0; i < 8; ++i)
10354       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10355                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10356     return DAG.getNode(
10357         X86ISD::VPERMV, DL, MVT::v8i32,
10358         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10359   }
10360
10361   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10362   // shuffle.
10363   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10364           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10365     return Result;
10366
10367   // Otherwise fall back on generic blend lowering.
10368   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10369                                                     Mask, DAG);
10370 }
10371
10372 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10373 ///
10374 /// This routine is only called when we have AVX2 and thus a reasonable
10375 /// instruction set for v16i16 shuffling..
10376 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10377                                         const X86Subtarget *Subtarget,
10378                                         SelectionDAG &DAG) {
10379   SDLoc DL(Op);
10380   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10381   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10382   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10383   ArrayRef<int> Mask = SVOp->getMask();
10384   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10385   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10386
10387   // Whenever we can lower this as a zext, that instruction is strictly faster
10388   // than any alternative. It also allows us to fold memory operands into the
10389   // shuffle in many cases.
10390   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10391                                                          Mask, Subtarget, DAG))
10392     return ZExt;
10393
10394   // Check for being able to broadcast a single element.
10395   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10396                                                         Mask, Subtarget, DAG))
10397     return Broadcast;
10398
10399   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10400                                                 Subtarget, DAG))
10401     return Blend;
10402
10403   // Use dedicated unpack instructions for masks that match their pattern.
10404   if (isShuffleEquivalent(V1, V2, Mask,
10405                           {// First 128-bit lane:
10406                            0, 16, 1, 17, 2, 18, 3, 19,
10407                            // Second 128-bit lane:
10408                            8, 24, 9, 25, 10, 26, 11, 27}))
10409     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10410   if (isShuffleEquivalent(V1, V2, Mask,
10411                           {// First 128-bit lane:
10412                            4, 20, 5, 21, 6, 22, 7, 23,
10413                            // Second 128-bit lane:
10414                            12, 28, 13, 29, 14, 30, 15, 31}))
10415     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10416
10417   // Try to use shift instructions.
10418   if (SDValue Shift =
10419           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10420     return Shift;
10421
10422   // Try to use byte rotation instructions.
10423   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10424           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10425     return Rotate;
10426
10427   if (isSingleInputShuffleMask(Mask)) {
10428     // There are no generalized cross-lane shuffle operations available on i16
10429     // element types.
10430     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10431       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10432                                                      Mask, DAG);
10433
10434     SmallVector<int, 8> RepeatedMask;
10435     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10436       // As this is a single-input shuffle, the repeated mask should be
10437       // a strictly valid v8i16 mask that we can pass through to the v8i16
10438       // lowering to handle even the v16 case.
10439       return lowerV8I16GeneralSingleInputVectorShuffle(
10440           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10441     }
10442
10443     SDValue PSHUFBMask[32];
10444     for (int i = 0; i < 16; ++i) {
10445       if (Mask[i] == -1) {
10446         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10447         continue;
10448       }
10449
10450       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10451       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10452       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10453       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10454     }
10455     return DAG.getBitcast(MVT::v16i16,
10456                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10457                                       DAG.getBitcast(MVT::v32i8, V1),
10458                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10459                                                   MVT::v32i8, PSHUFBMask)));
10460   }
10461
10462   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10463   // shuffle.
10464   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10465           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10466     return Result;
10467
10468   // Otherwise fall back on generic lowering.
10469   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10470 }
10471
10472 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10473 ///
10474 /// This routine is only called when we have AVX2 and thus a reasonable
10475 /// instruction set for v32i8 shuffling..
10476 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10477                                        const X86Subtarget *Subtarget,
10478                                        SelectionDAG &DAG) {
10479   SDLoc DL(Op);
10480   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10481   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10482   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10483   ArrayRef<int> Mask = SVOp->getMask();
10484   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10485   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10486
10487   // Whenever we can lower this as a zext, that instruction is strictly faster
10488   // than any alternative. It also allows us to fold memory operands into the
10489   // shuffle in many cases.
10490   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10491                                                          Mask, Subtarget, DAG))
10492     return ZExt;
10493
10494   // Check for being able to broadcast a single element.
10495   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10496                                                         Mask, Subtarget, DAG))
10497     return Broadcast;
10498
10499   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10500                                                 Subtarget, DAG))
10501     return Blend;
10502
10503   // Use dedicated unpack instructions for masks that match their pattern.
10504   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10505   // 256-bit lanes.
10506   if (isShuffleEquivalent(
10507           V1, V2, Mask,
10508           {// First 128-bit lane:
10509            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10510            // Second 128-bit lane:
10511            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10512     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10513   if (isShuffleEquivalent(
10514           V1, V2, Mask,
10515           {// First 128-bit lane:
10516            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10517            // Second 128-bit lane:
10518            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10519     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10520
10521   // Try to use shift instructions.
10522   if (SDValue Shift =
10523           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10524     return Shift;
10525
10526   // Try to use byte rotation instructions.
10527   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10528           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10529     return Rotate;
10530
10531   if (isSingleInputShuffleMask(Mask)) {
10532     // There are no generalized cross-lane shuffle operations available on i8
10533     // element types.
10534     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10535       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10536                                                      Mask, DAG);
10537
10538     SDValue PSHUFBMask[32];
10539     for (int i = 0; i < 32; ++i)
10540       PSHUFBMask[i] =
10541           Mask[i] < 0
10542               ? DAG.getUNDEF(MVT::i8)
10543               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10544                                 MVT::i8);
10545
10546     return DAG.getNode(
10547         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10548         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10549   }
10550
10551   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10552   // shuffle.
10553   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10554           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10555     return Result;
10556
10557   // Otherwise fall back on generic lowering.
10558   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10559 }
10560
10561 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10562 ///
10563 /// This routine either breaks down the specific type of a 256-bit x86 vector
10564 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10565 /// together based on the available instructions.
10566 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10567                                         MVT VT, const X86Subtarget *Subtarget,
10568                                         SelectionDAG &DAG) {
10569   SDLoc DL(Op);
10570   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10571   ArrayRef<int> Mask = SVOp->getMask();
10572
10573   // If we have a single input to the zero element, insert that into V1 if we
10574   // can do so cheaply.
10575   int NumElts = VT.getVectorNumElements();
10576   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10577     return M >= NumElts;
10578   });
10579
10580   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10581     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10582                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10583       return Insertion;
10584
10585   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10586   // check for those subtargets here and avoid much of the subtarget querying in
10587   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10588   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10589   // floating point types there eventually, just immediately cast everything to
10590   // a float and operate entirely in that domain.
10591   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10592     int ElementBits = VT.getScalarSizeInBits();
10593     if (ElementBits < 32)
10594       // No floating point type available, decompose into 128-bit vectors.
10595       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10596
10597     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10598                                 VT.getVectorNumElements());
10599     V1 = DAG.getBitcast(FpVT, V1);
10600     V2 = DAG.getBitcast(FpVT, V2);
10601     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10602   }
10603
10604   switch (VT.SimpleTy) {
10605   case MVT::v4f64:
10606     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10607   case MVT::v4i64:
10608     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10609   case MVT::v8f32:
10610     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10611   case MVT::v8i32:
10612     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10613   case MVT::v16i16:
10614     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10615   case MVT::v32i8:
10616     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10617
10618   default:
10619     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10620   }
10621 }
10622
10623 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10624                                            ArrayRef<int> Mask, SDValue V1,
10625                                            SDValue V2, SelectionDAG &DAG) {
10626
10627   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10628
10629   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10630   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10631
10632   SmallVector<SDValue, 32>  VPermMask;
10633   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i)
10634     VPermMask.push_back(Mask[i] < 0 ? DAG.getUNDEF(MaskEltVT) :
10635                         DAG.getConstant(Mask[i], DL, MaskEltVT));
10636   SDValue MaskNode = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVecVT,
10637                                  VPermMask);
10638   if (isSingleInputShuffleMask(Mask))
10639     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10640
10641   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10642 }
10643
10644 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10645 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10646                                        const X86Subtarget *Subtarget,
10647                                        SelectionDAG &DAG) {
10648   SDLoc DL(Op);
10649   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10650   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10651   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10652   ArrayRef<int> Mask = SVOp->getMask();
10653   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10654
10655   if (SDValue Unpck =
10656           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
10657     return Unpck;
10658
10659   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10660 }
10661
10662 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10663 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10664                                        const X86Subtarget *Subtarget,
10665                                        SelectionDAG &DAG) {
10666   SDLoc DL(Op);
10667   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10668   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10669   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10670   ArrayRef<int> Mask = SVOp->getMask();
10671   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10672
10673   if (SDValue Unpck =
10674           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
10675     return Unpck;
10676
10677   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
10678 }
10679
10680 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10681 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10682                                        const X86Subtarget *Subtarget,
10683                                        SelectionDAG &DAG) {
10684   SDLoc DL(Op);
10685   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10686   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10687   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10688   ArrayRef<int> Mask = SVOp->getMask();
10689   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10690
10691   if (SDValue Unpck =
10692           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
10693     return Unpck;
10694
10695   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
10696 }
10697
10698 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10699 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10700                                        const X86Subtarget *Subtarget,
10701                                        SelectionDAG &DAG) {
10702   SDLoc DL(Op);
10703   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10704   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10705   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10706   ArrayRef<int> Mask = SVOp->getMask();
10707   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10708
10709   if (SDValue Unpck =
10710           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
10711     return Unpck;
10712
10713   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
10714 }
10715
10716 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10717 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10718                                         const X86Subtarget *Subtarget,
10719                                         SelectionDAG &DAG) {
10720   SDLoc DL(Op);
10721   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10722   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10723   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10724   ArrayRef<int> Mask = SVOp->getMask();
10725   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10726   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10727
10728   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
10729 }
10730
10731 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10732 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10733                                        const X86Subtarget *Subtarget,
10734                                        SelectionDAG &DAG) {
10735   SDLoc DL(Op);
10736   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10737   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10738   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10739   ArrayRef<int> Mask = SVOp->getMask();
10740   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10741   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10742
10743   // FIXME: Implement direct support for this type!
10744   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10745 }
10746
10747 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10748 ///
10749 /// This routine either breaks down the specific type of a 512-bit x86 vector
10750 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10751 /// together based on the available instructions.
10752 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10753                                         MVT VT, const X86Subtarget *Subtarget,
10754                                         SelectionDAG &DAG) {
10755   SDLoc DL(Op);
10756   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10757   ArrayRef<int> Mask = SVOp->getMask();
10758   assert(Subtarget->hasAVX512() &&
10759          "Cannot lower 512-bit vectors w/ basic ISA!");
10760
10761   // Check for being able to broadcast a single element.
10762   if (SDValue Broadcast =
10763           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10764     return Broadcast;
10765
10766   // Dispatch to each element type for lowering. If we don't have supprot for
10767   // specific element type shuffles at 512 bits, immediately split them and
10768   // lower them. Each lowering routine of a given type is allowed to assume that
10769   // the requisite ISA extensions for that element type are available.
10770   switch (VT.SimpleTy) {
10771   case MVT::v8f64:
10772     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10773   case MVT::v16f32:
10774     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10775   case MVT::v8i64:
10776     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10777   case MVT::v16i32:
10778     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10779   case MVT::v32i16:
10780     if (Subtarget->hasBWI())
10781       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10782     break;
10783   case MVT::v64i8:
10784     if (Subtarget->hasBWI())
10785       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10786     break;
10787
10788   default:
10789     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10790   }
10791
10792   // Otherwise fall back on splitting.
10793   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10794 }
10795
10796 // Lower vXi1 vector shuffles.
10797 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
10798 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
10799 // vector, shuffle and then truncate it back.
10800 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10801                                       MVT VT, const X86Subtarget *Subtarget,
10802                                       SelectionDAG &DAG) {
10803   SDLoc DL(Op);
10804   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10805   ArrayRef<int> Mask = SVOp->getMask();
10806   assert(Subtarget->hasAVX512() &&
10807          "Cannot lower 512-bit vectors w/o basic ISA!");
10808   EVT ExtVT;
10809   switch (VT.SimpleTy) {
10810   default:
10811     assert(false && "Expected a vector of i1 elements");
10812     break;
10813   case MVT::v2i1:
10814     ExtVT = MVT::v2i64;
10815     break;
10816   case MVT::v4i1:
10817     ExtVT = MVT::v4i32;
10818     break;
10819   case MVT::v8i1:
10820     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
10821     break;
10822   case MVT::v16i1:
10823     ExtVT = MVT::v16i32;
10824     break;
10825   case MVT::v32i1:
10826     ExtVT = MVT::v32i16;
10827     break;
10828   case MVT::v64i1:
10829     ExtVT = MVT::v64i8;
10830     break;
10831   }
10832
10833   if (ISD::isBuildVectorAllZeros(V1.getNode()))
10834     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10835   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
10836     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10837   else
10838     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
10839
10840   if (V2.isUndef())
10841     V2 = DAG.getUNDEF(ExtVT);
10842   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
10843     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10844   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
10845     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10846   else
10847     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
10848   return DAG.getNode(ISD::TRUNCATE, DL, VT,
10849                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
10850 }
10851 /// \brief Top-level lowering for x86 vector shuffles.
10852 ///
10853 /// This handles decomposition, canonicalization, and lowering of all x86
10854 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10855 /// above in helper routines. The canonicalization attempts to widen shuffles
10856 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10857 /// s.t. only one of the two inputs needs to be tested, etc.
10858 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10859                                   SelectionDAG &DAG) {
10860   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10861   ArrayRef<int> Mask = SVOp->getMask();
10862   SDValue V1 = Op.getOperand(0);
10863   SDValue V2 = Op.getOperand(1);
10864   MVT VT = Op.getSimpleValueType();
10865   int NumElements = VT.getVectorNumElements();
10866   SDLoc dl(Op);
10867   bool Is1BitVector = (VT.getScalarType() == MVT::i1);
10868
10869   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
10870          "Can't lower MMX shuffles");
10871
10872   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10873   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10874   if (V1IsUndef && V2IsUndef)
10875     return DAG.getUNDEF(VT);
10876
10877   // When we create a shuffle node we put the UNDEF node to second operand,
10878   // but in some cases the first operand may be transformed to UNDEF.
10879   // In this case we should just commute the node.
10880   if (V1IsUndef)
10881     return DAG.getCommutedVectorShuffle(*SVOp);
10882
10883   // Check for non-undef masks pointing at an undef vector and make the masks
10884   // undef as well. This makes it easier to match the shuffle based solely on
10885   // the mask.
10886   if (V2IsUndef)
10887     for (int M : Mask)
10888       if (M >= NumElements) {
10889         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10890         for (int &M : NewMask)
10891           if (M >= NumElements)
10892             M = -1;
10893         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10894       }
10895
10896   // We actually see shuffles that are entirely re-arrangements of a set of
10897   // zero inputs. This mostly happens while decomposing complex shuffles into
10898   // simple ones. Directly lower these as a buildvector of zeros.
10899   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10900   if (Zeroable.all())
10901     return getZeroVector(VT, Subtarget, DAG, dl);
10902
10903   // Try to collapse shuffles into using a vector type with fewer elements but
10904   // wider element types. We cap this to not form integers or floating point
10905   // elements wider than 64 bits, but it might be interesting to form i128
10906   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10907   SmallVector<int, 16> WidenedMask;
10908   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
10909       canWidenShuffleElements(Mask, WidenedMask)) {
10910     MVT NewEltVT = VT.isFloatingPoint()
10911                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10912                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10913     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10914     // Make sure that the new vector type is legal. For example, v2f64 isn't
10915     // legal on SSE1.
10916     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10917       V1 = DAG.getBitcast(NewVT, V1);
10918       V2 = DAG.getBitcast(NewVT, V2);
10919       return DAG.getBitcast(
10920           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10921     }
10922   }
10923
10924   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10925   for (int M : SVOp->getMask())
10926     if (M < 0)
10927       ++NumUndefElements;
10928     else if (M < NumElements)
10929       ++NumV1Elements;
10930     else
10931       ++NumV2Elements;
10932
10933   // Commute the shuffle as needed such that more elements come from V1 than
10934   // V2. This allows us to match the shuffle pattern strictly on how many
10935   // elements come from V1 without handling the symmetric cases.
10936   if (NumV2Elements > NumV1Elements)
10937     return DAG.getCommutedVectorShuffle(*SVOp);
10938
10939   // When the number of V1 and V2 elements are the same, try to minimize the
10940   // number of uses of V2 in the low half of the vector. When that is tied,
10941   // ensure that the sum of indices for V1 is equal to or lower than the sum
10942   // indices for V2. When those are equal, try to ensure that the number of odd
10943   // indices for V1 is lower than the number of odd indices for V2.
10944   if (NumV1Elements == NumV2Elements) {
10945     int LowV1Elements = 0, LowV2Elements = 0;
10946     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10947       if (M >= NumElements)
10948         ++LowV2Elements;
10949       else if (M >= 0)
10950         ++LowV1Elements;
10951     if (LowV2Elements > LowV1Elements) {
10952       return DAG.getCommutedVectorShuffle(*SVOp);
10953     } else if (LowV2Elements == LowV1Elements) {
10954       int SumV1Indices = 0, SumV2Indices = 0;
10955       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10956         if (SVOp->getMask()[i] >= NumElements)
10957           SumV2Indices += i;
10958         else if (SVOp->getMask()[i] >= 0)
10959           SumV1Indices += i;
10960       if (SumV2Indices < SumV1Indices) {
10961         return DAG.getCommutedVectorShuffle(*SVOp);
10962       } else if (SumV2Indices == SumV1Indices) {
10963         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10964         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10965           if (SVOp->getMask()[i] >= NumElements)
10966             NumV2OddIndices += i % 2;
10967           else if (SVOp->getMask()[i] >= 0)
10968             NumV1OddIndices += i % 2;
10969         if (NumV2OddIndices < NumV1OddIndices)
10970           return DAG.getCommutedVectorShuffle(*SVOp);
10971       }
10972     }
10973   }
10974
10975   // For each vector width, delegate to a specialized lowering routine.
10976   if (VT.getSizeInBits() == 128)
10977     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10978
10979   if (VT.getSizeInBits() == 256)
10980     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10981
10982   if (VT.getSizeInBits() == 512)
10983     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10984
10985   if (Is1BitVector)
10986     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10987   llvm_unreachable("Unimplemented!");
10988 }
10989
10990 // This function assumes its argument is a BUILD_VECTOR of constants or
10991 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10992 // true.
10993 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10994                                     unsigned &MaskValue) {
10995   MaskValue = 0;
10996   unsigned NumElems = BuildVector->getNumOperands();
10997   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10998   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10999   unsigned NumElemsInLane = NumElems / NumLanes;
11000
11001   // Blend for v16i16 should be symmetric for the both lanes.
11002   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11003     SDValue EltCond = BuildVector->getOperand(i);
11004     SDValue SndLaneEltCond =
11005         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11006
11007     int Lane1Cond = -1, Lane2Cond = -1;
11008     if (isa<ConstantSDNode>(EltCond))
11009       Lane1Cond = !isZero(EltCond);
11010     if (isa<ConstantSDNode>(SndLaneEltCond))
11011       Lane2Cond = !isZero(SndLaneEltCond);
11012
11013     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11014       // Lane1Cond != 0, means we want the first argument.
11015       // Lane1Cond == 0, means we want the second argument.
11016       // The encoding of this argument is 0 for the first argument, 1
11017       // for the second. Therefore, invert the condition.
11018       MaskValue |= !Lane1Cond << i;
11019     else if (Lane1Cond < 0)
11020       MaskValue |= !Lane2Cond << i;
11021     else
11022       return false;
11023   }
11024   return true;
11025 }
11026
11027 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11028 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11029                                            const X86Subtarget *Subtarget,
11030                                            SelectionDAG &DAG) {
11031   SDValue Cond = Op.getOperand(0);
11032   SDValue LHS = Op.getOperand(1);
11033   SDValue RHS = Op.getOperand(2);
11034   SDLoc dl(Op);
11035   MVT VT = Op.getSimpleValueType();
11036
11037   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11038     return SDValue();
11039   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11040
11041   // Only non-legal VSELECTs reach this lowering, convert those into generic
11042   // shuffles and re-use the shuffle lowering path for blends.
11043   SmallVector<int, 32> Mask;
11044   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11045     SDValue CondElt = CondBV->getOperand(i);
11046     Mask.push_back(
11047         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
11048   }
11049   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11050 }
11051
11052 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11053   // A vselect where all conditions and data are constants can be optimized into
11054   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11055   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11056       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11057       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11058     return SDValue();
11059
11060   // Try to lower this to a blend-style vector shuffle. This can handle all
11061   // constant condition cases.
11062   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11063     return BlendOp;
11064
11065   // Variable blends are only legal from SSE4.1 onward.
11066   if (!Subtarget->hasSSE41())
11067     return SDValue();
11068
11069   // Only some types will be legal on some subtargets. If we can emit a legal
11070   // VSELECT-matching blend, return Op, and but if we need to expand, return
11071   // a null value.
11072   switch (Op.getSimpleValueType().SimpleTy) {
11073   default:
11074     // Most of the vector types have blends past SSE4.1.
11075     return Op;
11076
11077   case MVT::v32i8:
11078     // The byte blends for AVX vectors were introduced only in AVX2.
11079     if (Subtarget->hasAVX2())
11080       return Op;
11081
11082     return SDValue();
11083
11084   case MVT::v8i16:
11085   case MVT::v16i16:
11086     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11087     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11088       return Op;
11089
11090     // FIXME: We should custom lower this by fixing the condition and using i8
11091     // blends.
11092     return SDValue();
11093   }
11094 }
11095
11096 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11097   MVT VT = Op.getSimpleValueType();
11098   SDLoc dl(Op);
11099
11100   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11101     return SDValue();
11102
11103   if (VT.getSizeInBits() == 8) {
11104     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11105                                   Op.getOperand(0), Op.getOperand(1));
11106     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11107                                   DAG.getValueType(VT));
11108     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11109   }
11110
11111   if (VT.getSizeInBits() == 16) {
11112     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11113     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11114     if (Idx == 0)
11115       return DAG.getNode(
11116           ISD::TRUNCATE, dl, MVT::i16,
11117           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11118                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11119                       Op.getOperand(1)));
11120     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11121                                   Op.getOperand(0), Op.getOperand(1));
11122     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11123                                   DAG.getValueType(VT));
11124     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11125   }
11126
11127   if (VT == MVT::f32) {
11128     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11129     // the result back to FR32 register. It's only worth matching if the
11130     // result has a single use which is a store or a bitcast to i32.  And in
11131     // the case of a store, it's not worth it if the index is a constant 0,
11132     // because a MOVSSmr can be used instead, which is smaller and faster.
11133     if (!Op.hasOneUse())
11134       return SDValue();
11135     SDNode *User = *Op.getNode()->use_begin();
11136     if ((User->getOpcode() != ISD::STORE ||
11137          (isa<ConstantSDNode>(Op.getOperand(1)) &&
11138           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11139         (User->getOpcode() != ISD::BITCAST ||
11140          User->getValueType(0) != MVT::i32))
11141       return SDValue();
11142     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11143                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11144                                   Op.getOperand(1));
11145     return DAG.getBitcast(MVT::f32, Extract);
11146   }
11147
11148   if (VT == MVT::i32 || VT == MVT::i64) {
11149     // ExtractPS/pextrq works with constant index.
11150     if (isa<ConstantSDNode>(Op.getOperand(1)))
11151       return Op;
11152   }
11153   return SDValue();
11154 }
11155
11156 /// Extract one bit from mask vector, like v16i1 or v8i1.
11157 /// AVX-512 feature.
11158 SDValue
11159 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11160   SDValue Vec = Op.getOperand(0);
11161   SDLoc dl(Vec);
11162   MVT VecVT = Vec.getSimpleValueType();
11163   SDValue Idx = Op.getOperand(1);
11164   MVT EltVT = Op.getSimpleValueType();
11165
11166   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11167   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11168          "Unexpected vector type in ExtractBitFromMaskVector");
11169
11170   // variable index can't be handled in mask registers,
11171   // extend vector to VR512
11172   if (!isa<ConstantSDNode>(Idx)) {
11173     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11174     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11175     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11176                               ExtVT.getVectorElementType(), Ext, Idx);
11177     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11178   }
11179
11180   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11181   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11182   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11183     rc = getRegClassFor(MVT::v16i1);
11184   unsigned MaxSift = rc->getSize()*8 - 1;
11185   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11186                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11187   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11188                     DAG.getConstant(MaxSift, dl, MVT::i8));
11189   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11190                        DAG.getIntPtrConstant(0, dl));
11191 }
11192
11193 SDValue
11194 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11195                                            SelectionDAG &DAG) const {
11196   SDLoc dl(Op);
11197   SDValue Vec = Op.getOperand(0);
11198   MVT VecVT = Vec.getSimpleValueType();
11199   SDValue Idx = Op.getOperand(1);
11200
11201   if (Op.getSimpleValueType() == MVT::i1)
11202     return ExtractBitFromMaskVector(Op, DAG);
11203
11204   if (!isa<ConstantSDNode>(Idx)) {
11205     if (VecVT.is512BitVector() ||
11206         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11207          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11208
11209       MVT MaskEltVT =
11210         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11211       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11212                                     MaskEltVT.getSizeInBits());
11213
11214       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11215       auto PtrVT = getPointerTy(DAG.getDataLayout());
11216       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11217                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11218                                  DAG.getConstant(0, dl, PtrVT));
11219       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11220       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11221                          DAG.getConstant(0, dl, PtrVT));
11222     }
11223     return SDValue();
11224   }
11225
11226   // If this is a 256-bit vector result, first extract the 128-bit vector and
11227   // then extract the element from the 128-bit vector.
11228   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11229
11230     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11231     // Get the 128-bit vector.
11232     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11233     MVT EltVT = VecVT.getVectorElementType();
11234
11235     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11236
11237     //if (IdxVal >= NumElems/2)
11238     //  IdxVal -= NumElems/2;
11239     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
11240     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11241                        DAG.getConstant(IdxVal, dl, MVT::i32));
11242   }
11243
11244   assert(VecVT.is128BitVector() && "Unexpected vector length");
11245
11246   if (Subtarget->hasSSE41())
11247     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11248       return Res;
11249
11250   MVT VT = Op.getSimpleValueType();
11251   // TODO: handle v16i8.
11252   if (VT.getSizeInBits() == 16) {
11253     SDValue Vec = Op.getOperand(0);
11254     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11255     if (Idx == 0)
11256       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11257                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11258                                      DAG.getBitcast(MVT::v4i32, Vec),
11259                                      Op.getOperand(1)));
11260     // Transform it so it match pextrw which produces a 32-bit result.
11261     MVT EltVT = MVT::i32;
11262     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11263                                   Op.getOperand(0), Op.getOperand(1));
11264     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11265                                   DAG.getValueType(VT));
11266     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11267   }
11268
11269   if (VT.getSizeInBits() == 32) {
11270     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11271     if (Idx == 0)
11272       return Op;
11273
11274     // SHUFPS the element to the lowest double word, then movss.
11275     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11276     MVT VVT = Op.getOperand(0).getSimpleValueType();
11277     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11278                                        DAG.getUNDEF(VVT), Mask);
11279     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11280                        DAG.getIntPtrConstant(0, dl));
11281   }
11282
11283   if (VT.getSizeInBits() == 64) {
11284     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11285     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11286     //        to match extract_elt for f64.
11287     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11288     if (Idx == 0)
11289       return Op;
11290
11291     // UNPCKHPD the element to the lowest double word, then movsd.
11292     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11293     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11294     int Mask[2] = { 1, -1 };
11295     MVT VVT = Op.getOperand(0).getSimpleValueType();
11296     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11297                                        DAG.getUNDEF(VVT), Mask);
11298     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11299                        DAG.getIntPtrConstant(0, dl));
11300   }
11301
11302   return SDValue();
11303 }
11304
11305 /// Insert one bit to mask vector, like v16i1 or v8i1.
11306 /// AVX-512 feature.
11307 SDValue
11308 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11309   SDLoc dl(Op);
11310   SDValue Vec = Op.getOperand(0);
11311   SDValue Elt = Op.getOperand(1);
11312   SDValue Idx = Op.getOperand(2);
11313   MVT VecVT = Vec.getSimpleValueType();
11314
11315   if (!isa<ConstantSDNode>(Idx)) {
11316     // Non constant index. Extend source and destination,
11317     // insert element and then truncate the result.
11318     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11319     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11320     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11321       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11322       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11323     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11324   }
11325
11326   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11327   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11328   if (IdxVal)
11329     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11330                            DAG.getConstant(IdxVal, dl, MVT::i8));
11331   if (Vec.getOpcode() == ISD::UNDEF)
11332     return EltInVec;
11333   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11334 }
11335
11336 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11337                                                   SelectionDAG &DAG) const {
11338   MVT VT = Op.getSimpleValueType();
11339   MVT EltVT = VT.getVectorElementType();
11340
11341   if (EltVT == MVT::i1)
11342     return InsertBitToMaskVector(Op, DAG);
11343
11344   SDLoc dl(Op);
11345   SDValue N0 = Op.getOperand(0);
11346   SDValue N1 = Op.getOperand(1);
11347   SDValue N2 = Op.getOperand(2);
11348   if (!isa<ConstantSDNode>(N2))
11349     return SDValue();
11350   auto *N2C = cast<ConstantSDNode>(N2);
11351   unsigned IdxVal = N2C->getZExtValue();
11352
11353   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11354   // into that, and then insert the subvector back into the result.
11355   if (VT.is256BitVector() || VT.is512BitVector()) {
11356     // With a 256-bit vector, we can insert into the zero element efficiently
11357     // using a blend if we have AVX or AVX2 and the right data type.
11358     if (VT.is256BitVector() && IdxVal == 0) {
11359       // TODO: It is worthwhile to cast integer to floating point and back
11360       // and incur a domain crossing penalty if that's what we'll end up
11361       // doing anyway after extracting to a 128-bit vector.
11362       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11363           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11364         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11365         N2 = DAG.getIntPtrConstant(1, dl);
11366         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11367       }
11368     }
11369
11370     // Get the desired 128-bit vector chunk.
11371     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11372
11373     // Insert the element into the desired chunk.
11374     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11375     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11376
11377     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11378                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11379
11380     // Insert the changed part back into the bigger vector
11381     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11382   }
11383   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11384
11385   if (Subtarget->hasSSE41()) {
11386     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11387       unsigned Opc;
11388       if (VT == MVT::v8i16) {
11389         Opc = X86ISD::PINSRW;
11390       } else {
11391         assert(VT == MVT::v16i8);
11392         Opc = X86ISD::PINSRB;
11393       }
11394
11395       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11396       // argument.
11397       if (N1.getValueType() != MVT::i32)
11398         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11399       if (N2.getValueType() != MVT::i32)
11400         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11401       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11402     }
11403
11404     if (EltVT == MVT::f32) {
11405       // Bits [7:6] of the constant are the source select. This will always be
11406       //   zero here. The DAG Combiner may combine an extract_elt index into
11407       //   these bits. For example (insert (extract, 3), 2) could be matched by
11408       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11409       // Bits [5:4] of the constant are the destination select. This is the
11410       //   value of the incoming immediate.
11411       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11412       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11413
11414       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11415       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11416         // If this is an insertion of 32-bits into the low 32-bits of
11417         // a vector, we prefer to generate a blend with immediate rather
11418         // than an insertps. Blends are simpler operations in hardware and so
11419         // will always have equal or better performance than insertps.
11420         // But if optimizing for size and there's a load folding opportunity,
11421         // generate insertps because blendps does not have a 32-bit memory
11422         // operand form.
11423         N2 = DAG.getIntPtrConstant(1, dl);
11424         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11425         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11426       }
11427       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11428       // Create this as a scalar to vector..
11429       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11430       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11431     }
11432
11433     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11434       // PINSR* works with constant index.
11435       return Op;
11436     }
11437   }
11438
11439   if (EltVT == MVT::i8)
11440     return SDValue();
11441
11442   if (EltVT.getSizeInBits() == 16) {
11443     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11444     // as its second argument.
11445     if (N1.getValueType() != MVT::i32)
11446       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11447     if (N2.getValueType() != MVT::i32)
11448       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11449     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11450   }
11451   return SDValue();
11452 }
11453
11454 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11455   SDLoc dl(Op);
11456   MVT OpVT = Op.getSimpleValueType();
11457
11458   // If this is a 256-bit vector result, first insert into a 128-bit
11459   // vector and then insert into the 256-bit vector.
11460   if (!OpVT.is128BitVector()) {
11461     // Insert into a 128-bit vector.
11462     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11463     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11464                                  OpVT.getVectorNumElements() / SizeFactor);
11465
11466     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11467
11468     // Insert the 128-bit vector.
11469     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11470   }
11471
11472   if (OpVT == MVT::v1i64 &&
11473       Op.getOperand(0).getValueType() == MVT::i64)
11474     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11475
11476   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11477   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11478   return DAG.getBitcast(
11479       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11480 }
11481
11482 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11483 // a simple subregister reference or explicit instructions to grab
11484 // upper bits of a vector.
11485 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11486                                       SelectionDAG &DAG) {
11487   SDLoc dl(Op);
11488   SDValue In =  Op.getOperand(0);
11489   SDValue Idx = Op.getOperand(1);
11490   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11491   MVT ResVT   = Op.getSimpleValueType();
11492   MVT InVT    = In.getSimpleValueType();
11493
11494   if (Subtarget->hasFp256()) {
11495     if (ResVT.is128BitVector() &&
11496         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11497         isa<ConstantSDNode>(Idx)) {
11498       return Extract128BitVector(In, IdxVal, DAG, dl);
11499     }
11500     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11501         isa<ConstantSDNode>(Idx)) {
11502       return Extract256BitVector(In, IdxVal, DAG, dl);
11503     }
11504   }
11505   return SDValue();
11506 }
11507
11508 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11509 // simple superregister reference or explicit instructions to insert
11510 // the upper bits of a vector.
11511 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11512                                      SelectionDAG &DAG) {
11513   if (!Subtarget->hasAVX())
11514     return SDValue();
11515
11516   SDLoc dl(Op);
11517   SDValue Vec = Op.getOperand(0);
11518   SDValue SubVec = Op.getOperand(1);
11519   SDValue Idx = Op.getOperand(2);
11520
11521   if (!isa<ConstantSDNode>(Idx))
11522     return SDValue();
11523
11524   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11525   MVT OpVT = Op.getSimpleValueType();
11526   MVT SubVecVT = SubVec.getSimpleValueType();
11527
11528   // Fold two 16-byte subvector loads into one 32-byte load:
11529   // (insert_subvector (insert_subvector undef, (load addr), 0),
11530   //                   (load addr + 16), Elts/2)
11531   // --> load32 addr
11532   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11533       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11534       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11535     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11536     if (Idx2 && Idx2->getZExtValue() == 0) {
11537       SDValue SubVec2 = Vec.getOperand(1);
11538       // If needed, look through a bitcast to get to the load.
11539       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11540         SubVec2 = SubVec2.getOperand(0);
11541
11542       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11543         bool Fast;
11544         unsigned Alignment = FirstLd->getAlignment();
11545         unsigned AS = FirstLd->getAddressSpace();
11546         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11547         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11548                                     OpVT, AS, Alignment, &Fast) && Fast) {
11549           SDValue Ops[] = { SubVec2, SubVec };
11550           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11551             return Ld;
11552         }
11553       }
11554     }
11555   }
11556
11557   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11558       SubVecVT.is128BitVector())
11559     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11560
11561   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11562     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11563
11564   if (OpVT.getVectorElementType() == MVT::i1) {
11565     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11566       return Op;
11567     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11568     SDValue Undef = DAG.getUNDEF(OpVT);
11569     unsigned NumElems = OpVT.getVectorNumElements();
11570     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11571
11572     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11573       // Zero upper bits of the Vec
11574       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11575       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11576
11577       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11578                                  SubVec, ZeroIdx);
11579       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11580       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11581     }
11582     if (IdxVal == 0) {
11583       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11584                                  SubVec, ZeroIdx);
11585       // Zero upper bits of the Vec2
11586       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11587       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11588       // Zero lower bits of the Vec
11589       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11590       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11591       // Merge them together
11592       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11593     }
11594   }
11595   return SDValue();
11596 }
11597
11598 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11599 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11600 // one of the above mentioned nodes. It has to be wrapped because otherwise
11601 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11602 // be used to form addressing mode. These wrapped nodes will be selected
11603 // into MOV32ri.
11604 SDValue
11605 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11606   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11607
11608   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11609   // global base reg.
11610   unsigned char OpFlag = 0;
11611   unsigned WrapperKind = X86ISD::Wrapper;
11612   CodeModel::Model M = DAG.getTarget().getCodeModel();
11613
11614   if (Subtarget->isPICStyleRIPRel() &&
11615       (M == CodeModel::Small || M == CodeModel::Kernel))
11616     WrapperKind = X86ISD::WrapperRIP;
11617   else if (Subtarget->isPICStyleGOT())
11618     OpFlag = X86II::MO_GOTOFF;
11619   else if (Subtarget->isPICStyleStubPIC())
11620     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11621
11622   auto PtrVT = getPointerTy(DAG.getDataLayout());
11623   SDValue Result = DAG.getTargetConstantPool(
11624       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11625   SDLoc DL(CP);
11626   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11627   // With PIC, the address is actually $g + Offset.
11628   if (OpFlag) {
11629     Result =
11630         DAG.getNode(ISD::ADD, DL, PtrVT,
11631                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11632   }
11633
11634   return Result;
11635 }
11636
11637 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11638   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11639
11640   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11641   // global base reg.
11642   unsigned char OpFlag = 0;
11643   unsigned WrapperKind = X86ISD::Wrapper;
11644   CodeModel::Model M = DAG.getTarget().getCodeModel();
11645
11646   if (Subtarget->isPICStyleRIPRel() &&
11647       (M == CodeModel::Small || M == CodeModel::Kernel))
11648     WrapperKind = X86ISD::WrapperRIP;
11649   else if (Subtarget->isPICStyleGOT())
11650     OpFlag = X86II::MO_GOTOFF;
11651   else if (Subtarget->isPICStyleStubPIC())
11652     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11653
11654   auto PtrVT = getPointerTy(DAG.getDataLayout());
11655   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11656   SDLoc DL(JT);
11657   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11658
11659   // With PIC, the address is actually $g + Offset.
11660   if (OpFlag)
11661     Result =
11662         DAG.getNode(ISD::ADD, DL, PtrVT,
11663                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11664
11665   return Result;
11666 }
11667
11668 SDValue
11669 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11670   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11671
11672   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11673   // global base reg.
11674   unsigned char OpFlag = 0;
11675   unsigned WrapperKind = X86ISD::Wrapper;
11676   CodeModel::Model M = DAG.getTarget().getCodeModel();
11677
11678   if (Subtarget->isPICStyleRIPRel() &&
11679       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11680     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11681       OpFlag = X86II::MO_GOTPCREL;
11682     WrapperKind = X86ISD::WrapperRIP;
11683   } else if (Subtarget->isPICStyleGOT()) {
11684     OpFlag = X86II::MO_GOT;
11685   } else if (Subtarget->isPICStyleStubPIC()) {
11686     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11687   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11688     OpFlag = X86II::MO_DARWIN_NONLAZY;
11689   }
11690
11691   auto PtrVT = getPointerTy(DAG.getDataLayout());
11692   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11693
11694   SDLoc DL(Op);
11695   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11696
11697   // With PIC, the address is actually $g + Offset.
11698   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11699       !Subtarget->is64Bit()) {
11700     Result =
11701         DAG.getNode(ISD::ADD, DL, PtrVT,
11702                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11703   }
11704
11705   // For symbols that require a load from a stub to get the address, emit the
11706   // load.
11707   if (isGlobalStubReference(OpFlag))
11708     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11709                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11710                          false, false, false, 0);
11711
11712   return Result;
11713 }
11714
11715 SDValue
11716 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11717   // Create the TargetBlockAddressAddress node.
11718   unsigned char OpFlags =
11719     Subtarget->ClassifyBlockAddressReference();
11720   CodeModel::Model M = DAG.getTarget().getCodeModel();
11721   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11722   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11723   SDLoc dl(Op);
11724   auto PtrVT = getPointerTy(DAG.getDataLayout());
11725   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11726
11727   if (Subtarget->isPICStyleRIPRel() &&
11728       (M == CodeModel::Small || M == CodeModel::Kernel))
11729     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11730   else
11731     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11732
11733   // With PIC, the address is actually $g + Offset.
11734   if (isGlobalRelativeToPICBase(OpFlags)) {
11735     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11736                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11737   }
11738
11739   return Result;
11740 }
11741
11742 SDValue
11743 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11744                                       int64_t Offset, SelectionDAG &DAG) const {
11745   // Create the TargetGlobalAddress node, folding in the constant
11746   // offset if it is legal.
11747   unsigned char OpFlags =
11748       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11749   CodeModel::Model M = DAG.getTarget().getCodeModel();
11750   auto PtrVT = getPointerTy(DAG.getDataLayout());
11751   SDValue Result;
11752   if (OpFlags == X86II::MO_NO_FLAG &&
11753       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11754     // A direct static reference to a global.
11755     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11756     Offset = 0;
11757   } else {
11758     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11759   }
11760
11761   if (Subtarget->isPICStyleRIPRel() &&
11762       (M == CodeModel::Small || M == CodeModel::Kernel))
11763     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11764   else
11765     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11766
11767   // With PIC, the address is actually $g + Offset.
11768   if (isGlobalRelativeToPICBase(OpFlags)) {
11769     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11770                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11771   }
11772
11773   // For globals that require a load from a stub to get the address, emit the
11774   // load.
11775   if (isGlobalStubReference(OpFlags))
11776     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11777                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11778                          false, false, false, 0);
11779
11780   // If there was a non-zero offset that we didn't fold, create an explicit
11781   // addition for it.
11782   if (Offset != 0)
11783     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11784                          DAG.getConstant(Offset, dl, PtrVT));
11785
11786   return Result;
11787 }
11788
11789 SDValue
11790 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11791   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11792   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11793   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11794 }
11795
11796 static SDValue
11797 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11798            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11799            unsigned char OperandFlags, bool LocalDynamic = false) {
11800   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11801   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11802   SDLoc dl(GA);
11803   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11804                                            GA->getValueType(0),
11805                                            GA->getOffset(),
11806                                            OperandFlags);
11807
11808   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11809                                            : X86ISD::TLSADDR;
11810
11811   if (InFlag) {
11812     SDValue Ops[] = { Chain,  TGA, *InFlag };
11813     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11814   } else {
11815     SDValue Ops[]  = { Chain, TGA };
11816     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11817   }
11818
11819   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11820   MFI->setAdjustsStack(true);
11821   MFI->setHasCalls(true);
11822
11823   SDValue Flag = Chain.getValue(1);
11824   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11825 }
11826
11827 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11828 static SDValue
11829 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11830                                 const EVT PtrVT) {
11831   SDValue InFlag;
11832   SDLoc dl(GA);  // ? function entry point might be better
11833   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11834                                    DAG.getNode(X86ISD::GlobalBaseReg,
11835                                                SDLoc(), PtrVT), InFlag);
11836   InFlag = Chain.getValue(1);
11837
11838   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11839 }
11840
11841 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11842 static SDValue
11843 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11844                                 const EVT PtrVT) {
11845   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11846                     X86::RAX, X86II::MO_TLSGD);
11847 }
11848
11849 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11850                                            SelectionDAG &DAG,
11851                                            const EVT PtrVT,
11852                                            bool is64Bit) {
11853   SDLoc dl(GA);
11854
11855   // Get the start address of the TLS block for this module.
11856   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11857       .getInfo<X86MachineFunctionInfo>();
11858   MFI->incNumLocalDynamicTLSAccesses();
11859
11860   SDValue Base;
11861   if (is64Bit) {
11862     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11863                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11864   } else {
11865     SDValue InFlag;
11866     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11867         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11868     InFlag = Chain.getValue(1);
11869     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11870                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11871   }
11872
11873   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11874   // of Base.
11875
11876   // Build x@dtpoff.
11877   unsigned char OperandFlags = X86II::MO_DTPOFF;
11878   unsigned WrapperKind = X86ISD::Wrapper;
11879   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11880                                            GA->getValueType(0),
11881                                            GA->getOffset(), OperandFlags);
11882   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11883
11884   // Add x@dtpoff with the base.
11885   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11886 }
11887
11888 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11889 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11890                                    const EVT PtrVT, TLSModel::Model model,
11891                                    bool is64Bit, bool isPIC) {
11892   SDLoc dl(GA);
11893
11894   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11895   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11896                                                          is64Bit ? 257 : 256));
11897
11898   SDValue ThreadPointer =
11899       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11900                   MachinePointerInfo(Ptr), false, false, false, 0);
11901
11902   unsigned char OperandFlags = 0;
11903   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11904   // initialexec.
11905   unsigned WrapperKind = X86ISD::Wrapper;
11906   if (model == TLSModel::LocalExec) {
11907     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11908   } else if (model == TLSModel::InitialExec) {
11909     if (is64Bit) {
11910       OperandFlags = X86II::MO_GOTTPOFF;
11911       WrapperKind = X86ISD::WrapperRIP;
11912     } else {
11913       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11914     }
11915   } else {
11916     llvm_unreachable("Unexpected model");
11917   }
11918
11919   // emit "addl x@ntpoff,%eax" (local exec)
11920   // or "addl x@indntpoff,%eax" (initial exec)
11921   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11922   SDValue TGA =
11923       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11924                                  GA->getOffset(), OperandFlags);
11925   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11926
11927   if (model == TLSModel::InitialExec) {
11928     if (isPIC && !is64Bit) {
11929       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11930                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11931                            Offset);
11932     }
11933
11934     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11935                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11936                          false, false, false, 0);
11937   }
11938
11939   // The address of the thread local variable is the add of the thread
11940   // pointer with the offset of the variable.
11941   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11942 }
11943
11944 SDValue
11945 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11946
11947   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11948   const GlobalValue *GV = GA->getGlobal();
11949   auto PtrVT = getPointerTy(DAG.getDataLayout());
11950
11951   if (Subtarget->isTargetELF()) {
11952     if (DAG.getTarget().Options.EmulatedTLS)
11953       return LowerToTLSEmulatedModel(GA, DAG);
11954     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11955     switch (model) {
11956       case TLSModel::GeneralDynamic:
11957         if (Subtarget->is64Bit())
11958           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11959         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11960       case TLSModel::LocalDynamic:
11961         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11962                                            Subtarget->is64Bit());
11963       case TLSModel::InitialExec:
11964       case TLSModel::LocalExec:
11965         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11966                                    DAG.getTarget().getRelocationModel() ==
11967                                        Reloc::PIC_);
11968     }
11969     llvm_unreachable("Unknown TLS model.");
11970   }
11971
11972   if (Subtarget->isTargetDarwin()) {
11973     // Darwin only has one model of TLS.  Lower to that.
11974     unsigned char OpFlag = 0;
11975     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11976                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11977
11978     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11979     // global base reg.
11980     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11981                  !Subtarget->is64Bit();
11982     if (PIC32)
11983       OpFlag = X86II::MO_TLVP_PIC_BASE;
11984     else
11985       OpFlag = X86II::MO_TLVP;
11986     SDLoc DL(Op);
11987     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11988                                                 GA->getValueType(0),
11989                                                 GA->getOffset(), OpFlag);
11990     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11991
11992     // With PIC32, the address is actually $g + Offset.
11993     if (PIC32)
11994       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11995                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11996                            Offset);
11997
11998     // Lowering the machine isd will make sure everything is in the right
11999     // location.
12000     SDValue Chain = DAG.getEntryNode();
12001     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12002     SDValue Args[] = { Chain, Offset };
12003     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12004
12005     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12006     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12007     MFI->setAdjustsStack(true);
12008
12009     // And our return value (tls address) is in the standard call return value
12010     // location.
12011     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12012     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12013   }
12014
12015   if (Subtarget->isTargetKnownWindowsMSVC() ||
12016       Subtarget->isTargetWindowsGNU()) {
12017     // Just use the implicit TLS architecture
12018     // Need to generate someting similar to:
12019     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12020     //                                  ; from TEB
12021     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12022     //   mov     rcx, qword [rdx+rcx*8]
12023     //   mov     eax, .tls$:tlsvar
12024     //   [rax+rcx] contains the address
12025     // Windows 64bit: gs:0x58
12026     // Windows 32bit: fs:__tls_array
12027
12028     SDLoc dl(GA);
12029     SDValue Chain = DAG.getEntryNode();
12030
12031     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12032     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12033     // use its literal value of 0x2C.
12034     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12035                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12036                                                              256)
12037                                         : Type::getInt32PtrTy(*DAG.getContext(),
12038                                                               257));
12039
12040     SDValue TlsArray = Subtarget->is64Bit()
12041                            ? DAG.getIntPtrConstant(0x58, dl)
12042                            : (Subtarget->isTargetWindowsGNU()
12043                                   ? DAG.getIntPtrConstant(0x2C, dl)
12044                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12045
12046     SDValue ThreadPointer =
12047         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12048                     false, false, 0);
12049
12050     SDValue res;
12051     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12052       res = ThreadPointer;
12053     } else {
12054       // Load the _tls_index variable
12055       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12056       if (Subtarget->is64Bit())
12057         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12058                              MachinePointerInfo(), MVT::i32, false, false,
12059                              false, 0);
12060       else
12061         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12062                           false, false, 0);
12063
12064       auto &DL = DAG.getDataLayout();
12065       SDValue Scale =
12066           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12067       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12068
12069       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12070     }
12071
12072     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12073                       false, 0);
12074
12075     // Get the offset of start of .tls section
12076     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12077                                              GA->getValueType(0),
12078                                              GA->getOffset(), X86II::MO_SECREL);
12079     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12080
12081     // The address of the thread local variable is the add of the thread
12082     // pointer with the offset of the variable.
12083     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12084   }
12085
12086   llvm_unreachable("TLS not implemented for this target.");
12087 }
12088
12089 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12090 /// and take a 2 x i32 value to shift plus a shift amount.
12091 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12092   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12093   MVT VT = Op.getSimpleValueType();
12094   unsigned VTBits = VT.getSizeInBits();
12095   SDLoc dl(Op);
12096   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12097   SDValue ShOpLo = Op.getOperand(0);
12098   SDValue ShOpHi = Op.getOperand(1);
12099   SDValue ShAmt  = Op.getOperand(2);
12100   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12101   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12102   // during isel.
12103   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12104                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12105   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12106                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12107                        : DAG.getConstant(0, dl, VT);
12108
12109   SDValue Tmp2, Tmp3;
12110   if (Op.getOpcode() == ISD::SHL_PARTS) {
12111     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12112     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12113   } else {
12114     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12115     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12116   }
12117
12118   // If the shift amount is larger or equal than the width of a part we can't
12119   // rely on the results of shld/shrd. Insert a test and select the appropriate
12120   // values for large shift amounts.
12121   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12122                                 DAG.getConstant(VTBits, dl, MVT::i8));
12123   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12124                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12125
12126   SDValue Hi, Lo;
12127   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12128   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12129   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12130
12131   if (Op.getOpcode() == ISD::SHL_PARTS) {
12132     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12133     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12134   } else {
12135     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12136     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12137   }
12138
12139   SDValue Ops[2] = { Lo, Hi };
12140   return DAG.getMergeValues(Ops, dl);
12141 }
12142
12143 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12144                                            SelectionDAG &DAG) const {
12145   SDValue Src = Op.getOperand(0);
12146   MVT SrcVT = Src.getSimpleValueType();
12147   MVT VT = Op.getSimpleValueType();
12148   SDLoc dl(Op);
12149
12150   if (SrcVT.isVector()) {
12151     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12152       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12153                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12154                          DAG.getUNDEF(SrcVT)));
12155     }
12156     if (SrcVT.getVectorElementType() == MVT::i1) {
12157       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12158       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12159                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12160     }
12161     return SDValue();
12162   }
12163
12164   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12165          "Unknown SINT_TO_FP to lower!");
12166
12167   // These are really Legal; return the operand so the caller accepts it as
12168   // Legal.
12169   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12170     return Op;
12171   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12172       Subtarget->is64Bit()) {
12173     return Op;
12174   }
12175
12176   unsigned Size = SrcVT.getSizeInBits()/8;
12177   MachineFunction &MF = DAG.getMachineFunction();
12178   auto PtrVT = getPointerTy(MF.getDataLayout());
12179   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12180   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12181   SDValue Chain = DAG.getStore(
12182       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12183       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12184       false, 0);
12185   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12186 }
12187
12188 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12189                                      SDValue StackSlot,
12190                                      SelectionDAG &DAG) const {
12191   // Build the FILD
12192   SDLoc DL(Op);
12193   SDVTList Tys;
12194   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12195   if (useSSE)
12196     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12197   else
12198     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12199
12200   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12201
12202   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12203   MachineMemOperand *MMO;
12204   if (FI) {
12205     int SSFI = FI->getIndex();
12206     MMO = DAG.getMachineFunction().getMachineMemOperand(
12207         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12208         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12209   } else {
12210     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12211     StackSlot = StackSlot.getOperand(1);
12212   }
12213   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12214   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12215                                            X86ISD::FILD, DL,
12216                                            Tys, Ops, SrcVT, MMO);
12217
12218   if (useSSE) {
12219     Chain = Result.getValue(1);
12220     SDValue InFlag = Result.getValue(2);
12221
12222     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12223     // shouldn't be necessary except that RFP cannot be live across
12224     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12225     MachineFunction &MF = DAG.getMachineFunction();
12226     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12227     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12228     auto PtrVT = getPointerTy(MF.getDataLayout());
12229     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12230     Tys = DAG.getVTList(MVT::Other);
12231     SDValue Ops[] = {
12232       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12233     };
12234     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12235         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12236         MachineMemOperand::MOStore, SSFISize, SSFISize);
12237
12238     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12239                                     Ops, Op.getValueType(), MMO);
12240     Result = DAG.getLoad(
12241         Op.getValueType(), DL, Chain, StackSlot,
12242         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12243         false, false, false, 0);
12244   }
12245
12246   return Result;
12247 }
12248
12249 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12250 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12251                                                SelectionDAG &DAG) const {
12252   // This algorithm is not obvious. Here it is what we're trying to output:
12253   /*
12254      movq       %rax,  %xmm0
12255      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12256      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12257      #ifdef __SSE3__
12258        haddpd   %xmm0, %xmm0
12259      #else
12260        pshufd   $0x4e, %xmm0, %xmm1
12261        addpd    %xmm1, %xmm0
12262      #endif
12263   */
12264
12265   SDLoc dl(Op);
12266   LLVMContext *Context = DAG.getContext();
12267
12268   // Build some magic constants.
12269   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12270   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12271   auto PtrVT = getPointerTy(DAG.getDataLayout());
12272   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12273
12274   SmallVector<Constant*,2> CV1;
12275   CV1.push_back(
12276     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12277                                       APInt(64, 0x4330000000000000ULL))));
12278   CV1.push_back(
12279     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12280                                       APInt(64, 0x4530000000000000ULL))));
12281   Constant *C1 = ConstantVector::get(CV1);
12282   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12283
12284   // Load the 64-bit value into an XMM register.
12285   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12286                             Op.getOperand(0));
12287   SDValue CLod0 =
12288       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12289                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12290                   false, false, false, 16);
12291   SDValue Unpck1 =
12292       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12293
12294   SDValue CLod1 =
12295       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12296                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12297                   false, false, false, 16);
12298   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12299   // TODO: Are there any fast-math-flags to propagate here?
12300   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12301   SDValue Result;
12302
12303   if (Subtarget->hasSSE3()) {
12304     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12305     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12306   } else {
12307     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12308     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12309                                            S2F, 0x4E, DAG);
12310     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12311                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12312   }
12313
12314   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12315                      DAG.getIntPtrConstant(0, dl));
12316 }
12317
12318 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12319 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12320                                                SelectionDAG &DAG) const {
12321   SDLoc dl(Op);
12322   // FP constant to bias correct the final result.
12323   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12324                                    MVT::f64);
12325
12326   // Load the 32-bit value into an XMM register.
12327   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12328                              Op.getOperand(0));
12329
12330   // Zero out the upper parts of the register.
12331   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12332
12333   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12334                      DAG.getBitcast(MVT::v2f64, Load),
12335                      DAG.getIntPtrConstant(0, dl));
12336
12337   // Or the load with the bias.
12338   SDValue Or = DAG.getNode(
12339       ISD::OR, dl, MVT::v2i64,
12340       DAG.getBitcast(MVT::v2i64,
12341                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12342       DAG.getBitcast(MVT::v2i64,
12343                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12344   Or =
12345       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12346                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12347
12348   // Subtract the bias.
12349   // TODO: Are there any fast-math-flags to propagate here?
12350   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12351
12352   // Handle final rounding.
12353   EVT DestVT = Op.getValueType();
12354
12355   if (DestVT.bitsLT(MVT::f64))
12356     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12357                        DAG.getIntPtrConstant(0, dl));
12358   if (DestVT.bitsGT(MVT::f64))
12359     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12360
12361   // Handle final rounding.
12362   return Sub;
12363 }
12364
12365 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12366                                      const X86Subtarget &Subtarget) {
12367   // The algorithm is the following:
12368   // #ifdef __SSE4_1__
12369   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12370   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12371   //                                 (uint4) 0x53000000, 0xaa);
12372   // #else
12373   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12374   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12375   // #endif
12376   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12377   //     return (float4) lo + fhi;
12378
12379   SDLoc DL(Op);
12380   SDValue V = Op->getOperand(0);
12381   EVT VecIntVT = V.getValueType();
12382   bool Is128 = VecIntVT == MVT::v4i32;
12383   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12384   // If we convert to something else than the supported type, e.g., to v4f64,
12385   // abort early.
12386   if (VecFloatVT != Op->getValueType(0))
12387     return SDValue();
12388
12389   unsigned NumElts = VecIntVT.getVectorNumElements();
12390   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12391          "Unsupported custom type");
12392   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12393
12394   // In the #idef/#else code, we have in common:
12395   // - The vector of constants:
12396   // -- 0x4b000000
12397   // -- 0x53000000
12398   // - A shift:
12399   // -- v >> 16
12400
12401   // Create the splat vector for 0x4b000000.
12402   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12403   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12404                            CstLow, CstLow, CstLow, CstLow};
12405   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12406                                   makeArrayRef(&CstLowArray[0], NumElts));
12407   // Create the splat vector for 0x53000000.
12408   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12409   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12410                             CstHigh, CstHigh, CstHigh, CstHigh};
12411   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12412                                    makeArrayRef(&CstHighArray[0], NumElts));
12413
12414   // Create the right shift.
12415   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12416   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12417                              CstShift, CstShift, CstShift, CstShift};
12418   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12419                                     makeArrayRef(&CstShiftArray[0], NumElts));
12420   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12421
12422   SDValue Low, High;
12423   if (Subtarget.hasSSE41()) {
12424     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12425     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12426     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12427     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12428     // Low will be bitcasted right away, so do not bother bitcasting back to its
12429     // original type.
12430     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12431                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12432     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12433     //                                 (uint4) 0x53000000, 0xaa);
12434     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12435     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12436     // High will be bitcasted right away, so do not bother bitcasting back to
12437     // its original type.
12438     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12439                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12440   } else {
12441     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12442     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12443                                      CstMask, CstMask, CstMask);
12444     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12445     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12446     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12447
12448     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12449     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12450   }
12451
12452   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12453   SDValue CstFAdd = DAG.getConstantFP(
12454       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12455   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12456                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12457   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12458                                    makeArrayRef(&CstFAddArray[0], NumElts));
12459
12460   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12461   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12462   // TODO: Are there any fast-math-flags to propagate here?
12463   SDValue FHigh =
12464       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12465   //     return (float4) lo + fhi;
12466   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12467   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12468 }
12469
12470 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12471                                                SelectionDAG &DAG) const {
12472   SDValue N0 = Op.getOperand(0);
12473   MVT SVT = N0.getSimpleValueType();
12474   SDLoc dl(Op);
12475
12476   switch (SVT.SimpleTy) {
12477   default:
12478     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12479   case MVT::v4i8:
12480   case MVT::v4i16:
12481   case MVT::v8i8:
12482   case MVT::v8i16: {
12483     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12484     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12485                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12486   }
12487   case MVT::v4i32:
12488   case MVT::v8i32:
12489     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12490   case MVT::v16i8:
12491   case MVT::v16i16:
12492     if (Subtarget->hasAVX512())
12493       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12494                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12495   }
12496   llvm_unreachable(nullptr);
12497 }
12498
12499 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12500                                            SelectionDAG &DAG) const {
12501   SDValue N0 = Op.getOperand(0);
12502   SDLoc dl(Op);
12503   auto PtrVT = getPointerTy(DAG.getDataLayout());
12504
12505   if (Op.getValueType().isVector())
12506     return lowerUINT_TO_FP_vec(Op, DAG);
12507
12508   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12509   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12510   // the optimization here.
12511   if (DAG.SignBitIsZero(N0))
12512     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12513
12514   MVT SrcVT = N0.getSimpleValueType();
12515   MVT DstVT = Op.getSimpleValueType();
12516
12517   if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
12518       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
12519     // Conversions from unsigned i32 to f32/f64 are legal,
12520     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
12521     return Op;
12522   }
12523
12524   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12525     return LowerUINT_TO_FP_i64(Op, DAG);
12526   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12527     return LowerUINT_TO_FP_i32(Op, DAG);
12528   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12529     return SDValue();
12530
12531   // Make a 64-bit buffer, and use it to build an FILD.
12532   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12533   if (SrcVT == MVT::i32) {
12534     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12535     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12536     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12537                                   StackSlot, MachinePointerInfo(),
12538                                   false, false, 0);
12539     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12540                                   OffsetSlot, MachinePointerInfo(),
12541                                   false, false, 0);
12542     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12543     return Fild;
12544   }
12545
12546   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12547   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12548                                StackSlot, MachinePointerInfo(),
12549                                false, false, 0);
12550   // For i64 source, we need to add the appropriate power of 2 if the input
12551   // was negative.  This is the same as the optimization in
12552   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12553   // we must be careful to do the computation in x87 extended precision, not
12554   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12555   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12556   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12557       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12558       MachineMemOperand::MOLoad, 8, 8);
12559
12560   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12561   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12562   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12563                                          MVT::i64, MMO);
12564
12565   APInt FF(32, 0x5F800000ULL);
12566
12567   // Check whether the sign bit is set.
12568   SDValue SignSet = DAG.getSetCC(
12569       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12570       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12571
12572   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12573   SDValue FudgePtr = DAG.getConstantPool(
12574       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12575
12576   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12577   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12578   SDValue Four = DAG.getIntPtrConstant(4, dl);
12579   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12580                                Zero, Four);
12581   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12582
12583   // Load the value out, extending it from f32 to f80.
12584   // FIXME: Avoid the extend by constructing the right constant pool?
12585   SDValue Fudge = DAG.getExtLoad(
12586       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12587       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12588       false, false, false, 4);
12589   // Extend everything to 80 bits to force it to be done on x87.
12590   // TODO: Are there any fast-math-flags to propagate here?
12591   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12592   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12593                      DAG.getIntPtrConstant(0, dl));
12594 }
12595
12596 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12597 // is legal, or has an f16 source (which needs to be promoted to f32),
12598 // just return an <SDValue(), SDValue()> pair.
12599 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12600 // to i16, i32 or i64, and we lower it to a legal sequence.
12601 // If lowered to the final integer result we return a <result, SDValue()> pair.
12602 // Otherwise we lower it to a sequence ending with a FIST, return a
12603 // <FIST, StackSlot> pair, and the caller is responsible for loading
12604 // the final integer result from StackSlot.
12605 std::pair<SDValue,SDValue>
12606 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12607                                    bool IsSigned, bool IsReplace) const {
12608   SDLoc DL(Op);
12609
12610   EVT DstTy = Op.getValueType();
12611   EVT TheVT = Op.getOperand(0).getValueType();
12612   auto PtrVT = getPointerTy(DAG.getDataLayout());
12613
12614   if (TheVT == MVT::f16)
12615     // We need to promote the f16 to f32 before using the lowering
12616     // in this routine.
12617     return std::make_pair(SDValue(), SDValue());
12618
12619   assert((TheVT == MVT::f32 ||
12620           TheVT == MVT::f64 ||
12621           TheVT == MVT::f80) &&
12622          "Unexpected FP operand type in FP_TO_INTHelper");
12623
12624   // If using FIST to compute an unsigned i64, we'll need some fixup
12625   // to handle values above the maximum signed i64.  A FIST is always
12626   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12627   bool UnsignedFixup = !IsSigned &&
12628                        DstTy == MVT::i64 &&
12629                        (!Subtarget->is64Bit() ||
12630                         !isScalarFPTypeInSSEReg(TheVT));
12631
12632   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12633     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12634     // The low 32 bits of the fist result will have the correct uint32 result.
12635     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12636     DstTy = MVT::i64;
12637   }
12638
12639   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12640          DstTy.getSimpleVT() >= MVT::i16 &&
12641          "Unknown FP_TO_INT to lower!");
12642
12643   // These are really Legal.
12644   if (DstTy == MVT::i32 &&
12645       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12646     return std::make_pair(SDValue(), SDValue());
12647   if (Subtarget->is64Bit() &&
12648       DstTy == MVT::i64 &&
12649       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12650     return std::make_pair(SDValue(), SDValue());
12651
12652   // We lower FP->int64 into FISTP64 followed by a load from a temporary
12653   // stack slot.
12654   MachineFunction &MF = DAG.getMachineFunction();
12655   unsigned MemSize = DstTy.getSizeInBits()/8;
12656   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12657   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12658
12659   unsigned Opc;
12660   switch (DstTy.getSimpleVT().SimpleTy) {
12661   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12662   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12663   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12664   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12665   }
12666
12667   SDValue Chain = DAG.getEntryNode();
12668   SDValue Value = Op.getOperand(0);
12669   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12670
12671   if (UnsignedFixup) {
12672     //
12673     // Conversion to unsigned i64 is implemented with a select,
12674     // depending on whether the source value fits in the range
12675     // of a signed i64.  Let Thresh be the FP equivalent of
12676     // 0x8000000000000000ULL.
12677     //
12678     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12679     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
12680     //  Fist-to-mem64 FistSrc
12681     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12682     //  to XOR'ing the high 32 bits with Adjust.
12683     //
12684     // Being a power of 2, Thresh is exactly representable in all FP formats.
12685     // For X87 we'd like to use the smallest FP type for this constant, but
12686     // for DAG type consistency we have to match the FP operand type.
12687
12688     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12689     APFloat::opStatus Status = APFloat::opOK;
12690     bool LosesInfo = false;
12691     if (TheVT == MVT::f64)
12692       // The rounding mode is irrelevant as the conversion should be exact.
12693       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12694                               &LosesInfo);
12695     else if (TheVT == MVT::f80)
12696       Status = Thresh.convert(APFloat::x87DoubleExtended,
12697                               APFloat::rmNearestTiesToEven, &LosesInfo);
12698
12699     assert(Status == APFloat::opOK && !LosesInfo &&
12700            "FP conversion should have been exact");
12701
12702     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12703
12704     SDValue Cmp = DAG.getSetCC(DL,
12705                                getSetCCResultType(DAG.getDataLayout(),
12706                                                   *DAG.getContext(), TheVT),
12707                                Value, ThreshVal, ISD::SETLT);
12708     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12709                            DAG.getConstant(0, DL, MVT::i32),
12710                            DAG.getConstant(0x80000000, DL, MVT::i32));
12711     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12712     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12713                                               *DAG.getContext(), TheVT),
12714                        Value, ThreshVal, ISD::SETLT);
12715     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12716   }
12717
12718   // FIXME This causes a redundant load/store if the SSE-class value is already
12719   // in memory, such as if it is on the callstack.
12720   if (isScalarFPTypeInSSEReg(TheVT)) {
12721     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12722     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12723                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12724                          false, 0);
12725     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12726     SDValue Ops[] = {
12727       Chain, StackSlot, DAG.getValueType(TheVT)
12728     };
12729
12730     MachineMemOperand *MMO =
12731         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12732                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12733     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12734     Chain = Value.getValue(1);
12735     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12736     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12737   }
12738
12739   MachineMemOperand *MMO =
12740       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12741                               MachineMemOperand::MOStore, MemSize, MemSize);
12742
12743   if (UnsignedFixup) {
12744
12745     // Insert the FIST, load its result as two i32's,
12746     // and XOR the high i32 with Adjust.
12747
12748     SDValue FistOps[] = { Chain, Value, StackSlot };
12749     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12750                                            FistOps, DstTy, MMO);
12751
12752     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12753                                 MachinePointerInfo(),
12754                                 false, false, false, 0);
12755     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12756                                    DAG.getConstant(4, DL, PtrVT));
12757
12758     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12759                                  MachinePointerInfo(),
12760                                  false, false, false, 0);
12761     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12762
12763     if (Subtarget->is64Bit()) {
12764       // Join High32 and Low32 into a 64-bit result.
12765       // (High32 << 32) | Low32
12766       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12767       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12768       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12769                            DAG.getConstant(32, DL, MVT::i8));
12770       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12771       return std::make_pair(Result, SDValue());
12772     }
12773
12774     SDValue ResultOps[] = { Low32, High32 };
12775
12776     SDValue pair = IsReplace
12777       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12778       : DAG.getMergeValues(ResultOps, DL);
12779     return std::make_pair(pair, SDValue());
12780   } else {
12781     // Build the FP_TO_INT*_IN_MEM
12782     SDValue Ops[] = { Chain, Value, StackSlot };
12783     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12784                                            Ops, DstTy, MMO);
12785     return std::make_pair(FIST, StackSlot);
12786   }
12787 }
12788
12789 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12790                               const X86Subtarget *Subtarget) {
12791   MVT VT = Op->getSimpleValueType(0);
12792   SDValue In = Op->getOperand(0);
12793   MVT InVT = In.getSimpleValueType();
12794   SDLoc dl(Op);
12795
12796   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12797     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12798
12799   // Optimize vectors in AVX mode:
12800   //
12801   //   v8i16 -> v8i32
12802   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12803   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12804   //   Concat upper and lower parts.
12805   //
12806   //   v4i32 -> v4i64
12807   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12808   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12809   //   Concat upper and lower parts.
12810   //
12811
12812   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12813       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12814       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12815     return SDValue();
12816
12817   if (Subtarget->hasInt256())
12818     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12819
12820   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12821   SDValue Undef = DAG.getUNDEF(InVT);
12822   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12823   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12824   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12825
12826   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12827                              VT.getVectorNumElements()/2);
12828
12829   OpLo = DAG.getBitcast(HVT, OpLo);
12830   OpHi = DAG.getBitcast(HVT, OpHi);
12831
12832   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12833 }
12834
12835 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12836                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12837   MVT VT = Op->getSimpleValueType(0);
12838   SDValue In = Op->getOperand(0);
12839   MVT InVT = In.getSimpleValueType();
12840   SDLoc DL(Op);
12841   unsigned int NumElts = VT.getVectorNumElements();
12842   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12843     return SDValue();
12844
12845   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12846     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12847
12848   assert(InVT.getVectorElementType() == MVT::i1);
12849   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12850   SDValue One =
12851    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12852   SDValue Zero =
12853    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12854
12855   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12856   if (VT.is512BitVector())
12857     return V;
12858   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12859 }
12860
12861 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12862                                SelectionDAG &DAG) {
12863   if (Subtarget->hasFp256())
12864     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12865       return Res;
12866
12867   return SDValue();
12868 }
12869
12870 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12871                                 SelectionDAG &DAG) {
12872   SDLoc DL(Op);
12873   MVT VT = Op.getSimpleValueType();
12874   SDValue In = Op.getOperand(0);
12875   MVT SVT = In.getSimpleValueType();
12876
12877   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12878     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12879
12880   if (Subtarget->hasFp256())
12881     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12882       return Res;
12883
12884   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12885          VT.getVectorNumElements() != SVT.getVectorNumElements());
12886   return SDValue();
12887 }
12888
12889 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12890   SDLoc DL(Op);
12891   MVT VT = Op.getSimpleValueType();
12892   SDValue In = Op.getOperand(0);
12893   MVT InVT = In.getSimpleValueType();
12894
12895   if (VT == MVT::i1) {
12896     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12897            "Invalid scalar TRUNCATE operation");
12898     if (InVT.getSizeInBits() >= 32)
12899       return SDValue();
12900     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12901     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12902   }
12903   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12904          "Invalid TRUNCATE operation");
12905
12906   // move vector to mask - truncate solution for SKX
12907   if (VT.getVectorElementType() == MVT::i1) {
12908     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12909         Subtarget->hasBWI())
12910       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12911     if ((InVT.is256BitVector() || InVT.is128BitVector())
12912         && InVT.getScalarSizeInBits() <= 16 &&
12913         Subtarget->hasBWI() && Subtarget->hasVLX())
12914       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12915     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12916         Subtarget->hasDQI())
12917       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12918     if ((InVT.is256BitVector() || InVT.is128BitVector())
12919         && InVT.getScalarSizeInBits() >= 32 &&
12920         Subtarget->hasDQI() && Subtarget->hasVLX())
12921       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12922   }
12923
12924   if (VT.getVectorElementType() == MVT::i1) {
12925     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12926     unsigned NumElts = InVT.getVectorNumElements();
12927     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12928     if (InVT.getSizeInBits() < 512) {
12929       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12930       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12931       InVT = ExtVT;
12932     }
12933
12934     SDValue OneV =
12935      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12936     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12937     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12938   }
12939
12940   // vpmovqb/w/d, vpmovdb/w, vpmovwb
12941   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12942       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12943     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12944
12945   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12946     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12947     if (Subtarget->hasInt256()) {
12948       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12949       In = DAG.getBitcast(MVT::v8i32, In);
12950       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12951                                 ShufMask);
12952       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12953                          DAG.getIntPtrConstant(0, DL));
12954     }
12955
12956     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12957                                DAG.getIntPtrConstant(0, DL));
12958     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12959                                DAG.getIntPtrConstant(2, DL));
12960     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12961     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12962     static const int ShufMask[] = {0, 2, 4, 6};
12963     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12964   }
12965
12966   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12967     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12968     if (Subtarget->hasInt256()) {
12969       In = DAG.getBitcast(MVT::v32i8, In);
12970
12971       SmallVector<SDValue,32> pshufbMask;
12972       for (unsigned i = 0; i < 2; ++i) {
12973         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12974         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12975         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12976         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12977         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12978         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12979         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12980         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12981         for (unsigned j = 0; j < 8; ++j)
12982           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12983       }
12984       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12985       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12986       In = DAG.getBitcast(MVT::v4i64, In);
12987
12988       static const int ShufMask[] = {0,  2,  -1,  -1};
12989       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12990                                 &ShufMask[0]);
12991       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12992                        DAG.getIntPtrConstant(0, DL));
12993       return DAG.getBitcast(VT, In);
12994     }
12995
12996     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12997                                DAG.getIntPtrConstant(0, DL));
12998
12999     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13000                                DAG.getIntPtrConstant(4, DL));
13001
13002     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13003     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13004
13005     // The PSHUFB mask:
13006     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13007                                    -1, -1, -1, -1, -1, -1, -1, -1};
13008
13009     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13010     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13011     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13012
13013     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13014     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13015
13016     // The MOVLHPS Mask:
13017     static const int ShufMask2[] = {0, 1, 4, 5};
13018     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13019     return DAG.getBitcast(MVT::v8i16, res);
13020   }
13021
13022   // Handle truncation of V256 to V128 using shuffles.
13023   if (!VT.is128BitVector() || !InVT.is256BitVector())
13024     return SDValue();
13025
13026   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13027
13028   unsigned NumElems = VT.getVectorNumElements();
13029   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13030
13031   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13032   // Prepare truncation shuffle mask
13033   for (unsigned i = 0; i != NumElems; ++i)
13034     MaskVec[i] = i * 2;
13035   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13036                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13037   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13038                      DAG.getIntPtrConstant(0, DL));
13039 }
13040
13041 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13042                                            SelectionDAG &DAG) const {
13043   assert(!Op.getSimpleValueType().isVector());
13044
13045   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13046     /*IsSigned=*/ true, /*IsReplace=*/ false);
13047   SDValue FIST = Vals.first, StackSlot = Vals.second;
13048   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13049   if (!FIST.getNode())
13050     return Op;
13051
13052   if (StackSlot.getNode())
13053     // Load the result.
13054     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13055                        FIST, StackSlot, MachinePointerInfo(),
13056                        false, false, false, 0);
13057
13058   // The node is the result.
13059   return FIST;
13060 }
13061
13062 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13063                                            SelectionDAG &DAG) const {
13064   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13065     /*IsSigned=*/ false, /*IsReplace=*/ false);
13066   SDValue FIST = Vals.first, StackSlot = Vals.second;
13067   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13068   if (!FIST.getNode())
13069     return Op;
13070
13071   if (StackSlot.getNode())
13072     // Load the result.
13073     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13074                        FIST, StackSlot, MachinePointerInfo(),
13075                        false, false, false, 0);
13076
13077   // The node is the result.
13078   return FIST;
13079 }
13080
13081 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13082   SDLoc DL(Op);
13083   MVT VT = Op.getSimpleValueType();
13084   SDValue In = Op.getOperand(0);
13085   MVT SVT = In.getSimpleValueType();
13086
13087   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13088
13089   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13090                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13091                                  In, DAG.getUNDEF(SVT)));
13092 }
13093
13094 /// The only differences between FABS and FNEG are the mask and the logic op.
13095 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13096 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13097   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13098          "Wrong opcode for lowering FABS or FNEG.");
13099
13100   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13101
13102   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13103   // into an FNABS. We'll lower the FABS after that if it is still in use.
13104   if (IsFABS)
13105     for (SDNode *User : Op->uses())
13106       if (User->getOpcode() == ISD::FNEG)
13107         return Op;
13108
13109   SDLoc dl(Op);
13110   MVT VT = Op.getSimpleValueType();
13111
13112   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13113   // decide if we should generate a 16-byte constant mask when we only need 4 or
13114   // 8 bytes for the scalar case.
13115
13116   MVT LogicVT;
13117   MVT EltVT;
13118   unsigned NumElts;
13119
13120   if (VT.isVector()) {
13121     LogicVT = VT;
13122     EltVT = VT.getVectorElementType();
13123     NumElts = VT.getVectorNumElements();
13124   } else {
13125     // There are no scalar bitwise logical SSE/AVX instructions, so we
13126     // generate a 16-byte vector constant and logic op even for the scalar case.
13127     // Using a 16-byte mask allows folding the load of the mask with
13128     // the logic op, so it can save (~4 bytes) on code size.
13129     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13130     EltVT = VT;
13131     NumElts = (VT == MVT::f64) ? 2 : 4;
13132   }
13133
13134   unsigned EltBits = EltVT.getSizeInBits();
13135   LLVMContext *Context = DAG.getContext();
13136   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13137   APInt MaskElt =
13138     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13139   Constant *C = ConstantInt::get(*Context, MaskElt);
13140   C = ConstantVector::getSplat(NumElts, C);
13141   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13142   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13143   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13144   SDValue Mask =
13145       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13146                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13147                   false, false, false, Alignment);
13148
13149   SDValue Op0 = Op.getOperand(0);
13150   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13151   unsigned LogicOp =
13152     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13153   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13154
13155   if (VT.isVector())
13156     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13157
13158   // For the scalar case extend to a 128-bit vector, perform the logic op,
13159   // and extract the scalar result back out.
13160   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13161   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13162   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13163                      DAG.getIntPtrConstant(0, dl));
13164 }
13165
13166 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13167   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13168   LLVMContext *Context = DAG.getContext();
13169   SDValue Op0 = Op.getOperand(0);
13170   SDValue Op1 = Op.getOperand(1);
13171   SDLoc dl(Op);
13172   MVT VT = Op.getSimpleValueType();
13173   MVT SrcVT = Op1.getSimpleValueType();
13174
13175   // If second operand is smaller, extend it first.
13176   if (SrcVT.bitsLT(VT)) {
13177     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13178     SrcVT = VT;
13179   }
13180   // And if it is bigger, shrink it first.
13181   if (SrcVT.bitsGT(VT)) {
13182     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13183     SrcVT = VT;
13184   }
13185
13186   // At this point the operands and the result should have the same
13187   // type, and that won't be f80 since that is not custom lowered.
13188
13189   const fltSemantics &Sem =
13190       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
13191   const unsigned SizeInBits = VT.getSizeInBits();
13192
13193   SmallVector<Constant *, 4> CV(
13194       VT == MVT::f64 ? 2 : 4,
13195       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13196
13197   // First, clear all bits but the sign bit from the second operand (sign).
13198   CV[0] = ConstantFP::get(*Context,
13199                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13200   Constant *C = ConstantVector::get(CV);
13201   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13202   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13203
13204   // Perform all logic operations as 16-byte vectors because there are no
13205   // scalar FP logic instructions in SSE. This allows load folding of the
13206   // constants into the logic instructions.
13207   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13208   SDValue Mask1 =
13209       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13210                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13211                   false, false, false, 16);
13212   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13213   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13214
13215   // Next, clear the sign bit from the first operand (magnitude).
13216   // If it's a constant, we can clear it here.
13217   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13218     APFloat APF = Op0CN->getValueAPF();
13219     // If the magnitude is a positive zero, the sign bit alone is enough.
13220     if (APF.isPosZero())
13221       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13222                          DAG.getIntPtrConstant(0, dl));
13223     APF.clearSign();
13224     CV[0] = ConstantFP::get(*Context, APF);
13225   } else {
13226     CV[0] = ConstantFP::get(
13227         *Context,
13228         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13229   }
13230   C = ConstantVector::get(CV);
13231   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13232   SDValue Val =
13233       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13234                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13235                   false, false, false, 16);
13236   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13237   if (!isa<ConstantFPSDNode>(Op0)) {
13238     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13239     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13240   }
13241   // OR the magnitude value with the sign bit.
13242   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13243   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13244                      DAG.getIntPtrConstant(0, dl));
13245 }
13246
13247 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13248   SDValue N0 = Op.getOperand(0);
13249   SDLoc dl(Op);
13250   MVT VT = Op.getSimpleValueType();
13251
13252   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13253   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13254                                   DAG.getConstant(1, dl, VT));
13255   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13256 }
13257
13258 // Check whether an OR'd tree is PTEST-able.
13259 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13260                                       SelectionDAG &DAG) {
13261   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13262
13263   if (!Subtarget->hasSSE41())
13264     return SDValue();
13265
13266   if (!Op->hasOneUse())
13267     return SDValue();
13268
13269   SDNode *N = Op.getNode();
13270   SDLoc DL(N);
13271
13272   SmallVector<SDValue, 8> Opnds;
13273   DenseMap<SDValue, unsigned> VecInMap;
13274   SmallVector<SDValue, 8> VecIns;
13275   EVT VT = MVT::Other;
13276
13277   // Recognize a special case where a vector is casted into wide integer to
13278   // test all 0s.
13279   Opnds.push_back(N->getOperand(0));
13280   Opnds.push_back(N->getOperand(1));
13281
13282   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13283     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13284     // BFS traverse all OR'd operands.
13285     if (I->getOpcode() == ISD::OR) {
13286       Opnds.push_back(I->getOperand(0));
13287       Opnds.push_back(I->getOperand(1));
13288       // Re-evaluate the number of nodes to be traversed.
13289       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13290       continue;
13291     }
13292
13293     // Quit if a non-EXTRACT_VECTOR_ELT
13294     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13295       return SDValue();
13296
13297     // Quit if without a constant index.
13298     SDValue Idx = I->getOperand(1);
13299     if (!isa<ConstantSDNode>(Idx))
13300       return SDValue();
13301
13302     SDValue ExtractedFromVec = I->getOperand(0);
13303     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13304     if (M == VecInMap.end()) {
13305       VT = ExtractedFromVec.getValueType();
13306       // Quit if not 128/256-bit vector.
13307       if (!VT.is128BitVector() && !VT.is256BitVector())
13308         return SDValue();
13309       // Quit if not the same type.
13310       if (VecInMap.begin() != VecInMap.end() &&
13311           VT != VecInMap.begin()->first.getValueType())
13312         return SDValue();
13313       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13314       VecIns.push_back(ExtractedFromVec);
13315     }
13316     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13317   }
13318
13319   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13320          "Not extracted from 128-/256-bit vector.");
13321
13322   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13323
13324   for (DenseMap<SDValue, unsigned>::const_iterator
13325         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13326     // Quit if not all elements are used.
13327     if (I->second != FullMask)
13328       return SDValue();
13329   }
13330
13331   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13332
13333   // Cast all vectors into TestVT for PTEST.
13334   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13335     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13336
13337   // If more than one full vectors are evaluated, OR them first before PTEST.
13338   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13339     // Each iteration will OR 2 nodes and append the result until there is only
13340     // 1 node left, i.e. the final OR'd value of all vectors.
13341     SDValue LHS = VecIns[Slot];
13342     SDValue RHS = VecIns[Slot + 1];
13343     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13344   }
13345
13346   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13347                      VecIns.back(), VecIns.back());
13348 }
13349
13350 /// \brief return true if \c Op has a use that doesn't just read flags.
13351 static bool hasNonFlagsUse(SDValue Op) {
13352   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13353        ++UI) {
13354     SDNode *User = *UI;
13355     unsigned UOpNo = UI.getOperandNo();
13356     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13357       // Look pass truncate.
13358       UOpNo = User->use_begin().getOperandNo();
13359       User = *User->use_begin();
13360     }
13361
13362     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13363         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13364       return true;
13365   }
13366   return false;
13367 }
13368
13369 /// Emit nodes that will be selected as "test Op0,Op0", or something
13370 /// equivalent.
13371 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13372                                     SelectionDAG &DAG) const {
13373   if (Op.getValueType() == MVT::i1) {
13374     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13375     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13376                        DAG.getConstant(0, dl, MVT::i8));
13377   }
13378   // CF and OF aren't always set the way we want. Determine which
13379   // of these we need.
13380   bool NeedCF = false;
13381   bool NeedOF = false;
13382   switch (X86CC) {
13383   default: break;
13384   case X86::COND_A: case X86::COND_AE:
13385   case X86::COND_B: case X86::COND_BE:
13386     NeedCF = true;
13387     break;
13388   case X86::COND_G: case X86::COND_GE:
13389   case X86::COND_L: case X86::COND_LE:
13390   case X86::COND_O: case X86::COND_NO: {
13391     // Check if we really need to set the
13392     // Overflow flag. If NoSignedWrap is present
13393     // that is not actually needed.
13394     switch (Op->getOpcode()) {
13395     case ISD::ADD:
13396     case ISD::SUB:
13397     case ISD::MUL:
13398     case ISD::SHL: {
13399       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13400       if (BinNode->Flags.hasNoSignedWrap())
13401         break;
13402     }
13403     default:
13404       NeedOF = true;
13405       break;
13406     }
13407     break;
13408   }
13409   }
13410   // See if we can use the EFLAGS value from the operand instead of
13411   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13412   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13413   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13414     // Emit a CMP with 0, which is the TEST pattern.
13415     //if (Op.getValueType() == MVT::i1)
13416     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13417     //                     DAG.getConstant(0, MVT::i1));
13418     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13419                        DAG.getConstant(0, dl, Op.getValueType()));
13420   }
13421   unsigned Opcode = 0;
13422   unsigned NumOperands = 0;
13423
13424   // Truncate operations may prevent the merge of the SETCC instruction
13425   // and the arithmetic instruction before it. Attempt to truncate the operands
13426   // of the arithmetic instruction and use a reduced bit-width instruction.
13427   bool NeedTruncation = false;
13428   SDValue ArithOp = Op;
13429   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13430     SDValue Arith = Op->getOperand(0);
13431     // Both the trunc and the arithmetic op need to have one user each.
13432     if (Arith->hasOneUse())
13433       switch (Arith.getOpcode()) {
13434         default: break;
13435         case ISD::ADD:
13436         case ISD::SUB:
13437         case ISD::AND:
13438         case ISD::OR:
13439         case ISD::XOR: {
13440           NeedTruncation = true;
13441           ArithOp = Arith;
13442         }
13443       }
13444   }
13445
13446   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13447   // which may be the result of a CAST.  We use the variable 'Op', which is the
13448   // non-casted variable when we check for possible users.
13449   switch (ArithOp.getOpcode()) {
13450   case ISD::ADD:
13451     // Due to an isel shortcoming, be conservative if this add is likely to be
13452     // selected as part of a load-modify-store instruction. When the root node
13453     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13454     // uses of other nodes in the match, such as the ADD in this case. This
13455     // leads to the ADD being left around and reselected, with the result being
13456     // two adds in the output.  Alas, even if none our users are stores, that
13457     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13458     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13459     // climbing the DAG back to the root, and it doesn't seem to be worth the
13460     // effort.
13461     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13462          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13463       if (UI->getOpcode() != ISD::CopyToReg &&
13464           UI->getOpcode() != ISD::SETCC &&
13465           UI->getOpcode() != ISD::STORE)
13466         goto default_case;
13467
13468     if (ConstantSDNode *C =
13469         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13470       // An add of one will be selected as an INC.
13471       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13472         Opcode = X86ISD::INC;
13473         NumOperands = 1;
13474         break;
13475       }
13476
13477       // An add of negative one (subtract of one) will be selected as a DEC.
13478       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13479         Opcode = X86ISD::DEC;
13480         NumOperands = 1;
13481         break;
13482       }
13483     }
13484
13485     // Otherwise use a regular EFLAGS-setting add.
13486     Opcode = X86ISD::ADD;
13487     NumOperands = 2;
13488     break;
13489   case ISD::SHL:
13490   case ISD::SRL:
13491     // If we have a constant logical shift that's only used in a comparison
13492     // against zero turn it into an equivalent AND. This allows turning it into
13493     // a TEST instruction later.
13494     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13495         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13496       EVT VT = Op.getValueType();
13497       unsigned BitWidth = VT.getSizeInBits();
13498       unsigned ShAmt = Op->getConstantOperandVal(1);
13499       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13500         break;
13501       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13502                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13503                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13504       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13505         break;
13506       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13507                                 DAG.getConstant(Mask, dl, VT));
13508       DAG.ReplaceAllUsesWith(Op, New);
13509       Op = New;
13510     }
13511     break;
13512
13513   case ISD::AND:
13514     // If the primary and result isn't used, don't bother using X86ISD::AND,
13515     // because a TEST instruction will be better.
13516     if (!hasNonFlagsUse(Op))
13517       break;
13518     // FALL THROUGH
13519   case ISD::SUB:
13520   case ISD::OR:
13521   case ISD::XOR:
13522     // Due to the ISEL shortcoming noted above, be conservative if this op is
13523     // likely to be selected as part of a load-modify-store instruction.
13524     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13525            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13526       if (UI->getOpcode() == ISD::STORE)
13527         goto default_case;
13528
13529     // Otherwise use a regular EFLAGS-setting instruction.
13530     switch (ArithOp.getOpcode()) {
13531     default: llvm_unreachable("unexpected operator!");
13532     case ISD::SUB: Opcode = X86ISD::SUB; break;
13533     case ISD::XOR: Opcode = X86ISD::XOR; break;
13534     case ISD::AND: Opcode = X86ISD::AND; break;
13535     case ISD::OR: {
13536       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13537         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13538         if (EFLAGS.getNode())
13539           return EFLAGS;
13540       }
13541       Opcode = X86ISD::OR;
13542       break;
13543     }
13544     }
13545
13546     NumOperands = 2;
13547     break;
13548   case X86ISD::ADD:
13549   case X86ISD::SUB:
13550   case X86ISD::INC:
13551   case X86ISD::DEC:
13552   case X86ISD::OR:
13553   case X86ISD::XOR:
13554   case X86ISD::AND:
13555     return SDValue(Op.getNode(), 1);
13556   default:
13557   default_case:
13558     break;
13559   }
13560
13561   // If we found that truncation is beneficial, perform the truncation and
13562   // update 'Op'.
13563   if (NeedTruncation) {
13564     EVT VT = Op.getValueType();
13565     SDValue WideVal = Op->getOperand(0);
13566     EVT WideVT = WideVal.getValueType();
13567     unsigned ConvertedOp = 0;
13568     // Use a target machine opcode to prevent further DAGCombine
13569     // optimizations that may separate the arithmetic operations
13570     // from the setcc node.
13571     switch (WideVal.getOpcode()) {
13572       default: break;
13573       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13574       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13575       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13576       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13577       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13578     }
13579
13580     if (ConvertedOp) {
13581       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13582       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13583         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13584         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13585         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13586       }
13587     }
13588   }
13589
13590   if (Opcode == 0)
13591     // Emit a CMP with 0, which is the TEST pattern.
13592     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13593                        DAG.getConstant(0, dl, Op.getValueType()));
13594
13595   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13596   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13597
13598   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13599   DAG.ReplaceAllUsesWith(Op, New);
13600   return SDValue(New.getNode(), 1);
13601 }
13602
13603 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13604 /// equivalent.
13605 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13606                                    SDLoc dl, SelectionDAG &DAG) const {
13607   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13608     if (C->getAPIntValue() == 0)
13609       return EmitTest(Op0, X86CC, dl, DAG);
13610
13611      if (Op0.getValueType() == MVT::i1)
13612        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13613   }
13614
13615   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13616        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13617     // Do the comparison at i32 if it's smaller, besides the Atom case.
13618     // This avoids subregister aliasing issues. Keep the smaller reference
13619     // if we're optimizing for size, however, as that'll allow better folding
13620     // of memory operations.
13621     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13622         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13623         !Subtarget->isAtom()) {
13624       unsigned ExtendOp =
13625           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13626       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13627       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13628     }
13629     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13630     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13631     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13632                               Op0, Op1);
13633     return SDValue(Sub.getNode(), 1);
13634   }
13635   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13636 }
13637
13638 /// Convert a comparison if required by the subtarget.
13639 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13640                                                  SelectionDAG &DAG) const {
13641   // If the subtarget does not support the FUCOMI instruction, floating-point
13642   // comparisons have to be converted.
13643   if (Subtarget->hasCMov() ||
13644       Cmp.getOpcode() != X86ISD::CMP ||
13645       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13646       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13647     return Cmp;
13648
13649   // The instruction selector will select an FUCOM instruction instead of
13650   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13651   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13652   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13653   SDLoc dl(Cmp);
13654   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13655   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13656   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13657                             DAG.getConstant(8, dl, MVT::i8));
13658   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13659   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13660 }
13661
13662 /// The minimum architected relative accuracy is 2^-12. We need one
13663 /// Newton-Raphson step to have a good float result (24 bits of precision).
13664 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13665                                             DAGCombinerInfo &DCI,
13666                                             unsigned &RefinementSteps,
13667                                             bool &UseOneConstNR) const {
13668   EVT VT = Op.getValueType();
13669   const char *RecipOp;
13670
13671   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13672   // TODO: Add support for AVX512 (v16f32).
13673   // It is likely not profitable to do this for f64 because a double-precision
13674   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13675   // instructions: convert to single, rsqrtss, convert back to double, refine
13676   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13677   // along with FMA, this could be a throughput win.
13678   if (VT == MVT::f32 && Subtarget->hasSSE1())
13679     RecipOp = "sqrtf";
13680   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13681            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13682     RecipOp = "vec-sqrtf";
13683   else
13684     return SDValue();
13685
13686   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13687   if (!Recips.isEnabled(RecipOp))
13688     return SDValue();
13689
13690   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13691   UseOneConstNR = false;
13692   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13693 }
13694
13695 /// The minimum architected relative accuracy is 2^-12. We need one
13696 /// Newton-Raphson step to have a good float result (24 bits of precision).
13697 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13698                                             DAGCombinerInfo &DCI,
13699                                             unsigned &RefinementSteps) const {
13700   EVT VT = Op.getValueType();
13701   const char *RecipOp;
13702
13703   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13704   // TODO: Add support for AVX512 (v16f32).
13705   // It is likely not profitable to do this for f64 because a double-precision
13706   // reciprocal estimate with refinement on x86 prior to FMA requires
13707   // 15 instructions: convert to single, rcpss, convert back to double, refine
13708   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13709   // along with FMA, this could be a throughput win.
13710   if (VT == MVT::f32 && Subtarget->hasSSE1())
13711     RecipOp = "divf";
13712   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13713            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13714     RecipOp = "vec-divf";
13715   else
13716     return SDValue();
13717
13718   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13719   if (!Recips.isEnabled(RecipOp))
13720     return SDValue();
13721
13722   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13723   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13724 }
13725
13726 /// If we have at least two divisions that use the same divisor, convert to
13727 /// multplication by a reciprocal. This may need to be adjusted for a given
13728 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13729 /// This is because we still need one division to calculate the reciprocal and
13730 /// then we need two multiplies by that reciprocal as replacements for the
13731 /// original divisions.
13732 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13733   return 2;
13734 }
13735
13736 static bool isAllOnes(SDValue V) {
13737   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13738   return C && C->isAllOnesValue();
13739 }
13740
13741 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13742 /// if it's possible.
13743 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13744                                      SDLoc dl, SelectionDAG &DAG) const {
13745   SDValue Op0 = And.getOperand(0);
13746   SDValue Op1 = And.getOperand(1);
13747   if (Op0.getOpcode() == ISD::TRUNCATE)
13748     Op0 = Op0.getOperand(0);
13749   if (Op1.getOpcode() == ISD::TRUNCATE)
13750     Op1 = Op1.getOperand(0);
13751
13752   SDValue LHS, RHS;
13753   if (Op1.getOpcode() == ISD::SHL)
13754     std::swap(Op0, Op1);
13755   if (Op0.getOpcode() == ISD::SHL) {
13756     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13757       if (And00C->getZExtValue() == 1) {
13758         // If we looked past a truncate, check that it's only truncating away
13759         // known zeros.
13760         unsigned BitWidth = Op0.getValueSizeInBits();
13761         unsigned AndBitWidth = And.getValueSizeInBits();
13762         if (BitWidth > AndBitWidth) {
13763           APInt Zeros, Ones;
13764           DAG.computeKnownBits(Op0, Zeros, Ones);
13765           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13766             return SDValue();
13767         }
13768         LHS = Op1;
13769         RHS = Op0.getOperand(1);
13770       }
13771   } else if (Op1.getOpcode() == ISD::Constant) {
13772     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13773     uint64_t AndRHSVal = AndRHS->getZExtValue();
13774     SDValue AndLHS = Op0;
13775
13776     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13777       LHS = AndLHS.getOperand(0);
13778       RHS = AndLHS.getOperand(1);
13779     }
13780
13781     // Use BT if the immediate can't be encoded in a TEST instruction.
13782     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13783       LHS = AndLHS;
13784       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13785     }
13786   }
13787
13788   if (LHS.getNode()) {
13789     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13790     // instruction.  Since the shift amount is in-range-or-undefined, we know
13791     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13792     // the encoding for the i16 version is larger than the i32 version.
13793     // Also promote i16 to i32 for performance / code size reason.
13794     if (LHS.getValueType() == MVT::i8 ||
13795         LHS.getValueType() == MVT::i16)
13796       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13797
13798     // If the operand types disagree, extend the shift amount to match.  Since
13799     // BT ignores high bits (like shifts) we can use anyextend.
13800     if (LHS.getValueType() != RHS.getValueType())
13801       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13802
13803     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13804     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13805     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13806                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13807   }
13808
13809   return SDValue();
13810 }
13811
13812 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13813 /// mask CMPs.
13814 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13815                               SDValue &Op1) {
13816   unsigned SSECC;
13817   bool Swap = false;
13818
13819   // SSE Condition code mapping:
13820   //  0 - EQ
13821   //  1 - LT
13822   //  2 - LE
13823   //  3 - UNORD
13824   //  4 - NEQ
13825   //  5 - NLT
13826   //  6 - NLE
13827   //  7 - ORD
13828   switch (SetCCOpcode) {
13829   default: llvm_unreachable("Unexpected SETCC condition");
13830   case ISD::SETOEQ:
13831   case ISD::SETEQ:  SSECC = 0; break;
13832   case ISD::SETOGT:
13833   case ISD::SETGT:  Swap = true; // Fallthrough
13834   case ISD::SETLT:
13835   case ISD::SETOLT: SSECC = 1; break;
13836   case ISD::SETOGE:
13837   case ISD::SETGE:  Swap = true; // Fallthrough
13838   case ISD::SETLE:
13839   case ISD::SETOLE: SSECC = 2; break;
13840   case ISD::SETUO:  SSECC = 3; break;
13841   case ISD::SETUNE:
13842   case ISD::SETNE:  SSECC = 4; break;
13843   case ISD::SETULE: Swap = true; // Fallthrough
13844   case ISD::SETUGE: SSECC = 5; break;
13845   case ISD::SETULT: Swap = true; // Fallthrough
13846   case ISD::SETUGT: SSECC = 6; break;
13847   case ISD::SETO:   SSECC = 7; break;
13848   case ISD::SETUEQ:
13849   case ISD::SETONE: SSECC = 8; break;
13850   }
13851   if (Swap)
13852     std::swap(Op0, Op1);
13853
13854   return SSECC;
13855 }
13856
13857 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13858 // ones, and then concatenate the result back.
13859 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13860   MVT VT = Op.getSimpleValueType();
13861
13862   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13863          "Unsupported value type for operation");
13864
13865   unsigned NumElems = VT.getVectorNumElements();
13866   SDLoc dl(Op);
13867   SDValue CC = Op.getOperand(2);
13868
13869   // Extract the LHS vectors
13870   SDValue LHS = Op.getOperand(0);
13871   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13872   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13873
13874   // Extract the RHS vectors
13875   SDValue RHS = Op.getOperand(1);
13876   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13877   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13878
13879   // Issue the operation on the smaller types and concatenate the result back
13880   MVT EltVT = VT.getVectorElementType();
13881   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13882   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13883                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13884                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13885 }
13886
13887 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13888   SDValue Op0 = Op.getOperand(0);
13889   SDValue Op1 = Op.getOperand(1);
13890   SDValue CC = Op.getOperand(2);
13891   MVT VT = Op.getSimpleValueType();
13892   SDLoc dl(Op);
13893
13894   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13895          "Unexpected type for boolean compare operation");
13896   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13897   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13898                                DAG.getConstant(-1, dl, VT));
13899   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13900                                DAG.getConstant(-1, dl, VT));
13901   switch (SetCCOpcode) {
13902   default: llvm_unreachable("Unexpected SETCC condition");
13903   case ISD::SETEQ:
13904     // (x == y) -> ~(x ^ y)
13905     return DAG.getNode(ISD::XOR, dl, VT,
13906                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13907                        DAG.getConstant(-1, dl, VT));
13908   case ISD::SETNE:
13909     // (x != y) -> (x ^ y)
13910     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13911   case ISD::SETUGT:
13912   case ISD::SETGT:
13913     // (x > y) -> (x & ~y)
13914     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13915   case ISD::SETULT:
13916   case ISD::SETLT:
13917     // (x < y) -> (~x & y)
13918     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13919   case ISD::SETULE:
13920   case ISD::SETLE:
13921     // (x <= y) -> (~x | y)
13922     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13923   case ISD::SETUGE:
13924   case ISD::SETGE:
13925     // (x >=y) -> (x | ~y)
13926     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13927   }
13928 }
13929
13930 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13931                                      const X86Subtarget *Subtarget) {
13932   SDValue Op0 = Op.getOperand(0);
13933   SDValue Op1 = Op.getOperand(1);
13934   SDValue CC = Op.getOperand(2);
13935   MVT VT = Op.getSimpleValueType();
13936   SDLoc dl(Op);
13937
13938   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13939          Op.getValueType().getScalarType() == MVT::i1 &&
13940          "Cannot set masked compare for this operation");
13941
13942   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13943   unsigned  Opc = 0;
13944   bool Unsigned = false;
13945   bool Swap = false;
13946   unsigned SSECC;
13947   switch (SetCCOpcode) {
13948   default: llvm_unreachable("Unexpected SETCC condition");
13949   case ISD::SETNE:  SSECC = 4; break;
13950   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13951   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13952   case ISD::SETLT:  Swap = true; //fall-through
13953   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13954   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13955   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13956   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13957   case ISD::SETULE: Unsigned = true; //fall-through
13958   case ISD::SETLE:  SSECC = 2; break;
13959   }
13960
13961   if (Swap)
13962     std::swap(Op0, Op1);
13963   if (Opc)
13964     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13965   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13966   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13967                      DAG.getConstant(SSECC, dl, MVT::i8));
13968 }
13969
13970 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13971 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13972 /// return an empty value.
13973 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13974 {
13975   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13976   if (!BV)
13977     return SDValue();
13978
13979   MVT VT = Op1.getSimpleValueType();
13980   MVT EVT = VT.getVectorElementType();
13981   unsigned n = VT.getVectorNumElements();
13982   SmallVector<SDValue, 8> ULTOp1;
13983
13984   for (unsigned i = 0; i < n; ++i) {
13985     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13986     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13987       return SDValue();
13988
13989     // Avoid underflow.
13990     APInt Val = Elt->getAPIntValue();
13991     if (Val == 0)
13992       return SDValue();
13993
13994     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13995   }
13996
13997   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13998 }
13999
14000 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14001                            SelectionDAG &DAG) {
14002   SDValue Op0 = Op.getOperand(0);
14003   SDValue Op1 = Op.getOperand(1);
14004   SDValue CC = Op.getOperand(2);
14005   MVT VT = Op.getSimpleValueType();
14006   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14007   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14008   SDLoc dl(Op);
14009
14010   if (isFP) {
14011 #ifndef NDEBUG
14012     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14013     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14014 #endif
14015
14016     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14017     unsigned Opc = X86ISD::CMPP;
14018     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14019       assert(VT.getVectorNumElements() <= 16);
14020       Opc = X86ISD::CMPM;
14021     }
14022     // In the two special cases we can't handle, emit two comparisons.
14023     if (SSECC == 8) {
14024       unsigned CC0, CC1;
14025       unsigned CombineOpc;
14026       if (SetCCOpcode == ISD::SETUEQ) {
14027         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14028       } else {
14029         assert(SetCCOpcode == ISD::SETONE);
14030         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14031       }
14032
14033       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14034                                  DAG.getConstant(CC0, dl, MVT::i8));
14035       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14036                                  DAG.getConstant(CC1, dl, MVT::i8));
14037       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14038     }
14039     // Handle all other FP comparisons here.
14040     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14041                        DAG.getConstant(SSECC, dl, MVT::i8));
14042   }
14043
14044   // Break 256-bit integer vector compare into smaller ones.
14045   if (VT.is256BitVector() && !Subtarget->hasInt256())
14046     return Lower256IntVSETCC(Op, DAG);
14047
14048   EVT OpVT = Op1.getValueType();
14049   if (OpVT.getVectorElementType() == MVT::i1)
14050     return LowerBoolVSETCC_AVX512(Op, DAG);
14051
14052   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14053   if (Subtarget->hasAVX512()) {
14054     if (Op1.getValueType().is512BitVector() ||
14055         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14056         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14057       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14058
14059     // In AVX-512 architecture setcc returns mask with i1 elements,
14060     // But there is no compare instruction for i8 and i16 elements in KNL.
14061     // We are not talking about 512-bit operands in this case, these
14062     // types are illegal.
14063     if (MaskResult &&
14064         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14065          OpVT.getVectorElementType().getSizeInBits() >= 8))
14066       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14067                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14068   }
14069
14070   // We are handling one of the integer comparisons here.  Since SSE only has
14071   // GT and EQ comparisons for integer, swapping operands and multiple
14072   // operations may be required for some comparisons.
14073   unsigned Opc;
14074   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14075   bool Subus = false;
14076
14077   switch (SetCCOpcode) {
14078   default: llvm_unreachable("Unexpected SETCC condition");
14079   case ISD::SETNE:  Invert = true;
14080   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14081   case ISD::SETLT:  Swap = true;
14082   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14083   case ISD::SETGE:  Swap = true;
14084   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14085                     Invert = true; break;
14086   case ISD::SETULT: Swap = true;
14087   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14088                     FlipSigns = true; break;
14089   case ISD::SETUGE: Swap = true;
14090   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14091                     FlipSigns = true; Invert = true; break;
14092   }
14093
14094   // Special case: Use min/max operations for SETULE/SETUGE
14095   MVT VET = VT.getVectorElementType();
14096   bool hasMinMax =
14097        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14098     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14099
14100   if (hasMinMax) {
14101     switch (SetCCOpcode) {
14102     default: break;
14103     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14104     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14105     }
14106
14107     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14108   }
14109
14110   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14111   if (!MinMax && hasSubus) {
14112     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14113     // Op0 u<= Op1:
14114     //   t = psubus Op0, Op1
14115     //   pcmpeq t, <0..0>
14116     switch (SetCCOpcode) {
14117     default: break;
14118     case ISD::SETULT: {
14119       // If the comparison is against a constant we can turn this into a
14120       // setule.  With psubus, setule does not require a swap.  This is
14121       // beneficial because the constant in the register is no longer
14122       // destructed as the destination so it can be hoisted out of a loop.
14123       // Only do this pre-AVX since vpcmp* is no longer destructive.
14124       if (Subtarget->hasAVX())
14125         break;
14126       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14127       if (ULEOp1.getNode()) {
14128         Op1 = ULEOp1;
14129         Subus = true; Invert = false; Swap = false;
14130       }
14131       break;
14132     }
14133     // Psubus is better than flip-sign because it requires no inversion.
14134     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14135     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14136     }
14137
14138     if (Subus) {
14139       Opc = X86ISD::SUBUS;
14140       FlipSigns = false;
14141     }
14142   }
14143
14144   if (Swap)
14145     std::swap(Op0, Op1);
14146
14147   // Check that the operation in question is available (most are plain SSE2,
14148   // but PCMPGTQ and PCMPEQQ have different requirements).
14149   if (VT == MVT::v2i64) {
14150     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14151       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14152
14153       // First cast everything to the right type.
14154       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14155       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14156
14157       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14158       // bits of the inputs before performing those operations. The lower
14159       // compare is always unsigned.
14160       SDValue SB;
14161       if (FlipSigns) {
14162         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14163       } else {
14164         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14165         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14166         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14167                          Sign, Zero, Sign, Zero);
14168       }
14169       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14170       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14171
14172       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14173       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14174       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14175
14176       // Create masks for only the low parts/high parts of the 64 bit integers.
14177       static const int MaskHi[] = { 1, 1, 3, 3 };
14178       static const int MaskLo[] = { 0, 0, 2, 2 };
14179       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14180       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14181       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14182
14183       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14184       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14185
14186       if (Invert)
14187         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14188
14189       return DAG.getBitcast(VT, Result);
14190     }
14191
14192     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14193       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14194       // pcmpeqd + pshufd + pand.
14195       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14196
14197       // First cast everything to the right type.
14198       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14199       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14200
14201       // Do the compare.
14202       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14203
14204       // Make sure the lower and upper halves are both all-ones.
14205       static const int Mask[] = { 1, 0, 3, 2 };
14206       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14207       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14208
14209       if (Invert)
14210         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14211
14212       return DAG.getBitcast(VT, Result);
14213     }
14214   }
14215
14216   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14217   // bits of the inputs before performing those operations.
14218   if (FlipSigns) {
14219     EVT EltVT = VT.getVectorElementType();
14220     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14221                                  VT);
14222     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14223     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14224   }
14225
14226   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14227
14228   // If the logical-not of the result is required, perform that now.
14229   if (Invert)
14230     Result = DAG.getNOT(dl, Result, VT);
14231
14232   if (MinMax)
14233     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14234
14235   if (Subus)
14236     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14237                          getZeroVector(VT, Subtarget, DAG, dl));
14238
14239   return Result;
14240 }
14241
14242 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14243
14244   MVT VT = Op.getSimpleValueType();
14245
14246   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14247
14248   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14249          && "SetCC type must be 8-bit or 1-bit integer");
14250   SDValue Op0 = Op.getOperand(0);
14251   SDValue Op1 = Op.getOperand(1);
14252   SDLoc dl(Op);
14253   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14254
14255   // Optimize to BT if possible.
14256   // Lower (X & (1 << N)) == 0 to BT(X, N).
14257   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14258   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14259   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14260       Op1.getOpcode() == ISD::Constant &&
14261       cast<ConstantSDNode>(Op1)->isNullValue() &&
14262       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14263     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14264     if (NewSetCC.getNode()) {
14265       if (VT == MVT::i1)
14266         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14267       return NewSetCC;
14268     }
14269   }
14270
14271   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14272   // these.
14273   if (Op1.getOpcode() == ISD::Constant &&
14274       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14275        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14276       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14277
14278     // If the input is a setcc, then reuse the input setcc or use a new one with
14279     // the inverted condition.
14280     if (Op0.getOpcode() == X86ISD::SETCC) {
14281       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14282       bool Invert = (CC == ISD::SETNE) ^
14283         cast<ConstantSDNode>(Op1)->isNullValue();
14284       if (!Invert)
14285         return Op0;
14286
14287       CCode = X86::GetOppositeBranchCondition(CCode);
14288       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14289                                   DAG.getConstant(CCode, dl, MVT::i8),
14290                                   Op0.getOperand(1));
14291       if (VT == MVT::i1)
14292         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14293       return SetCC;
14294     }
14295   }
14296   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14297       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14298       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14299
14300     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14301     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14302   }
14303
14304   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14305   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14306   if (X86CC == X86::COND_INVALID)
14307     return SDValue();
14308
14309   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14310   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14311   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14312                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14313   if (VT == MVT::i1)
14314     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14315   return SetCC;
14316 }
14317
14318 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14319 static bool isX86LogicalCmp(SDValue Op) {
14320   unsigned Opc = Op.getNode()->getOpcode();
14321   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14322       Opc == X86ISD::SAHF)
14323     return true;
14324   if (Op.getResNo() == 1 &&
14325       (Opc == X86ISD::ADD ||
14326        Opc == X86ISD::SUB ||
14327        Opc == X86ISD::ADC ||
14328        Opc == X86ISD::SBB ||
14329        Opc == X86ISD::SMUL ||
14330        Opc == X86ISD::UMUL ||
14331        Opc == X86ISD::INC ||
14332        Opc == X86ISD::DEC ||
14333        Opc == X86ISD::OR ||
14334        Opc == X86ISD::XOR ||
14335        Opc == X86ISD::AND))
14336     return true;
14337
14338   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14339     return true;
14340
14341   return false;
14342 }
14343
14344 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14345   if (V.getOpcode() != ISD::TRUNCATE)
14346     return false;
14347
14348   SDValue VOp0 = V.getOperand(0);
14349   unsigned InBits = VOp0.getValueSizeInBits();
14350   unsigned Bits = V.getValueSizeInBits();
14351   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14352 }
14353
14354 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14355   bool addTest = true;
14356   SDValue Cond  = Op.getOperand(0);
14357   SDValue Op1 = Op.getOperand(1);
14358   SDValue Op2 = Op.getOperand(2);
14359   SDLoc DL(Op);
14360   EVT VT = Op1.getValueType();
14361   SDValue CC;
14362
14363   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14364   // are available or VBLENDV if AVX is available.
14365   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14366   if (Cond.getOpcode() == ISD::SETCC &&
14367       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14368        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14369       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14370     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14371     int SSECC = translateX86FSETCC(
14372         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14373
14374     if (SSECC != 8) {
14375       if (Subtarget->hasAVX512()) {
14376         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14377                                   DAG.getConstant(SSECC, DL, MVT::i8));
14378         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14379       }
14380
14381       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14382                                 DAG.getConstant(SSECC, DL, MVT::i8));
14383
14384       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14385       // of 3 logic instructions for size savings and potentially speed.
14386       // Unfortunately, there is no scalar form of VBLENDV.
14387
14388       // If either operand is a constant, don't try this. We can expect to
14389       // optimize away at least one of the logic instructions later in that
14390       // case, so that sequence would be faster than a variable blend.
14391
14392       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14393       // uses XMM0 as the selection register. That may need just as many
14394       // instructions as the AND/ANDN/OR sequence due to register moves, so
14395       // don't bother.
14396
14397       if (Subtarget->hasAVX() &&
14398           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14399
14400         // Convert to vectors, do a VSELECT, and convert back to scalar.
14401         // All of the conversions should be optimized away.
14402
14403         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14404         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14405         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14406         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14407
14408         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14409         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14410
14411         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14412
14413         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14414                            VSel, DAG.getIntPtrConstant(0, DL));
14415       }
14416       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14417       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14418       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14419     }
14420   }
14421
14422   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14423     SDValue Op1Scalar;
14424     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14425       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14426     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14427       Op1Scalar = Op1.getOperand(0);
14428     SDValue Op2Scalar;
14429     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14430       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14431     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14432       Op2Scalar = Op2.getOperand(0);
14433     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14434       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14435                                       Op1Scalar.getValueType(),
14436                                       Cond, Op1Scalar, Op2Scalar);
14437       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14438         return DAG.getBitcast(VT, newSelect);
14439       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14440       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14441                          DAG.getIntPtrConstant(0, DL));
14442     }
14443   }
14444
14445   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14446     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14447     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14448                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14449     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14450                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14451     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14452                                     Cond, Op1, Op2);
14453     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14454   }
14455
14456   if (Cond.getOpcode() == ISD::SETCC) {
14457     SDValue NewCond = LowerSETCC(Cond, DAG);
14458     if (NewCond.getNode())
14459       Cond = NewCond;
14460   }
14461
14462   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14463   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14464   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14465   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14466   if (Cond.getOpcode() == X86ISD::SETCC &&
14467       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14468       isZero(Cond.getOperand(1).getOperand(1))) {
14469     SDValue Cmp = Cond.getOperand(1);
14470
14471     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14472
14473     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14474         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14475       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14476
14477       SDValue CmpOp0 = Cmp.getOperand(0);
14478       // Apply further optimizations for special cases
14479       // (select (x != 0), -1, 0) -> neg & sbb
14480       // (select (x == 0), 0, -1) -> neg & sbb
14481       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14482         if (YC->isNullValue() &&
14483             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14484           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14485           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14486                                     DAG.getConstant(0, DL,
14487                                                     CmpOp0.getValueType()),
14488                                     CmpOp0);
14489           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14490                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14491                                     SDValue(Neg.getNode(), 1));
14492           return Res;
14493         }
14494
14495       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14496                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14497       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14498
14499       SDValue Res =   // Res = 0 or -1.
14500         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14501                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14502
14503       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14504         Res = DAG.getNOT(DL, Res, Res.getValueType());
14505
14506       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14507       if (!N2C || !N2C->isNullValue())
14508         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14509       return Res;
14510     }
14511   }
14512
14513   // Look past (and (setcc_carry (cmp ...)), 1).
14514   if (Cond.getOpcode() == ISD::AND &&
14515       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14516     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14517     if (C && C->getAPIntValue() == 1)
14518       Cond = Cond.getOperand(0);
14519   }
14520
14521   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14522   // setting operand in place of the X86ISD::SETCC.
14523   unsigned CondOpcode = Cond.getOpcode();
14524   if (CondOpcode == X86ISD::SETCC ||
14525       CondOpcode == X86ISD::SETCC_CARRY) {
14526     CC = Cond.getOperand(0);
14527
14528     SDValue Cmp = Cond.getOperand(1);
14529     unsigned Opc = Cmp.getOpcode();
14530     MVT VT = Op.getSimpleValueType();
14531
14532     bool IllegalFPCMov = false;
14533     if (VT.isFloatingPoint() && !VT.isVector() &&
14534         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14535       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14536
14537     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14538         Opc == X86ISD::BT) { // FIXME
14539       Cond = Cmp;
14540       addTest = false;
14541     }
14542   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14543              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14544              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14545               Cond.getOperand(0).getValueType() != MVT::i8)) {
14546     SDValue LHS = Cond.getOperand(0);
14547     SDValue RHS = Cond.getOperand(1);
14548     unsigned X86Opcode;
14549     unsigned X86Cond;
14550     SDVTList VTs;
14551     switch (CondOpcode) {
14552     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14553     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14554     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14555     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14556     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14557     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14558     default: llvm_unreachable("unexpected overflowing operator");
14559     }
14560     if (CondOpcode == ISD::UMULO)
14561       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14562                           MVT::i32);
14563     else
14564       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14565
14566     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14567
14568     if (CondOpcode == ISD::UMULO)
14569       Cond = X86Op.getValue(2);
14570     else
14571       Cond = X86Op.getValue(1);
14572
14573     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14574     addTest = false;
14575   }
14576
14577   if (addTest) {
14578     // Look past the truncate if the high bits are known zero.
14579     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14580       Cond = Cond.getOperand(0);
14581
14582     // We know the result of AND is compared against zero. Try to match
14583     // it to BT.
14584     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14585       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14586       if (NewSetCC.getNode()) {
14587         CC = NewSetCC.getOperand(0);
14588         Cond = NewSetCC.getOperand(1);
14589         addTest = false;
14590       }
14591     }
14592   }
14593
14594   if (addTest) {
14595     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14596     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14597   }
14598
14599   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14600   // a <  b ?  0 : -1 -> RES = setcc_carry
14601   // a >= b ? -1 :  0 -> RES = setcc_carry
14602   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14603   if (Cond.getOpcode() == X86ISD::SUB) {
14604     Cond = ConvertCmpIfNecessary(Cond, DAG);
14605     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14606
14607     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14608         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14609       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14610                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14611                                 Cond);
14612       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14613         return DAG.getNOT(DL, Res, Res.getValueType());
14614       return Res;
14615     }
14616   }
14617
14618   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14619   // widen the cmov and push the truncate through. This avoids introducing a new
14620   // branch during isel and doesn't add any extensions.
14621   if (Op.getValueType() == MVT::i8 &&
14622       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14623     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14624     if (T1.getValueType() == T2.getValueType() &&
14625         // Blacklist CopyFromReg to avoid partial register stalls.
14626         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14627       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14628       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14629       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14630     }
14631   }
14632
14633   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14634   // condition is true.
14635   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14636   SDValue Ops[] = { Op2, Op1, CC, Cond };
14637   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14638 }
14639
14640 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14641                                        const X86Subtarget *Subtarget,
14642                                        SelectionDAG &DAG) {
14643   MVT VT = Op->getSimpleValueType(0);
14644   SDValue In = Op->getOperand(0);
14645   MVT InVT = In.getSimpleValueType();
14646   MVT VTElt = VT.getVectorElementType();
14647   MVT InVTElt = InVT.getVectorElementType();
14648   SDLoc dl(Op);
14649
14650   // SKX processor
14651   if ((InVTElt == MVT::i1) &&
14652       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14653         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14654
14655        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14656         VTElt.getSizeInBits() <= 16)) ||
14657
14658        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14659         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14660
14661        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14662         VTElt.getSizeInBits() >= 32))))
14663     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14664
14665   unsigned int NumElts = VT.getVectorNumElements();
14666
14667   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14668     return SDValue();
14669
14670   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14671     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14672       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14673     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14674   }
14675
14676   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14677   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14678   SDValue NegOne =
14679    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14680                    ExtVT);
14681   SDValue Zero =
14682    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14683
14684   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14685   if (VT.is512BitVector())
14686     return V;
14687   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14688 }
14689
14690 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14691                                              const X86Subtarget *Subtarget,
14692                                              SelectionDAG &DAG) {
14693   SDValue In = Op->getOperand(0);
14694   MVT VT = Op->getSimpleValueType(0);
14695   MVT InVT = In.getSimpleValueType();
14696   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14697
14698   MVT InSVT = InVT.getScalarType();
14699   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14700
14701   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14702     return SDValue();
14703   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14704     return SDValue();
14705
14706   SDLoc dl(Op);
14707
14708   // SSE41 targets can use the pmovsx* instructions directly.
14709   if (Subtarget->hasSSE41())
14710     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14711
14712   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14713   SDValue Curr = In;
14714   MVT CurrVT = InVT;
14715
14716   // As SRAI is only available on i16/i32 types, we expand only up to i32
14717   // and handle i64 separately.
14718   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14719     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14720     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14721     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14722     Curr = DAG.getBitcast(CurrVT, Curr);
14723   }
14724
14725   SDValue SignExt = Curr;
14726   if (CurrVT != InVT) {
14727     unsigned SignExtShift =
14728         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14729     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14730                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14731   }
14732
14733   if (CurrVT == VT)
14734     return SignExt;
14735
14736   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14737     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14738                                DAG.getConstant(31, dl, MVT::i8));
14739     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14740     return DAG.getBitcast(VT, Ext);
14741   }
14742
14743   return SDValue();
14744 }
14745
14746 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14747                                 SelectionDAG &DAG) {
14748   MVT VT = Op->getSimpleValueType(0);
14749   SDValue In = Op->getOperand(0);
14750   MVT InVT = In.getSimpleValueType();
14751   SDLoc dl(Op);
14752
14753   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14754     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14755
14756   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14757       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14758       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14759     return SDValue();
14760
14761   if (Subtarget->hasInt256())
14762     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14763
14764   // Optimize vectors in AVX mode
14765   // Sign extend  v8i16 to v8i32 and
14766   //              v4i32 to v4i64
14767   //
14768   // Divide input vector into two parts
14769   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14770   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14771   // concat the vectors to original VT
14772
14773   unsigned NumElems = InVT.getVectorNumElements();
14774   SDValue Undef = DAG.getUNDEF(InVT);
14775
14776   SmallVector<int,8> ShufMask1(NumElems, -1);
14777   for (unsigned i = 0; i != NumElems/2; ++i)
14778     ShufMask1[i] = i;
14779
14780   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14781
14782   SmallVector<int,8> ShufMask2(NumElems, -1);
14783   for (unsigned i = 0; i != NumElems/2; ++i)
14784     ShufMask2[i] = i + NumElems/2;
14785
14786   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14787
14788   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14789                                 VT.getVectorNumElements()/2);
14790
14791   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14792   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14793
14794   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14795 }
14796
14797 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14798 // may emit an illegal shuffle but the expansion is still better than scalar
14799 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14800 // we'll emit a shuffle and a arithmetic shift.
14801 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14802 // TODO: It is possible to support ZExt by zeroing the undef values during
14803 // the shuffle phase or after the shuffle.
14804 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14805                                  SelectionDAG &DAG) {
14806   MVT RegVT = Op.getSimpleValueType();
14807   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14808   assert(RegVT.isInteger() &&
14809          "We only custom lower integer vector sext loads.");
14810
14811   // Nothing useful we can do without SSE2 shuffles.
14812   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14813
14814   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14815   SDLoc dl(Ld);
14816   EVT MemVT = Ld->getMemoryVT();
14817   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14818   unsigned RegSz = RegVT.getSizeInBits();
14819
14820   ISD::LoadExtType Ext = Ld->getExtensionType();
14821
14822   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14823          && "Only anyext and sext are currently implemented.");
14824   assert(MemVT != RegVT && "Cannot extend to the same type");
14825   assert(MemVT.isVector() && "Must load a vector from memory");
14826
14827   unsigned NumElems = RegVT.getVectorNumElements();
14828   unsigned MemSz = MemVT.getSizeInBits();
14829   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14830
14831   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14832     // The only way in which we have a legal 256-bit vector result but not the
14833     // integer 256-bit operations needed to directly lower a sextload is if we
14834     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14835     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14836     // correctly legalized. We do this late to allow the canonical form of
14837     // sextload to persist throughout the rest of the DAG combiner -- it wants
14838     // to fold together any extensions it can, and so will fuse a sign_extend
14839     // of an sextload into a sextload targeting a wider value.
14840     SDValue Load;
14841     if (MemSz == 128) {
14842       // Just switch this to a normal load.
14843       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14844                                        "it must be a legal 128-bit vector "
14845                                        "type!");
14846       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14847                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14848                   Ld->isInvariant(), Ld->getAlignment());
14849     } else {
14850       assert(MemSz < 128 &&
14851              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14852       // Do an sext load to a 128-bit vector type. We want to use the same
14853       // number of elements, but elements half as wide. This will end up being
14854       // recursively lowered by this routine, but will succeed as we definitely
14855       // have all the necessary features if we're using AVX1.
14856       EVT HalfEltVT =
14857           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14858       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14859       Load =
14860           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14861                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14862                          Ld->isNonTemporal(), Ld->isInvariant(),
14863                          Ld->getAlignment());
14864     }
14865
14866     // Replace chain users with the new chain.
14867     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14868     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14869
14870     // Finally, do a normal sign-extend to the desired register.
14871     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14872   }
14873
14874   // All sizes must be a power of two.
14875   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14876          "Non-power-of-two elements are not custom lowered!");
14877
14878   // Attempt to load the original value using scalar loads.
14879   // Find the largest scalar type that divides the total loaded size.
14880   MVT SclrLoadTy = MVT::i8;
14881   for (MVT Tp : MVT::integer_valuetypes()) {
14882     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14883       SclrLoadTy = Tp;
14884     }
14885   }
14886
14887   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14888   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14889       (64 <= MemSz))
14890     SclrLoadTy = MVT::f64;
14891
14892   // Calculate the number of scalar loads that we need to perform
14893   // in order to load our vector from memory.
14894   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14895
14896   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14897          "Can only lower sext loads with a single scalar load!");
14898
14899   unsigned loadRegZize = RegSz;
14900   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14901     loadRegZize = 128;
14902
14903   // Represent our vector as a sequence of elements which are the
14904   // largest scalar that we can load.
14905   EVT LoadUnitVecVT = EVT::getVectorVT(
14906       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14907
14908   // Represent the data using the same element type that is stored in
14909   // memory. In practice, we ''widen'' MemVT.
14910   EVT WideVecVT =
14911       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14912                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14913
14914   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14915          "Invalid vector type");
14916
14917   // We can't shuffle using an illegal type.
14918   assert(TLI.isTypeLegal(WideVecVT) &&
14919          "We only lower types that form legal widened vector types");
14920
14921   SmallVector<SDValue, 8> Chains;
14922   SDValue Ptr = Ld->getBasePtr();
14923   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14924                                       TLI.getPointerTy(DAG.getDataLayout()));
14925   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14926
14927   for (unsigned i = 0; i < NumLoads; ++i) {
14928     // Perform a single load.
14929     SDValue ScalarLoad =
14930         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14931                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14932                     Ld->getAlignment());
14933     Chains.push_back(ScalarLoad.getValue(1));
14934     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14935     // another round of DAGCombining.
14936     if (i == 0)
14937       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14938     else
14939       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14940                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14941
14942     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14943   }
14944
14945   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14946
14947   // Bitcast the loaded value to a vector of the original element type, in
14948   // the size of the target vector type.
14949   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14950   unsigned SizeRatio = RegSz / MemSz;
14951
14952   if (Ext == ISD::SEXTLOAD) {
14953     // If we have SSE4.1, we can directly emit a VSEXT node.
14954     if (Subtarget->hasSSE41()) {
14955       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14956       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14957       return Sext;
14958     }
14959
14960     // Otherwise we'll shuffle the small elements in the high bits of the
14961     // larger type and perform an arithmetic shift. If the shift is not legal
14962     // it's better to scalarize.
14963     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14964            "We can't implement a sext load without an arithmetic right shift!");
14965
14966     // Redistribute the loaded elements into the different locations.
14967     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14968     for (unsigned i = 0; i != NumElems; ++i)
14969       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14970
14971     SDValue Shuff = DAG.getVectorShuffle(
14972         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14973
14974     Shuff = DAG.getBitcast(RegVT, Shuff);
14975
14976     // Build the arithmetic shift.
14977     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14978                    MemVT.getVectorElementType().getSizeInBits();
14979     Shuff =
14980         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14981                     DAG.getConstant(Amt, dl, RegVT));
14982
14983     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14984     return Shuff;
14985   }
14986
14987   // Redistribute the loaded elements into the different locations.
14988   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14989   for (unsigned i = 0; i != NumElems; ++i)
14990     ShuffleVec[i * SizeRatio] = i;
14991
14992   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14993                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14994
14995   // Bitcast to the requested type.
14996   Shuff = DAG.getBitcast(RegVT, Shuff);
14997   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14998   return Shuff;
14999 }
15000
15001 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15002 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15003 // from the AND / OR.
15004 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15005   Opc = Op.getOpcode();
15006   if (Opc != ISD::OR && Opc != ISD::AND)
15007     return false;
15008   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15009           Op.getOperand(0).hasOneUse() &&
15010           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15011           Op.getOperand(1).hasOneUse());
15012 }
15013
15014 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15015 // 1 and that the SETCC node has a single use.
15016 static bool isXor1OfSetCC(SDValue Op) {
15017   if (Op.getOpcode() != ISD::XOR)
15018     return false;
15019   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15020   if (N1C && N1C->getAPIntValue() == 1) {
15021     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15022       Op.getOperand(0).hasOneUse();
15023   }
15024   return false;
15025 }
15026
15027 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15028   bool addTest = true;
15029   SDValue Chain = Op.getOperand(0);
15030   SDValue Cond  = Op.getOperand(1);
15031   SDValue Dest  = Op.getOperand(2);
15032   SDLoc dl(Op);
15033   SDValue CC;
15034   bool Inverted = false;
15035
15036   if (Cond.getOpcode() == ISD::SETCC) {
15037     // Check for setcc([su]{add,sub,mul}o == 0).
15038     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15039         isa<ConstantSDNode>(Cond.getOperand(1)) &&
15040         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
15041         Cond.getOperand(0).getResNo() == 1 &&
15042         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15043          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15044          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15045          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15046          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15047          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15048       Inverted = true;
15049       Cond = Cond.getOperand(0);
15050     } else {
15051       SDValue NewCond = LowerSETCC(Cond, DAG);
15052       if (NewCond.getNode())
15053         Cond = NewCond;
15054     }
15055   }
15056 #if 0
15057   // FIXME: LowerXALUO doesn't handle these!!
15058   else if (Cond.getOpcode() == X86ISD::ADD  ||
15059            Cond.getOpcode() == X86ISD::SUB  ||
15060            Cond.getOpcode() == X86ISD::SMUL ||
15061            Cond.getOpcode() == X86ISD::UMUL)
15062     Cond = LowerXALUO(Cond, DAG);
15063 #endif
15064
15065   // Look pass (and (setcc_carry (cmp ...)), 1).
15066   if (Cond.getOpcode() == ISD::AND &&
15067       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15068     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15069     if (C && C->getAPIntValue() == 1)
15070       Cond = Cond.getOperand(0);
15071   }
15072
15073   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15074   // setting operand in place of the X86ISD::SETCC.
15075   unsigned CondOpcode = Cond.getOpcode();
15076   if (CondOpcode == X86ISD::SETCC ||
15077       CondOpcode == X86ISD::SETCC_CARRY) {
15078     CC = Cond.getOperand(0);
15079
15080     SDValue Cmp = Cond.getOperand(1);
15081     unsigned Opc = Cmp.getOpcode();
15082     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15083     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15084       Cond = Cmp;
15085       addTest = false;
15086     } else {
15087       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15088       default: break;
15089       case X86::COND_O:
15090       case X86::COND_B:
15091         // These can only come from an arithmetic instruction with overflow,
15092         // e.g. SADDO, UADDO.
15093         Cond = Cond.getNode()->getOperand(1);
15094         addTest = false;
15095         break;
15096       }
15097     }
15098   }
15099   CondOpcode = Cond.getOpcode();
15100   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15101       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15102       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15103        Cond.getOperand(0).getValueType() != MVT::i8)) {
15104     SDValue LHS = Cond.getOperand(0);
15105     SDValue RHS = Cond.getOperand(1);
15106     unsigned X86Opcode;
15107     unsigned X86Cond;
15108     SDVTList VTs;
15109     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15110     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15111     // X86ISD::INC).
15112     switch (CondOpcode) {
15113     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15114     case ISD::SADDO:
15115       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15116         if (C->isOne()) {
15117           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15118           break;
15119         }
15120       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15121     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15122     case ISD::SSUBO:
15123       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15124         if (C->isOne()) {
15125           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15126           break;
15127         }
15128       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15129     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15130     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15131     default: llvm_unreachable("unexpected overflowing operator");
15132     }
15133     if (Inverted)
15134       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15135     if (CondOpcode == ISD::UMULO)
15136       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15137                           MVT::i32);
15138     else
15139       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15140
15141     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15142
15143     if (CondOpcode == ISD::UMULO)
15144       Cond = X86Op.getValue(2);
15145     else
15146       Cond = X86Op.getValue(1);
15147
15148     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15149     addTest = false;
15150   } else {
15151     unsigned CondOpc;
15152     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15153       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15154       if (CondOpc == ISD::OR) {
15155         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15156         // two branches instead of an explicit OR instruction with a
15157         // separate test.
15158         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15159             isX86LogicalCmp(Cmp)) {
15160           CC = Cond.getOperand(0).getOperand(0);
15161           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15162                               Chain, Dest, CC, Cmp);
15163           CC = Cond.getOperand(1).getOperand(0);
15164           Cond = Cmp;
15165           addTest = false;
15166         }
15167       } else { // ISD::AND
15168         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15169         // two branches instead of an explicit AND instruction with a
15170         // separate test. However, we only do this if this block doesn't
15171         // have a fall-through edge, because this requires an explicit
15172         // jmp when the condition is false.
15173         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15174             isX86LogicalCmp(Cmp) &&
15175             Op.getNode()->hasOneUse()) {
15176           X86::CondCode CCode =
15177             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15178           CCode = X86::GetOppositeBranchCondition(CCode);
15179           CC = DAG.getConstant(CCode, dl, MVT::i8);
15180           SDNode *User = *Op.getNode()->use_begin();
15181           // Look for an unconditional branch following this conditional branch.
15182           // We need this because we need to reverse the successors in order
15183           // to implement FCMP_OEQ.
15184           if (User->getOpcode() == ISD::BR) {
15185             SDValue FalseBB = User->getOperand(1);
15186             SDNode *NewBR =
15187               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15188             assert(NewBR == User);
15189             (void)NewBR;
15190             Dest = FalseBB;
15191
15192             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15193                                 Chain, Dest, CC, Cmp);
15194             X86::CondCode CCode =
15195               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15196             CCode = X86::GetOppositeBranchCondition(CCode);
15197             CC = DAG.getConstant(CCode, dl, MVT::i8);
15198             Cond = Cmp;
15199             addTest = false;
15200           }
15201         }
15202       }
15203     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15204       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15205       // It should be transformed during dag combiner except when the condition
15206       // is set by a arithmetics with overflow node.
15207       X86::CondCode CCode =
15208         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15209       CCode = X86::GetOppositeBranchCondition(CCode);
15210       CC = DAG.getConstant(CCode, dl, MVT::i8);
15211       Cond = Cond.getOperand(0).getOperand(1);
15212       addTest = false;
15213     } else if (Cond.getOpcode() == ISD::SETCC &&
15214                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15215       // For FCMP_OEQ, we can emit
15216       // two branches instead of an explicit AND instruction with a
15217       // separate test. However, we only do this if this block doesn't
15218       // have a fall-through edge, because this requires an explicit
15219       // jmp when the condition is false.
15220       if (Op.getNode()->hasOneUse()) {
15221         SDNode *User = *Op.getNode()->use_begin();
15222         // Look for an unconditional branch following this conditional branch.
15223         // We need this because we need to reverse the successors in order
15224         // to implement FCMP_OEQ.
15225         if (User->getOpcode() == ISD::BR) {
15226           SDValue FalseBB = User->getOperand(1);
15227           SDNode *NewBR =
15228             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15229           assert(NewBR == User);
15230           (void)NewBR;
15231           Dest = FalseBB;
15232
15233           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15234                                     Cond.getOperand(0), Cond.getOperand(1));
15235           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15236           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15237           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15238                               Chain, Dest, CC, Cmp);
15239           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15240           Cond = Cmp;
15241           addTest = false;
15242         }
15243       }
15244     } else if (Cond.getOpcode() == ISD::SETCC &&
15245                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15246       // For FCMP_UNE, we can emit
15247       // two branches instead of an explicit AND instruction with a
15248       // separate test. However, we only do this if this block doesn't
15249       // have a fall-through edge, because this requires an explicit
15250       // jmp when the condition is false.
15251       if (Op.getNode()->hasOneUse()) {
15252         SDNode *User = *Op.getNode()->use_begin();
15253         // Look for an unconditional branch following this conditional branch.
15254         // We need this because we need to reverse the successors in order
15255         // to implement FCMP_UNE.
15256         if (User->getOpcode() == ISD::BR) {
15257           SDValue FalseBB = User->getOperand(1);
15258           SDNode *NewBR =
15259             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15260           assert(NewBR == User);
15261           (void)NewBR;
15262
15263           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15264                                     Cond.getOperand(0), Cond.getOperand(1));
15265           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15266           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15267           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15268                               Chain, Dest, CC, Cmp);
15269           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15270           Cond = Cmp;
15271           addTest = false;
15272           Dest = FalseBB;
15273         }
15274       }
15275     }
15276   }
15277
15278   if (addTest) {
15279     // Look pass the truncate if the high bits are known zero.
15280     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15281         Cond = Cond.getOperand(0);
15282
15283     // We know the result of AND is compared against zero. Try to match
15284     // it to BT.
15285     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15286       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15287       if (NewSetCC.getNode()) {
15288         CC = NewSetCC.getOperand(0);
15289         Cond = NewSetCC.getOperand(1);
15290         addTest = false;
15291       }
15292     }
15293   }
15294
15295   if (addTest) {
15296     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15297     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15298     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15299   }
15300   Cond = ConvertCmpIfNecessary(Cond, DAG);
15301   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15302                      Chain, Dest, CC, Cond);
15303 }
15304
15305 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15306 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15307 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15308 // that the guard pages used by the OS virtual memory manager are allocated in
15309 // correct sequence.
15310 SDValue
15311 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15312                                            SelectionDAG &DAG) const {
15313   MachineFunction &MF = DAG.getMachineFunction();
15314   bool SplitStack = MF.shouldSplitStack();
15315   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15316                SplitStack;
15317   SDLoc dl(Op);
15318
15319   if (!Lower) {
15320     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15321     SDNode* Node = Op.getNode();
15322
15323     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15324     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15325         " not tell us which reg is the stack pointer!");
15326     EVT VT = Node->getValueType(0);
15327     SDValue Tmp1 = SDValue(Node, 0);
15328     SDValue Tmp2 = SDValue(Node, 1);
15329     SDValue Tmp3 = Node->getOperand(2);
15330     SDValue Chain = Tmp1.getOperand(0);
15331
15332     // Chain the dynamic stack allocation so that it doesn't modify the stack
15333     // pointer when other instructions are using the stack.
15334     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15335         SDLoc(Node));
15336
15337     SDValue Size = Tmp2.getOperand(1);
15338     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15339     Chain = SP.getValue(1);
15340     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15341     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15342     unsigned StackAlign = TFI.getStackAlignment();
15343     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15344     if (Align > StackAlign)
15345       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15346           DAG.getConstant(-(uint64_t)Align, dl, VT));
15347     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15348
15349     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15350         DAG.getIntPtrConstant(0, dl, true), SDValue(),
15351         SDLoc(Node));
15352
15353     SDValue Ops[2] = { Tmp1, Tmp2 };
15354     return DAG.getMergeValues(Ops, dl);
15355   }
15356
15357   // Get the inputs.
15358   SDValue Chain = Op.getOperand(0);
15359   SDValue Size  = Op.getOperand(1);
15360   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15361   EVT VT = Op.getNode()->getValueType(0);
15362
15363   bool Is64Bit = Subtarget->is64Bit();
15364   MVT SPTy = getPointerTy(DAG.getDataLayout());
15365
15366   if (SplitStack) {
15367     MachineRegisterInfo &MRI = MF.getRegInfo();
15368
15369     if (Is64Bit) {
15370       // The 64 bit implementation of segmented stacks needs to clobber both r10
15371       // r11. This makes it impossible to use it along with nested parameters.
15372       const Function *F = MF.getFunction();
15373
15374       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15375            I != E; ++I)
15376         if (I->hasNestAttr())
15377           report_fatal_error("Cannot use segmented stacks with functions that "
15378                              "have nested arguments.");
15379     }
15380
15381     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15382     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15383     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15384     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15385                                 DAG.getRegister(Vreg, SPTy));
15386     SDValue Ops1[2] = { Value, Chain };
15387     return DAG.getMergeValues(Ops1, dl);
15388   } else {
15389     SDValue Flag;
15390     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15391
15392     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15393     Flag = Chain.getValue(1);
15394     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15395
15396     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15397
15398     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15399     unsigned SPReg = RegInfo->getStackRegister();
15400     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15401     Chain = SP.getValue(1);
15402
15403     if (Align) {
15404       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15405                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15406       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15407     }
15408
15409     SDValue Ops1[2] = { SP, Chain };
15410     return DAG.getMergeValues(Ops1, dl);
15411   }
15412 }
15413
15414 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15415   MachineFunction &MF = DAG.getMachineFunction();
15416   auto PtrVT = getPointerTy(MF.getDataLayout());
15417   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15418
15419   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15420   SDLoc DL(Op);
15421
15422   if (!Subtarget->is64Bit() ||
15423       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15424     // vastart just stores the address of the VarArgsFrameIndex slot into the
15425     // memory location argument.
15426     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15427     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15428                         MachinePointerInfo(SV), false, false, 0);
15429   }
15430
15431   // __va_list_tag:
15432   //   gp_offset         (0 - 6 * 8)
15433   //   fp_offset         (48 - 48 + 8 * 16)
15434   //   overflow_arg_area (point to parameters coming in memory).
15435   //   reg_save_area
15436   SmallVector<SDValue, 8> MemOps;
15437   SDValue FIN = Op.getOperand(1);
15438   // Store gp_offset
15439   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15440                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15441                                                DL, MVT::i32),
15442                                FIN, MachinePointerInfo(SV), false, false, 0);
15443   MemOps.push_back(Store);
15444
15445   // Store fp_offset
15446   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15447   Store = DAG.getStore(Op.getOperand(0), DL,
15448                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15449                                        MVT::i32),
15450                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15451   MemOps.push_back(Store);
15452
15453   // Store ptr to overflow_arg_area
15454   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15455   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15456   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15457                        MachinePointerInfo(SV, 8),
15458                        false, false, 0);
15459   MemOps.push_back(Store);
15460
15461   // Store ptr to reg_save_area.
15462   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15463       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15464   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15465   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15466       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15467   MemOps.push_back(Store);
15468   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15469 }
15470
15471 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15472   assert(Subtarget->is64Bit() &&
15473          "LowerVAARG only handles 64-bit va_arg!");
15474   assert(Op.getNode()->getNumOperands() == 4);
15475
15476   MachineFunction &MF = DAG.getMachineFunction();
15477   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15478     // The Win64 ABI uses char* instead of a structure.
15479     return DAG.expandVAArg(Op.getNode());
15480
15481   SDValue Chain = Op.getOperand(0);
15482   SDValue SrcPtr = Op.getOperand(1);
15483   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15484   unsigned Align = Op.getConstantOperandVal(3);
15485   SDLoc dl(Op);
15486
15487   EVT ArgVT = Op.getNode()->getValueType(0);
15488   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15489   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15490   uint8_t ArgMode;
15491
15492   // Decide which area this value should be read from.
15493   // TODO: Implement the AMD64 ABI in its entirety. This simple
15494   // selection mechanism works only for the basic types.
15495   if (ArgVT == MVT::f80) {
15496     llvm_unreachable("va_arg for f80 not yet implemented");
15497   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15498     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15499   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15500     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15501   } else {
15502     llvm_unreachable("Unhandled argument type in LowerVAARG");
15503   }
15504
15505   if (ArgMode == 2) {
15506     // Sanity Check: Make sure using fp_offset makes sense.
15507     assert(!Subtarget->useSoftFloat() &&
15508            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15509            Subtarget->hasSSE1());
15510   }
15511
15512   // Insert VAARG_64 node into the DAG
15513   // VAARG_64 returns two values: Variable Argument Address, Chain
15514   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15515                        DAG.getConstant(ArgMode, dl, MVT::i8),
15516                        DAG.getConstant(Align, dl, MVT::i32)};
15517   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15518   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15519                                           VTs, InstOps, MVT::i64,
15520                                           MachinePointerInfo(SV),
15521                                           /*Align=*/0,
15522                                           /*Volatile=*/false,
15523                                           /*ReadMem=*/true,
15524                                           /*WriteMem=*/true);
15525   Chain = VAARG.getValue(1);
15526
15527   // Load the next argument and return it
15528   return DAG.getLoad(ArgVT, dl,
15529                      Chain,
15530                      VAARG,
15531                      MachinePointerInfo(),
15532                      false, false, false, 0);
15533 }
15534
15535 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15536                            SelectionDAG &DAG) {
15537   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15538   // where a va_list is still an i8*.
15539   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15540   if (Subtarget->isCallingConvWin64(
15541         DAG.getMachineFunction().getFunction()->getCallingConv()))
15542     // Probably a Win64 va_copy.
15543     return DAG.expandVACopy(Op.getNode());
15544
15545   SDValue Chain = Op.getOperand(0);
15546   SDValue DstPtr = Op.getOperand(1);
15547   SDValue SrcPtr = Op.getOperand(2);
15548   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15549   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15550   SDLoc DL(Op);
15551
15552   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15553                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15554                        false, false,
15555                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15556 }
15557
15558 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15559 // amount is a constant. Takes immediate version of shift as input.
15560 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15561                                           SDValue SrcOp, uint64_t ShiftAmt,
15562                                           SelectionDAG &DAG) {
15563   MVT ElementType = VT.getVectorElementType();
15564
15565   // Fold this packed shift into its first operand if ShiftAmt is 0.
15566   if (ShiftAmt == 0)
15567     return SrcOp;
15568
15569   // Check for ShiftAmt >= element width
15570   if (ShiftAmt >= ElementType.getSizeInBits()) {
15571     if (Opc == X86ISD::VSRAI)
15572       ShiftAmt = ElementType.getSizeInBits() - 1;
15573     else
15574       return DAG.getConstant(0, dl, VT);
15575   }
15576
15577   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15578          && "Unknown target vector shift-by-constant node");
15579
15580   // Fold this packed vector shift into a build vector if SrcOp is a
15581   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15582   if (VT == SrcOp.getSimpleValueType() &&
15583       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15584     SmallVector<SDValue, 8> Elts;
15585     unsigned NumElts = SrcOp->getNumOperands();
15586     ConstantSDNode *ND;
15587
15588     switch(Opc) {
15589     default: llvm_unreachable(nullptr);
15590     case X86ISD::VSHLI:
15591       for (unsigned i=0; i!=NumElts; ++i) {
15592         SDValue CurrentOp = SrcOp->getOperand(i);
15593         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15594           Elts.push_back(CurrentOp);
15595           continue;
15596         }
15597         ND = cast<ConstantSDNode>(CurrentOp);
15598         const APInt &C = ND->getAPIntValue();
15599         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15600       }
15601       break;
15602     case X86ISD::VSRLI:
15603       for (unsigned i=0; i!=NumElts; ++i) {
15604         SDValue CurrentOp = SrcOp->getOperand(i);
15605         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15606           Elts.push_back(CurrentOp);
15607           continue;
15608         }
15609         ND = cast<ConstantSDNode>(CurrentOp);
15610         const APInt &C = ND->getAPIntValue();
15611         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15612       }
15613       break;
15614     case X86ISD::VSRAI:
15615       for (unsigned i=0; i!=NumElts; ++i) {
15616         SDValue CurrentOp = SrcOp->getOperand(i);
15617         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15618           Elts.push_back(CurrentOp);
15619           continue;
15620         }
15621         ND = cast<ConstantSDNode>(CurrentOp);
15622         const APInt &C = ND->getAPIntValue();
15623         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15624       }
15625       break;
15626     }
15627
15628     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15629   }
15630
15631   return DAG.getNode(Opc, dl, VT, SrcOp,
15632                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15633 }
15634
15635 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15636 // may or may not be a constant. Takes immediate version of shift as input.
15637 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15638                                    SDValue SrcOp, SDValue ShAmt,
15639                                    SelectionDAG &DAG) {
15640   MVT SVT = ShAmt.getSimpleValueType();
15641   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15642
15643   // Catch shift-by-constant.
15644   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15645     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15646                                       CShAmt->getZExtValue(), DAG);
15647
15648   // Change opcode to non-immediate version
15649   switch (Opc) {
15650     default: llvm_unreachable("Unknown target vector shift node");
15651     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15652     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15653     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15654   }
15655
15656   const X86Subtarget &Subtarget =
15657       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15658   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15659       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15660     // Let the shuffle legalizer expand this shift amount node.
15661     SDValue Op0 = ShAmt.getOperand(0);
15662     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15663     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15664   } else {
15665     // Need to build a vector containing shift amount.
15666     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15667     SmallVector<SDValue, 4> ShOps;
15668     ShOps.push_back(ShAmt);
15669     if (SVT == MVT::i32) {
15670       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15671       ShOps.push_back(DAG.getUNDEF(SVT));
15672     }
15673     ShOps.push_back(DAG.getUNDEF(SVT));
15674
15675     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15676     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15677   }
15678
15679   // The return type has to be a 128-bit type with the same element
15680   // type as the input type.
15681   MVT EltVT = VT.getVectorElementType();
15682   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15683
15684   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15685   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15686 }
15687
15688 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15689 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15690 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15691 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15692                                     SDValue PreservedSrc,
15693                                     const X86Subtarget *Subtarget,
15694                                     SelectionDAG &DAG) {
15695     EVT VT = Op.getValueType();
15696     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15697                                   MVT::i1, VT.getVectorNumElements());
15698     SDValue VMask = SDValue();
15699     unsigned OpcodeSelect = ISD::VSELECT;
15700     SDLoc dl(Op);
15701
15702     assert(MaskVT.isSimple() && "invalid mask type");
15703
15704     if (isAllOnes(Mask))
15705       return Op;
15706
15707     if (MaskVT.bitsGT(Mask.getValueType())) {
15708       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15709                                          MaskVT.getSizeInBits());
15710       VMask = DAG.getBitcast(MaskVT,
15711                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15712     } else {
15713       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15714                                        Mask.getValueType().getSizeInBits());
15715       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15716       // are extracted by EXTRACT_SUBVECTOR.
15717       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15718                           DAG.getBitcast(BitcastVT, Mask),
15719                           DAG.getIntPtrConstant(0, dl));
15720     }
15721
15722     switch (Op.getOpcode()) {
15723       default: break;
15724       case X86ISD::PCMPEQM:
15725       case X86ISD::PCMPGTM:
15726       case X86ISD::CMPM:
15727       case X86ISD::CMPMU:
15728         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15729       case X86ISD::VTRUNC:
15730       case X86ISD::VTRUNCS:
15731       case X86ISD::VTRUNCUS:
15732         // We can't use ISD::VSELECT here because it is not always "Legal"
15733         // for the destination type. For example vpmovqb require only AVX512
15734         // and vselect that can operate on byte element type require BWI
15735         OpcodeSelect = X86ISD::SELECT;
15736         break;
15737     }
15738     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15739       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15740     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15741 }
15742
15743 /// \brief Creates an SDNode for a predicated scalar operation.
15744 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15745 /// The mask is coming as MVT::i8 and it should be truncated
15746 /// to MVT::i1 while lowering masking intrinsics.
15747 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15748 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15749 /// for a scalar instruction.
15750 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15751                                     SDValue PreservedSrc,
15752                                     const X86Subtarget *Subtarget,
15753                                     SelectionDAG &DAG) {
15754     if (isAllOnes(Mask))
15755       return Op;
15756
15757     EVT VT = Op.getValueType();
15758     SDLoc dl(Op);
15759     // The mask should be of type MVT::i1
15760     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15761
15762     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15763       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15764     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15765 }
15766
15767 static int getSEHRegistrationNodeSize(const Function *Fn) {
15768   if (!Fn->hasPersonalityFn())
15769     report_fatal_error(
15770         "querying registration node size for function without personality");
15771   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15772   // WinEHStatePass for the full struct definition.
15773   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15774   case EHPersonality::MSVC_X86SEH: return 24;
15775   case EHPersonality::MSVC_CXX: return 16;
15776   default: break;
15777   }
15778   report_fatal_error("can only recover FP for MSVC EH personality functions");
15779 }
15780
15781 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15782 /// function or when returning to a parent frame after catching an exception, we
15783 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15784 /// Here's the math:
15785 ///   RegNodeBase = EntryEBP - RegNodeSize
15786 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15787 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15788 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15789 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15790                                    SDValue EntryEBP) {
15791   MachineFunction &MF = DAG.getMachineFunction();
15792   SDLoc dl;
15793
15794   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15795   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15796
15797   // It's possible that the parent function no longer has a personality function
15798   // if the exceptional code was optimized away, in which case we just return
15799   // the incoming EBP.
15800   if (!Fn->hasPersonalityFn())
15801     return EntryEBP;
15802
15803   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15804
15805   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15806   // registration.
15807   MCSymbol *OffsetSym =
15808       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15809           GlobalValue::getRealLinkageName(Fn->getName()));
15810   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15811   SDValue RegNodeFrameOffset =
15812       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15813
15814   // RegNodeBase = EntryEBP - RegNodeSize
15815   // ParentFP = RegNodeBase - RegNodeFrameOffset
15816   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15817                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15818   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15819 }
15820
15821 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15822                                        SelectionDAG &DAG) {
15823   SDLoc dl(Op);
15824   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15825   EVT VT = Op.getValueType();
15826   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15827   if (IntrData) {
15828     switch(IntrData->Type) {
15829     case INTR_TYPE_1OP:
15830       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15831     case INTR_TYPE_2OP:
15832       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15833         Op.getOperand(2));
15834     case INTR_TYPE_2OP_IMM8:
15835       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15836                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
15837     case INTR_TYPE_3OP:
15838       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15839         Op.getOperand(2), Op.getOperand(3));
15840     case INTR_TYPE_4OP:
15841       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15842         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15843     case INTR_TYPE_1OP_MASK_RM: {
15844       SDValue Src = Op.getOperand(1);
15845       SDValue PassThru = Op.getOperand(2);
15846       SDValue Mask = Op.getOperand(3);
15847       SDValue RoundingMode;
15848       // We allways add rounding mode to the Node.
15849       // If the rounding mode is not specified, we add the
15850       // "current direction" mode.
15851       if (Op.getNumOperands() == 4)
15852         RoundingMode =
15853           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15854       else
15855         RoundingMode = Op.getOperand(4);
15856       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15857       if (IntrWithRoundingModeOpcode != 0)
15858         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15859             X86::STATIC_ROUNDING::CUR_DIRECTION)
15860           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15861                                       dl, Op.getValueType(), Src, RoundingMode),
15862                                       Mask, PassThru, Subtarget, DAG);
15863       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15864                                               RoundingMode),
15865                                   Mask, PassThru, Subtarget, DAG);
15866     }
15867     case INTR_TYPE_1OP_MASK: {
15868       SDValue Src = Op.getOperand(1);
15869       SDValue PassThru = Op.getOperand(2);
15870       SDValue Mask = Op.getOperand(3);
15871       // We add rounding mode to the Node when
15872       //   - RM Opcode is specified and
15873       //   - RM is not "current direction".
15874       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15875       if (IntrWithRoundingModeOpcode != 0) {
15876         SDValue Rnd = Op.getOperand(4);
15877         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15878         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15879           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15880                                       dl, Op.getValueType(),
15881                                       Src, Rnd),
15882                                       Mask, PassThru, Subtarget, DAG);
15883         }
15884       }
15885       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15886                                   Mask, PassThru, Subtarget, DAG);
15887     }
15888     case INTR_TYPE_SCALAR_MASK_RM: {
15889       SDValue Src1 = Op.getOperand(1);
15890       SDValue Src2 = Op.getOperand(2);
15891       SDValue Src0 = Op.getOperand(3);
15892       SDValue Mask = Op.getOperand(4);
15893       // There are 2 kinds of intrinsics in this group:
15894       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15895       // (2) With rounding mode and sae - 7 operands.
15896       if (Op.getNumOperands() == 6) {
15897         SDValue Sae  = Op.getOperand(5);
15898         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15899         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15900                                                 Sae),
15901                                     Mask, Src0, Subtarget, DAG);
15902       }
15903       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15904       SDValue RoundingMode  = Op.getOperand(5);
15905       SDValue Sae  = Op.getOperand(6);
15906       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15907                                               RoundingMode, Sae),
15908                                   Mask, Src0, Subtarget, DAG);
15909     }
15910     case INTR_TYPE_2OP_MASK: {
15911       SDValue Src1 = Op.getOperand(1);
15912       SDValue Src2 = Op.getOperand(2);
15913       SDValue PassThru = Op.getOperand(3);
15914       SDValue Mask = Op.getOperand(4);
15915       // We specify 2 possible opcodes for intrinsics with rounding modes.
15916       // First, we check if the intrinsic may have non-default rounding mode,
15917       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15918       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15919       if (IntrWithRoundingModeOpcode != 0) {
15920         SDValue Rnd = Op.getOperand(5);
15921         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15922         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15923           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15924                                       dl, Op.getValueType(),
15925                                       Src1, Src2, Rnd),
15926                                       Mask, PassThru, Subtarget, DAG);
15927         }
15928       }
15929       // TODO: Intrinsics should have fast-math-flags to propagate.
15930       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
15931                                   Mask, PassThru, Subtarget, DAG);
15932     }
15933     case INTR_TYPE_2OP_MASK_RM: {
15934       SDValue Src1 = Op.getOperand(1);
15935       SDValue Src2 = Op.getOperand(2);
15936       SDValue PassThru = Op.getOperand(3);
15937       SDValue Mask = Op.getOperand(4);
15938       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15939       // First, we check if the intrinsic have rounding mode (6 operands),
15940       // if not, we set rounding mode to "current".
15941       SDValue Rnd;
15942       if (Op.getNumOperands() == 6)
15943         Rnd = Op.getOperand(5);
15944       else
15945         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15946       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15947                                               Src1, Src2, Rnd),
15948                                   Mask, PassThru, Subtarget, DAG);
15949     }
15950     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
15951       SDValue Src1 = Op.getOperand(1);
15952       SDValue Src2 = Op.getOperand(2);
15953       SDValue Src3 = Op.getOperand(3);
15954       SDValue PassThru = Op.getOperand(4);
15955       SDValue Mask = Op.getOperand(5);
15956       SDValue Sae  = Op.getOperand(6);
15957
15958       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
15959                                               Src2, Src3, Sae),
15960                                   Mask, PassThru, Subtarget, DAG);
15961     }
15962     case INTR_TYPE_3OP_MASK_RM: {
15963       SDValue Src1 = Op.getOperand(1);
15964       SDValue Src2 = Op.getOperand(2);
15965       SDValue Imm = Op.getOperand(3);
15966       SDValue PassThru = Op.getOperand(4);
15967       SDValue Mask = Op.getOperand(5);
15968       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15969       // First, we check if the intrinsic have rounding mode (7 operands),
15970       // if not, we set rounding mode to "current".
15971       SDValue Rnd;
15972       if (Op.getNumOperands() == 7)
15973         Rnd = Op.getOperand(6);
15974       else
15975         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15976       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15977         Src1, Src2, Imm, Rnd),
15978         Mask, PassThru, Subtarget, DAG);
15979     }
15980     case INTR_TYPE_3OP_IMM8_MASK:
15981     case INTR_TYPE_3OP_MASK:
15982     case INSERT_SUBVEC: {
15983       SDValue Src1 = Op.getOperand(1);
15984       SDValue Src2 = Op.getOperand(2);
15985       SDValue Src3 = Op.getOperand(3);
15986       SDValue PassThru = Op.getOperand(4);
15987       SDValue Mask = Op.getOperand(5);
15988
15989       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
15990         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
15991       else if (IntrData->Type == INSERT_SUBVEC) {
15992         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
15993         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
15994         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
15995         Imm *= Src2.getValueType().getVectorNumElements();
15996         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
15997       }
15998
15999       // We specify 2 possible opcodes for intrinsics with rounding modes.
16000       // First, we check if the intrinsic may have non-default rounding mode,
16001       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16002       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16003       if (IntrWithRoundingModeOpcode != 0) {
16004         SDValue Rnd = Op.getOperand(6);
16005         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16006         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16007           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16008                                       dl, Op.getValueType(),
16009                                       Src1, Src2, Src3, Rnd),
16010                                       Mask, PassThru, Subtarget, DAG);
16011         }
16012       }
16013       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16014                                               Src1, Src2, Src3),
16015                                   Mask, PassThru, Subtarget, DAG);
16016     }
16017     case VPERM_3OP_MASKZ:
16018     case VPERM_3OP_MASK:
16019     case FMA_OP_MASK3:
16020     case FMA_OP_MASKZ:
16021     case FMA_OP_MASK: {
16022       SDValue Src1 = Op.getOperand(1);
16023       SDValue Src2 = Op.getOperand(2);
16024       SDValue Src3 = Op.getOperand(3);
16025       SDValue Mask = Op.getOperand(4);
16026       EVT VT = Op.getValueType();
16027       SDValue PassThru = SDValue();
16028
16029       // set PassThru element
16030       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
16031         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16032       else if (IntrData->Type == FMA_OP_MASK3)
16033         PassThru = Src3;
16034       else
16035         PassThru = Src1;
16036
16037       // We specify 2 possible opcodes for intrinsics with rounding modes.
16038       // First, we check if the intrinsic may have non-default rounding mode,
16039       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16040       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16041       if (IntrWithRoundingModeOpcode != 0) {
16042         SDValue Rnd = Op.getOperand(5);
16043         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16044             X86::STATIC_ROUNDING::CUR_DIRECTION)
16045           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16046                                                   dl, Op.getValueType(),
16047                                                   Src1, Src2, Src3, Rnd),
16048                                       Mask, PassThru, Subtarget, DAG);
16049       }
16050       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16051                                               dl, Op.getValueType(),
16052                                               Src1, Src2, Src3),
16053                                   Mask, PassThru, Subtarget, DAG);
16054     }
16055     case CMP_MASK:
16056     case CMP_MASK_CC: {
16057       // Comparison intrinsics with masks.
16058       // Example of transformation:
16059       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16060       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16061       // (i8 (bitcast
16062       //   (v8i1 (insert_subvector undef,
16063       //           (v2i1 (and (PCMPEQM %a, %b),
16064       //                      (extract_subvector
16065       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16066       EVT VT = Op.getOperand(1).getValueType();
16067       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16068                                     VT.getVectorNumElements());
16069       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16070       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16071                                        Mask.getValueType().getSizeInBits());
16072       SDValue Cmp;
16073       if (IntrData->Type == CMP_MASK_CC) {
16074         SDValue CC = Op.getOperand(3);
16075         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16076         // We specify 2 possible opcodes for intrinsics with rounding modes.
16077         // First, we check if the intrinsic may have non-default rounding mode,
16078         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16079         if (IntrData->Opc1 != 0) {
16080           SDValue Rnd = Op.getOperand(5);
16081           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16082               X86::STATIC_ROUNDING::CUR_DIRECTION)
16083             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16084                               Op.getOperand(2), CC, Rnd);
16085         }
16086         //default rounding mode
16087         if(!Cmp.getNode())
16088             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16089                               Op.getOperand(2), CC);
16090
16091       } else {
16092         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16093         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16094                           Op.getOperand(2));
16095       }
16096       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16097                                              DAG.getTargetConstant(0, dl,
16098                                                                    MaskVT),
16099                                              Subtarget, DAG);
16100       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16101                                 DAG.getUNDEF(BitcastVT), CmpMask,
16102                                 DAG.getIntPtrConstant(0, dl));
16103       return DAG.getBitcast(Op.getValueType(), Res);
16104     }
16105     case COMI: { // Comparison intrinsics
16106       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16107       SDValue LHS = Op.getOperand(1);
16108       SDValue RHS = Op.getOperand(2);
16109       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16110       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16111       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16112       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16113                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16114       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16115     }
16116     case VSHIFT:
16117       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16118                                  Op.getOperand(1), Op.getOperand(2), DAG);
16119     case VSHIFT_MASK:
16120       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16121                                                       Op.getSimpleValueType(),
16122                                                       Op.getOperand(1),
16123                                                       Op.getOperand(2), DAG),
16124                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16125                                   DAG);
16126     case COMPRESS_EXPAND_IN_REG: {
16127       SDValue Mask = Op.getOperand(3);
16128       SDValue DataToCompress = Op.getOperand(1);
16129       SDValue PassThru = Op.getOperand(2);
16130       if (isAllOnes(Mask)) // return data as is
16131         return Op.getOperand(1);
16132
16133       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16134                                               DataToCompress),
16135                                   Mask, PassThru, Subtarget, DAG);
16136     }
16137     case BLEND: {
16138       SDValue Mask = Op.getOperand(3);
16139       EVT VT = Op.getValueType();
16140       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16141                                     VT.getVectorNumElements());
16142       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16143                                        Mask.getValueType().getSizeInBits());
16144       SDLoc dl(Op);
16145       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16146                                   DAG.getBitcast(BitcastVT, Mask),
16147                                   DAG.getIntPtrConstant(0, dl));
16148       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16149                          Op.getOperand(2));
16150     }
16151     default:
16152       break;
16153     }
16154   }
16155
16156   switch (IntNo) {
16157   default: return SDValue();    // Don't custom lower most intrinsics.
16158
16159   case Intrinsic::x86_avx2_permd:
16160   case Intrinsic::x86_avx2_permps:
16161     // Operands intentionally swapped. Mask is last operand to intrinsic,
16162     // but second operand for node/instruction.
16163     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16164                        Op.getOperand(2), Op.getOperand(1));
16165
16166   // ptest and testp intrinsics. The intrinsic these come from are designed to
16167   // return an integer value, not just an instruction so lower it to the ptest
16168   // or testp pattern and a setcc for the result.
16169   case Intrinsic::x86_sse41_ptestz:
16170   case Intrinsic::x86_sse41_ptestc:
16171   case Intrinsic::x86_sse41_ptestnzc:
16172   case Intrinsic::x86_avx_ptestz_256:
16173   case Intrinsic::x86_avx_ptestc_256:
16174   case Intrinsic::x86_avx_ptestnzc_256:
16175   case Intrinsic::x86_avx_vtestz_ps:
16176   case Intrinsic::x86_avx_vtestc_ps:
16177   case Intrinsic::x86_avx_vtestnzc_ps:
16178   case Intrinsic::x86_avx_vtestz_pd:
16179   case Intrinsic::x86_avx_vtestc_pd:
16180   case Intrinsic::x86_avx_vtestnzc_pd:
16181   case Intrinsic::x86_avx_vtestz_ps_256:
16182   case Intrinsic::x86_avx_vtestc_ps_256:
16183   case Intrinsic::x86_avx_vtestnzc_ps_256:
16184   case Intrinsic::x86_avx_vtestz_pd_256:
16185   case Intrinsic::x86_avx_vtestc_pd_256:
16186   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16187     bool IsTestPacked = false;
16188     unsigned X86CC;
16189     switch (IntNo) {
16190     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16191     case Intrinsic::x86_avx_vtestz_ps:
16192     case Intrinsic::x86_avx_vtestz_pd:
16193     case Intrinsic::x86_avx_vtestz_ps_256:
16194     case Intrinsic::x86_avx_vtestz_pd_256:
16195       IsTestPacked = true; // Fallthrough
16196     case Intrinsic::x86_sse41_ptestz:
16197     case Intrinsic::x86_avx_ptestz_256:
16198       // ZF = 1
16199       X86CC = X86::COND_E;
16200       break;
16201     case Intrinsic::x86_avx_vtestc_ps:
16202     case Intrinsic::x86_avx_vtestc_pd:
16203     case Intrinsic::x86_avx_vtestc_ps_256:
16204     case Intrinsic::x86_avx_vtestc_pd_256:
16205       IsTestPacked = true; // Fallthrough
16206     case Intrinsic::x86_sse41_ptestc:
16207     case Intrinsic::x86_avx_ptestc_256:
16208       // CF = 1
16209       X86CC = X86::COND_B;
16210       break;
16211     case Intrinsic::x86_avx_vtestnzc_ps:
16212     case Intrinsic::x86_avx_vtestnzc_pd:
16213     case Intrinsic::x86_avx_vtestnzc_ps_256:
16214     case Intrinsic::x86_avx_vtestnzc_pd_256:
16215       IsTestPacked = true; // Fallthrough
16216     case Intrinsic::x86_sse41_ptestnzc:
16217     case Intrinsic::x86_avx_ptestnzc_256:
16218       // ZF and CF = 0
16219       X86CC = X86::COND_A;
16220       break;
16221     }
16222
16223     SDValue LHS = Op.getOperand(1);
16224     SDValue RHS = Op.getOperand(2);
16225     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16226     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16227     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16228     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16229     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16230   }
16231   case Intrinsic::x86_avx512_kortestz_w:
16232   case Intrinsic::x86_avx512_kortestc_w: {
16233     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16234     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16235     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16236     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16237     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16238     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16239     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16240   }
16241
16242   case Intrinsic::x86_sse42_pcmpistria128:
16243   case Intrinsic::x86_sse42_pcmpestria128:
16244   case Intrinsic::x86_sse42_pcmpistric128:
16245   case Intrinsic::x86_sse42_pcmpestric128:
16246   case Intrinsic::x86_sse42_pcmpistrio128:
16247   case Intrinsic::x86_sse42_pcmpestrio128:
16248   case Intrinsic::x86_sse42_pcmpistris128:
16249   case Intrinsic::x86_sse42_pcmpestris128:
16250   case Intrinsic::x86_sse42_pcmpistriz128:
16251   case Intrinsic::x86_sse42_pcmpestriz128: {
16252     unsigned Opcode;
16253     unsigned X86CC;
16254     switch (IntNo) {
16255     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16256     case Intrinsic::x86_sse42_pcmpistria128:
16257       Opcode = X86ISD::PCMPISTRI;
16258       X86CC = X86::COND_A;
16259       break;
16260     case Intrinsic::x86_sse42_pcmpestria128:
16261       Opcode = X86ISD::PCMPESTRI;
16262       X86CC = X86::COND_A;
16263       break;
16264     case Intrinsic::x86_sse42_pcmpistric128:
16265       Opcode = X86ISD::PCMPISTRI;
16266       X86CC = X86::COND_B;
16267       break;
16268     case Intrinsic::x86_sse42_pcmpestric128:
16269       Opcode = X86ISD::PCMPESTRI;
16270       X86CC = X86::COND_B;
16271       break;
16272     case Intrinsic::x86_sse42_pcmpistrio128:
16273       Opcode = X86ISD::PCMPISTRI;
16274       X86CC = X86::COND_O;
16275       break;
16276     case Intrinsic::x86_sse42_pcmpestrio128:
16277       Opcode = X86ISD::PCMPESTRI;
16278       X86CC = X86::COND_O;
16279       break;
16280     case Intrinsic::x86_sse42_pcmpistris128:
16281       Opcode = X86ISD::PCMPISTRI;
16282       X86CC = X86::COND_S;
16283       break;
16284     case Intrinsic::x86_sse42_pcmpestris128:
16285       Opcode = X86ISD::PCMPESTRI;
16286       X86CC = X86::COND_S;
16287       break;
16288     case Intrinsic::x86_sse42_pcmpistriz128:
16289       Opcode = X86ISD::PCMPISTRI;
16290       X86CC = X86::COND_E;
16291       break;
16292     case Intrinsic::x86_sse42_pcmpestriz128:
16293       Opcode = X86ISD::PCMPESTRI;
16294       X86CC = X86::COND_E;
16295       break;
16296     }
16297     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16298     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16299     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16300     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16301                                 DAG.getConstant(X86CC, dl, MVT::i8),
16302                                 SDValue(PCMP.getNode(), 1));
16303     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16304   }
16305
16306   case Intrinsic::x86_sse42_pcmpistri128:
16307   case Intrinsic::x86_sse42_pcmpestri128: {
16308     unsigned Opcode;
16309     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16310       Opcode = X86ISD::PCMPISTRI;
16311     else
16312       Opcode = X86ISD::PCMPESTRI;
16313
16314     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16315     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16316     return DAG.getNode(Opcode, dl, VTs, NewOps);
16317   }
16318
16319   case Intrinsic::x86_seh_lsda: {
16320     // Compute the symbol for the LSDA. We know it'll get emitted later.
16321     MachineFunction &MF = DAG.getMachineFunction();
16322     SDValue Op1 = Op.getOperand(1);
16323     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16324     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16325         GlobalValue::getRealLinkageName(Fn->getName()));
16326
16327     // Generate a simple absolute symbol reference. This intrinsic is only
16328     // supported on 32-bit Windows, which isn't PIC.
16329     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16330     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16331   }
16332
16333   case Intrinsic::x86_seh_recoverfp: {
16334     SDValue FnOp = Op.getOperand(1);
16335     SDValue IncomingFPOp = Op.getOperand(2);
16336     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16337     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16338     if (!Fn)
16339       report_fatal_error(
16340           "llvm.x86.seh.recoverfp must take a function as the first argument");
16341     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16342   }
16343
16344   case Intrinsic::localaddress: {
16345     // Returns one of the stack, base, or frame pointer registers, depending on
16346     // which is used to reference local variables.
16347     MachineFunction &MF = DAG.getMachineFunction();
16348     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16349     unsigned Reg;
16350     if (RegInfo->hasBasePointer(MF))
16351       Reg = RegInfo->getBaseRegister();
16352     else // This function handles the SP or FP case.
16353       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16354     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16355   }
16356   }
16357 }
16358
16359 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16360                               SDValue Src, SDValue Mask, SDValue Base,
16361                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16362                               const X86Subtarget * Subtarget) {
16363   SDLoc dl(Op);
16364   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16365   if (!C)
16366     llvm_unreachable("Invalid scale type");
16367   unsigned ScaleVal = C->getZExtValue();
16368   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16369     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16370
16371   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16372   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16373                              Index.getSimpleValueType().getVectorNumElements());
16374   SDValue MaskInReg;
16375   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16376   if (MaskC)
16377     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16378   else {
16379     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16380                                      Mask.getValueType().getSizeInBits());
16381
16382     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16383     // are extracted by EXTRACT_SUBVECTOR.
16384     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16385                             DAG.getBitcast(BitcastVT, Mask),
16386                             DAG.getIntPtrConstant(0, dl));
16387   }
16388   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16389   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16390   SDValue Segment = DAG.getRegister(0, MVT::i32);
16391   if (Src.getOpcode() == ISD::UNDEF)
16392     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16393   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16394   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16395   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16396   return DAG.getMergeValues(RetOps, dl);
16397 }
16398
16399 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16400                                SDValue Src, SDValue Mask, SDValue Base,
16401                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16402   SDLoc dl(Op);
16403   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16404   if (!C)
16405     llvm_unreachable("Invalid scale type");
16406   unsigned ScaleVal = C->getZExtValue();
16407   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16408     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16409
16410   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16411   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16412   SDValue Segment = DAG.getRegister(0, MVT::i32);
16413   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16414                              Index.getSimpleValueType().getVectorNumElements());
16415   SDValue MaskInReg;
16416   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16417   if (MaskC)
16418     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16419   else {
16420     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16421                                      Mask.getValueType().getSizeInBits());
16422
16423     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16424     // are extracted by EXTRACT_SUBVECTOR.
16425     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16426                             DAG.getBitcast(BitcastVT, Mask),
16427                             DAG.getIntPtrConstant(0, dl));
16428   }
16429   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16430   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16431   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16432   return SDValue(Res, 1);
16433 }
16434
16435 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16436                                SDValue Mask, SDValue Base, SDValue Index,
16437                                SDValue ScaleOp, SDValue Chain) {
16438   SDLoc dl(Op);
16439   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16440   assert(C && "Invalid scale type");
16441   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16442   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16443   SDValue Segment = DAG.getRegister(0, MVT::i32);
16444   EVT MaskVT =
16445     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16446   SDValue MaskInReg;
16447   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16448   if (MaskC)
16449     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16450   else
16451     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16452   //SDVTList VTs = DAG.getVTList(MVT::Other);
16453   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16454   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16455   return SDValue(Res, 0);
16456 }
16457
16458 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16459 // read performance monitor counters (x86_rdpmc).
16460 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16461                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16462                               SmallVectorImpl<SDValue> &Results) {
16463   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16464   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16465   SDValue LO, HI;
16466
16467   // The ECX register is used to select the index of the performance counter
16468   // to read.
16469   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16470                                    N->getOperand(2));
16471   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16472
16473   // Reads the content of a 64-bit performance counter and returns it in the
16474   // registers EDX:EAX.
16475   if (Subtarget->is64Bit()) {
16476     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16477     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16478                             LO.getValue(2));
16479   } else {
16480     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16481     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16482                             LO.getValue(2));
16483   }
16484   Chain = HI.getValue(1);
16485
16486   if (Subtarget->is64Bit()) {
16487     // The EAX register is loaded with the low-order 32 bits. The EDX register
16488     // is loaded with the supported high-order bits of the counter.
16489     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16490                               DAG.getConstant(32, DL, MVT::i8));
16491     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16492     Results.push_back(Chain);
16493     return;
16494   }
16495
16496   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16497   SDValue Ops[] = { LO, HI };
16498   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16499   Results.push_back(Pair);
16500   Results.push_back(Chain);
16501 }
16502
16503 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16504 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16505 // also used to custom lower READCYCLECOUNTER nodes.
16506 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16507                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16508                               SmallVectorImpl<SDValue> &Results) {
16509   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16510   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16511   SDValue LO, HI;
16512
16513   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16514   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16515   // and the EAX register is loaded with the low-order 32 bits.
16516   if (Subtarget->is64Bit()) {
16517     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16518     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16519                             LO.getValue(2));
16520   } else {
16521     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16522     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16523                             LO.getValue(2));
16524   }
16525   SDValue Chain = HI.getValue(1);
16526
16527   if (Opcode == X86ISD::RDTSCP_DAG) {
16528     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16529
16530     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16531     // the ECX register. Add 'ecx' explicitly to the chain.
16532     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16533                                      HI.getValue(2));
16534     // Explicitly store the content of ECX at the location passed in input
16535     // to the 'rdtscp' intrinsic.
16536     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16537                          MachinePointerInfo(), false, false, 0);
16538   }
16539
16540   if (Subtarget->is64Bit()) {
16541     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16542     // the EAX register is loaded with the low-order 32 bits.
16543     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16544                               DAG.getConstant(32, DL, MVT::i8));
16545     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16546     Results.push_back(Chain);
16547     return;
16548   }
16549
16550   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16551   SDValue Ops[] = { LO, HI };
16552   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16553   Results.push_back(Pair);
16554   Results.push_back(Chain);
16555 }
16556
16557 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16558                                      SelectionDAG &DAG) {
16559   SmallVector<SDValue, 2> Results;
16560   SDLoc DL(Op);
16561   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16562                           Results);
16563   return DAG.getMergeValues(Results, DL);
16564 }
16565
16566 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16567                                     SelectionDAG &DAG) {
16568   MachineFunction &MF = DAG.getMachineFunction();
16569   const Function *Fn = MF.getFunction();
16570   SDLoc dl(Op);
16571   SDValue Chain = Op.getOperand(0);
16572
16573   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16574          "using llvm.x86.seh.restoreframe requires a frame pointer");
16575
16576   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16577   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16578
16579   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16580   unsigned FrameReg =
16581       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16582   unsigned SPReg = RegInfo->getStackRegister();
16583   unsigned SlotSize = RegInfo->getSlotSize();
16584
16585   // Get incoming EBP.
16586   SDValue IncomingEBP =
16587       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16588
16589   // SP is saved in the first field of every registration node, so load
16590   // [EBP-RegNodeSize] into SP.
16591   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16592   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16593                                DAG.getConstant(-RegNodeSize, dl, VT));
16594   SDValue NewSP =
16595       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16596                   false, VT.getScalarSizeInBits() / 8);
16597   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16598
16599   if (!RegInfo->needsStackRealignment(MF)) {
16600     // Adjust EBP to point back to the original frame position.
16601     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16602     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16603   } else {
16604     assert(RegInfo->hasBasePointer(MF) &&
16605            "functions with Win32 EH must use frame or base pointer register");
16606
16607     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16608     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16609     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16610
16611     // Reload the spilled EBP value, now that the stack and base pointers are
16612     // set up.
16613     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16614     X86FI->setHasSEHFramePtrSave(true);
16615     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16616     X86FI->setSEHFramePtrSaveIndex(FI);
16617     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16618                                 MachinePointerInfo(), false, false, false,
16619                                 VT.getScalarSizeInBits() / 8);
16620     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16621   }
16622
16623   return Chain;
16624 }
16625
16626 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16627 /// return truncate Store/MaskedStore Node
16628 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16629                                                SelectionDAG &DAG,
16630                                                MVT ElementType) {
16631   SDLoc dl(Op);
16632   SDValue Mask = Op.getOperand(4);
16633   SDValue DataToTruncate = Op.getOperand(3);
16634   SDValue Addr = Op.getOperand(2);
16635   SDValue Chain = Op.getOperand(0);
16636
16637   EVT VT  = DataToTruncate.getValueType();
16638   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16639                              ElementType, VT.getVectorNumElements());
16640
16641   if (isAllOnes(Mask)) // return just a truncate store
16642     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16643                              MachinePointerInfo(), SVT, false, false,
16644                              SVT.getScalarSizeInBits()/8);
16645
16646   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16647                                 MVT::i1, VT.getVectorNumElements());
16648   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16649                                    Mask.getValueType().getSizeInBits());
16650   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16651   // are extracted by EXTRACT_SUBVECTOR.
16652   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16653                               DAG.getBitcast(BitcastVT, Mask),
16654                               DAG.getIntPtrConstant(0, dl));
16655
16656   MachineMemOperand *MMO = DAG.getMachineFunction().
16657     getMachineMemOperand(MachinePointerInfo(),
16658                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16659                          SVT.getScalarSizeInBits()/8);
16660
16661   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16662                             VMask, SVT, MMO, true);
16663 }
16664
16665 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16666                                       SelectionDAG &DAG) {
16667   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16668
16669   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16670   if (!IntrData) {
16671     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16672       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16673     return SDValue();
16674   }
16675
16676   SDLoc dl(Op);
16677   switch(IntrData->Type) {
16678   default:
16679     llvm_unreachable("Unknown Intrinsic Type");
16680     break;
16681   case RDSEED:
16682   case RDRAND: {
16683     // Emit the node with the right value type.
16684     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16685     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16686
16687     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16688     // Otherwise return the value from Rand, which is always 0, casted to i32.
16689     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16690                       DAG.getConstant(1, dl, Op->getValueType(1)),
16691                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16692                       SDValue(Result.getNode(), 1) };
16693     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16694                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16695                                   Ops);
16696
16697     // Return { result, isValid, chain }.
16698     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16699                        SDValue(Result.getNode(), 2));
16700   }
16701   case GATHER: {
16702   //gather(v1, mask, index, base, scale);
16703     SDValue Chain = Op.getOperand(0);
16704     SDValue Src   = Op.getOperand(2);
16705     SDValue Base  = Op.getOperand(3);
16706     SDValue Index = Op.getOperand(4);
16707     SDValue Mask  = Op.getOperand(5);
16708     SDValue Scale = Op.getOperand(6);
16709     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16710                          Chain, Subtarget);
16711   }
16712   case SCATTER: {
16713   //scatter(base, mask, index, v1, scale);
16714     SDValue Chain = Op.getOperand(0);
16715     SDValue Base  = Op.getOperand(2);
16716     SDValue Mask  = Op.getOperand(3);
16717     SDValue Index = Op.getOperand(4);
16718     SDValue Src   = Op.getOperand(5);
16719     SDValue Scale = Op.getOperand(6);
16720     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16721                           Scale, Chain);
16722   }
16723   case PREFETCH: {
16724     SDValue Hint = Op.getOperand(6);
16725     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16726     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16727     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16728     SDValue Chain = Op.getOperand(0);
16729     SDValue Mask  = Op.getOperand(2);
16730     SDValue Index = Op.getOperand(3);
16731     SDValue Base  = Op.getOperand(4);
16732     SDValue Scale = Op.getOperand(5);
16733     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16734   }
16735   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16736   case RDTSC: {
16737     SmallVector<SDValue, 2> Results;
16738     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16739                             Results);
16740     return DAG.getMergeValues(Results, dl);
16741   }
16742   // Read Performance Monitoring Counters.
16743   case RDPMC: {
16744     SmallVector<SDValue, 2> Results;
16745     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16746     return DAG.getMergeValues(Results, dl);
16747   }
16748   // XTEST intrinsics.
16749   case XTEST: {
16750     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16751     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16752     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16753                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16754                                 InTrans);
16755     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16756     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16757                        Ret, SDValue(InTrans.getNode(), 1));
16758   }
16759   // ADC/ADCX/SBB
16760   case ADX: {
16761     SmallVector<SDValue, 2> Results;
16762     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16763     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16764     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16765                                 DAG.getConstant(-1, dl, MVT::i8));
16766     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16767                               Op.getOperand(4), GenCF.getValue(1));
16768     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16769                                  Op.getOperand(5), MachinePointerInfo(),
16770                                  false, false, 0);
16771     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16772                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16773                                 Res.getValue(1));
16774     Results.push_back(SetCC);
16775     Results.push_back(Store);
16776     return DAG.getMergeValues(Results, dl);
16777   }
16778   case COMPRESS_TO_MEM: {
16779     SDLoc dl(Op);
16780     SDValue Mask = Op.getOperand(4);
16781     SDValue DataToCompress = Op.getOperand(3);
16782     SDValue Addr = Op.getOperand(2);
16783     SDValue Chain = Op.getOperand(0);
16784
16785     EVT VT = DataToCompress.getValueType();
16786     if (isAllOnes(Mask)) // return just a store
16787       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16788                           MachinePointerInfo(), false, false,
16789                           VT.getScalarSizeInBits()/8);
16790
16791     SDValue Compressed =
16792       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16793                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16794     return DAG.getStore(Chain, dl, Compressed, Addr,
16795                         MachinePointerInfo(), false, false,
16796                         VT.getScalarSizeInBits()/8);
16797   }
16798   case TRUNCATE_TO_MEM_VI8:
16799     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16800   case TRUNCATE_TO_MEM_VI16:
16801     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16802   case TRUNCATE_TO_MEM_VI32:
16803     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16804   case EXPAND_FROM_MEM: {
16805     SDLoc dl(Op);
16806     SDValue Mask = Op.getOperand(4);
16807     SDValue PassThru = Op.getOperand(3);
16808     SDValue Addr = Op.getOperand(2);
16809     SDValue Chain = Op.getOperand(0);
16810     EVT VT = Op.getValueType();
16811
16812     if (isAllOnes(Mask)) // return just a load
16813       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16814                          false, VT.getScalarSizeInBits()/8);
16815
16816     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16817                                        false, false, false,
16818                                        VT.getScalarSizeInBits()/8);
16819
16820     SDValue Results[] = {
16821       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16822                            Mask, PassThru, Subtarget, DAG), Chain};
16823     return DAG.getMergeValues(Results, dl);
16824   }
16825   }
16826 }
16827
16828 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16829                                            SelectionDAG &DAG) const {
16830   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16831   MFI->setReturnAddressIsTaken(true);
16832
16833   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16834     return SDValue();
16835
16836   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16837   SDLoc dl(Op);
16838   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16839
16840   if (Depth > 0) {
16841     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16842     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16843     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16844     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16845                        DAG.getNode(ISD::ADD, dl, PtrVT,
16846                                    FrameAddr, Offset),
16847                        MachinePointerInfo(), false, false, false, 0);
16848   }
16849
16850   // Just load the return address.
16851   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16852   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16853                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16854 }
16855
16856 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16857   MachineFunction &MF = DAG.getMachineFunction();
16858   MachineFrameInfo *MFI = MF.getFrameInfo();
16859   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16860   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16861   EVT VT = Op.getValueType();
16862
16863   MFI->setFrameAddressIsTaken(true);
16864
16865   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16866     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16867     // is not possible to crawl up the stack without looking at the unwind codes
16868     // simultaneously.
16869     int FrameAddrIndex = FuncInfo->getFAIndex();
16870     if (!FrameAddrIndex) {
16871       // Set up a frame object for the return address.
16872       unsigned SlotSize = RegInfo->getSlotSize();
16873       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16874           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16875       FuncInfo->setFAIndex(FrameAddrIndex);
16876     }
16877     return DAG.getFrameIndex(FrameAddrIndex, VT);
16878   }
16879
16880   unsigned FrameReg =
16881       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16882   SDLoc dl(Op);  // FIXME probably not meaningful
16883   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16884   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16885           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16886          "Invalid Frame Register!");
16887   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16888   while (Depth--)
16889     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16890                             MachinePointerInfo(),
16891                             false, false, false, 0);
16892   return FrameAddr;
16893 }
16894
16895 // FIXME? Maybe this could be a TableGen attribute on some registers and
16896 // this table could be generated automatically from RegInfo.
16897 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16898                                               SelectionDAG &DAG) const {
16899   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16900   const MachineFunction &MF = DAG.getMachineFunction();
16901
16902   unsigned Reg = StringSwitch<unsigned>(RegName)
16903                        .Case("esp", X86::ESP)
16904                        .Case("rsp", X86::RSP)
16905                        .Case("ebp", X86::EBP)
16906                        .Case("rbp", X86::RBP)
16907                        .Default(0);
16908
16909   if (Reg == X86::EBP || Reg == X86::RBP) {
16910     if (!TFI.hasFP(MF))
16911       report_fatal_error("register " + StringRef(RegName) +
16912                          " is allocatable: function has no frame pointer");
16913 #ifndef NDEBUG
16914     else {
16915       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16916       unsigned FrameReg =
16917           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16918       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16919              "Invalid Frame Register!");
16920     }
16921 #endif
16922   }
16923
16924   if (Reg)
16925     return Reg;
16926
16927   report_fatal_error("Invalid register name global variable");
16928 }
16929
16930 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16931                                                      SelectionDAG &DAG) const {
16932   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16933   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16934 }
16935
16936 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16937   SDValue Chain     = Op.getOperand(0);
16938   SDValue Offset    = Op.getOperand(1);
16939   SDValue Handler   = Op.getOperand(2);
16940   SDLoc dl      (Op);
16941
16942   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16943   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16944   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16945   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16946           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16947          "Invalid Frame Register!");
16948   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16949   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16950
16951   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16952                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16953                                                        dl));
16954   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16955   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16956                        false, false, 0);
16957   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16958
16959   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16960                      DAG.getRegister(StoreAddrReg, PtrVT));
16961 }
16962
16963 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16964                                                SelectionDAG &DAG) const {
16965   SDLoc DL(Op);
16966   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16967                      DAG.getVTList(MVT::i32, MVT::Other),
16968                      Op.getOperand(0), Op.getOperand(1));
16969 }
16970
16971 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16972                                                 SelectionDAG &DAG) const {
16973   SDLoc DL(Op);
16974   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16975                      Op.getOperand(0), Op.getOperand(1));
16976 }
16977
16978 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16979   return Op.getOperand(0);
16980 }
16981
16982 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16983                                                 SelectionDAG &DAG) const {
16984   SDValue Root = Op.getOperand(0);
16985   SDValue Trmp = Op.getOperand(1); // trampoline
16986   SDValue FPtr = Op.getOperand(2); // nested function
16987   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16988   SDLoc dl (Op);
16989
16990   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16991   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16992
16993   if (Subtarget->is64Bit()) {
16994     SDValue OutChains[6];
16995
16996     // Large code-model.
16997     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16998     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16999
17000     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17001     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17002
17003     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17004
17005     // Load the pointer to the nested function into R11.
17006     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17007     SDValue Addr = Trmp;
17008     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17009                                 Addr, MachinePointerInfo(TrmpAddr),
17010                                 false, false, 0);
17011
17012     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17013                        DAG.getConstant(2, dl, MVT::i64));
17014     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17015                                 MachinePointerInfo(TrmpAddr, 2),
17016                                 false, false, 2);
17017
17018     // Load the 'nest' parameter value into R10.
17019     // R10 is specified in X86CallingConv.td
17020     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17021     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17022                        DAG.getConstant(10, dl, MVT::i64));
17023     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17024                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17025                                 false, false, 0);
17026
17027     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17028                        DAG.getConstant(12, dl, MVT::i64));
17029     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17030                                 MachinePointerInfo(TrmpAddr, 12),
17031                                 false, false, 2);
17032
17033     // Jump to the nested function.
17034     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17035     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17036                        DAG.getConstant(20, dl, MVT::i64));
17037     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17038                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17039                                 false, false, 0);
17040
17041     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17042     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17043                        DAG.getConstant(22, dl, MVT::i64));
17044     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17045                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17046                                 false, false, 0);
17047
17048     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17049   } else {
17050     const Function *Func =
17051       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17052     CallingConv::ID CC = Func->getCallingConv();
17053     unsigned NestReg;
17054
17055     switch (CC) {
17056     default:
17057       llvm_unreachable("Unsupported calling convention");
17058     case CallingConv::C:
17059     case CallingConv::X86_StdCall: {
17060       // Pass 'nest' parameter in ECX.
17061       // Must be kept in sync with X86CallingConv.td
17062       NestReg = X86::ECX;
17063
17064       // Check that ECX wasn't needed by an 'inreg' parameter.
17065       FunctionType *FTy = Func->getFunctionType();
17066       const AttributeSet &Attrs = Func->getAttributes();
17067
17068       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17069         unsigned InRegCount = 0;
17070         unsigned Idx = 1;
17071
17072         for (FunctionType::param_iterator I = FTy->param_begin(),
17073              E = FTy->param_end(); I != E; ++I, ++Idx)
17074           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17075             auto &DL = DAG.getDataLayout();
17076             // FIXME: should only count parameters that are lowered to integers.
17077             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17078           }
17079
17080         if (InRegCount > 2) {
17081           report_fatal_error("Nest register in use - reduce number of inreg"
17082                              " parameters!");
17083         }
17084       }
17085       break;
17086     }
17087     case CallingConv::X86_FastCall:
17088     case CallingConv::X86_ThisCall:
17089     case CallingConv::Fast:
17090       // Pass 'nest' parameter in EAX.
17091       // Must be kept in sync with X86CallingConv.td
17092       NestReg = X86::EAX;
17093       break;
17094     }
17095
17096     SDValue OutChains[4];
17097     SDValue Addr, Disp;
17098
17099     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17100                        DAG.getConstant(10, dl, MVT::i32));
17101     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17102
17103     // This is storing the opcode for MOV32ri.
17104     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17105     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17106     OutChains[0] = DAG.getStore(Root, dl,
17107                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17108                                 Trmp, MachinePointerInfo(TrmpAddr),
17109                                 false, false, 0);
17110
17111     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17112                        DAG.getConstant(1, dl, MVT::i32));
17113     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17114                                 MachinePointerInfo(TrmpAddr, 1),
17115                                 false, false, 1);
17116
17117     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17118     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17119                        DAG.getConstant(5, dl, MVT::i32));
17120     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17121                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17122                                 false, false, 1);
17123
17124     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17125                        DAG.getConstant(6, dl, MVT::i32));
17126     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17127                                 MachinePointerInfo(TrmpAddr, 6),
17128                                 false, false, 1);
17129
17130     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17131   }
17132 }
17133
17134 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17135                                             SelectionDAG &DAG) const {
17136   /*
17137    The rounding mode is in bits 11:10 of FPSR, and has the following
17138    settings:
17139      00 Round to nearest
17140      01 Round to -inf
17141      10 Round to +inf
17142      11 Round to 0
17143
17144   FLT_ROUNDS, on the other hand, expects the following:
17145     -1 Undefined
17146      0 Round to 0
17147      1 Round to nearest
17148      2 Round to +inf
17149      3 Round to -inf
17150
17151   To perform the conversion, we do:
17152     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17153   */
17154
17155   MachineFunction &MF = DAG.getMachineFunction();
17156   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17157   unsigned StackAlignment = TFI.getStackAlignment();
17158   MVT VT = Op.getSimpleValueType();
17159   SDLoc DL(Op);
17160
17161   // Save FP Control Word to stack slot
17162   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17163   SDValue StackSlot =
17164       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17165
17166   MachineMemOperand *MMO =
17167       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17168                               MachineMemOperand::MOStore, 2, 2);
17169
17170   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17171   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17172                                           DAG.getVTList(MVT::Other),
17173                                           Ops, MVT::i16, MMO);
17174
17175   // Load FP Control Word from stack slot
17176   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17177                             MachinePointerInfo(), false, false, false, 0);
17178
17179   // Transform as necessary
17180   SDValue CWD1 =
17181     DAG.getNode(ISD::SRL, DL, MVT::i16,
17182                 DAG.getNode(ISD::AND, DL, MVT::i16,
17183                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17184                 DAG.getConstant(11, DL, MVT::i8));
17185   SDValue CWD2 =
17186     DAG.getNode(ISD::SRL, DL, MVT::i16,
17187                 DAG.getNode(ISD::AND, DL, MVT::i16,
17188                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17189                 DAG.getConstant(9, DL, MVT::i8));
17190
17191   SDValue RetVal =
17192     DAG.getNode(ISD::AND, DL, MVT::i16,
17193                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17194                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17195                             DAG.getConstant(1, DL, MVT::i16)),
17196                 DAG.getConstant(3, DL, MVT::i16));
17197
17198   return DAG.getNode((VT.getSizeInBits() < 16 ?
17199                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17200 }
17201
17202 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
17203   MVT VT = Op.getSimpleValueType();
17204   EVT OpVT = VT;
17205   unsigned NumBits = VT.getSizeInBits();
17206   SDLoc dl(Op);
17207
17208   Op = Op.getOperand(0);
17209   if (VT == MVT::i8) {
17210     // Zero extend to i32 since there is not an i8 bsr.
17211     OpVT = MVT::i32;
17212     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17213   }
17214
17215   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17216   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17217   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17218
17219   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17220   SDValue Ops[] = {
17221     Op,
17222     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17223     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17224     Op.getValue(1)
17225   };
17226   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17227
17228   // Finally xor with NumBits-1.
17229   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17230                    DAG.getConstant(NumBits - 1, dl, OpVT));
17231
17232   if (VT == MVT::i8)
17233     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17234   return Op;
17235 }
17236
17237 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17238   MVT VT = Op.getSimpleValueType();
17239   EVT OpVT = VT;
17240   unsigned NumBits = VT.getSizeInBits();
17241   SDLoc dl(Op);
17242
17243   Op = Op.getOperand(0);
17244   if (VT == MVT::i8) {
17245     // Zero extend to i32 since there is not an i8 bsr.
17246     OpVT = MVT::i32;
17247     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17248   }
17249
17250   // Issue a bsr (scan bits in reverse).
17251   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17252   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17253
17254   // And xor with NumBits-1.
17255   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17256                    DAG.getConstant(NumBits - 1, dl, OpVT));
17257
17258   if (VT == MVT::i8)
17259     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17260   return Op;
17261 }
17262
17263 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17264   MVT VT = Op.getSimpleValueType();
17265   unsigned NumBits = VT.getScalarSizeInBits();
17266   SDLoc dl(Op);
17267
17268   if (VT.isVector()) {
17269     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17270
17271     SDValue N0 = Op.getOperand(0);
17272     SDValue Zero = DAG.getConstant(0, dl, VT);
17273
17274     // lsb(x) = (x & -x)
17275     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
17276                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
17277
17278     // cttz_undef(x) = (width - 1) - ctlz(lsb)
17279     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
17280         TLI.isOperationLegal(ISD::CTLZ, VT)) {
17281       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
17282       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
17283                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
17284     }
17285
17286     // cttz(x) = ctpop(lsb - 1)
17287     SDValue One = DAG.getConstant(1, dl, VT);
17288     return DAG.getNode(ISD::CTPOP, dl, VT,
17289                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
17290   }
17291
17292   assert(Op.getOpcode() == ISD::CTTZ &&
17293          "Only scalar CTTZ requires custom lowering");
17294
17295   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17296   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17297   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
17298
17299   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17300   SDValue Ops[] = {
17301     Op,
17302     DAG.getConstant(NumBits, dl, VT),
17303     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17304     Op.getValue(1)
17305   };
17306   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17307 }
17308
17309 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17310 // ones, and then concatenate the result back.
17311 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17312   MVT VT = Op.getSimpleValueType();
17313
17314   assert(VT.is256BitVector() && VT.isInteger() &&
17315          "Unsupported value type for operation");
17316
17317   unsigned NumElems = VT.getVectorNumElements();
17318   SDLoc dl(Op);
17319
17320   // Extract the LHS vectors
17321   SDValue LHS = Op.getOperand(0);
17322   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17323   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17324
17325   // Extract the RHS vectors
17326   SDValue RHS = Op.getOperand(1);
17327   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17328   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17329
17330   MVT EltVT = VT.getVectorElementType();
17331   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17332
17333   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17334                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17335                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17336 }
17337
17338 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17339   if (Op.getValueType() == MVT::i1)
17340     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17341                        Op.getOperand(0), Op.getOperand(1));
17342   assert(Op.getSimpleValueType().is256BitVector() &&
17343          Op.getSimpleValueType().isInteger() &&
17344          "Only handle AVX 256-bit vector integer operation");
17345   return Lower256IntArith(Op, DAG);
17346 }
17347
17348 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17349   if (Op.getValueType() == MVT::i1)
17350     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17351                        Op.getOperand(0), Op.getOperand(1));
17352   assert(Op.getSimpleValueType().is256BitVector() &&
17353          Op.getSimpleValueType().isInteger() &&
17354          "Only handle AVX 256-bit vector integer operation");
17355   return Lower256IntArith(Op, DAG);
17356 }
17357
17358 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17359   assert(Op.getSimpleValueType().is256BitVector() &&
17360          Op.getSimpleValueType().isInteger() &&
17361          "Only handle AVX 256-bit vector integer operation");
17362   return Lower256IntArith(Op, DAG);
17363 }
17364
17365 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17366                         SelectionDAG &DAG) {
17367   SDLoc dl(Op);
17368   MVT VT = Op.getSimpleValueType();
17369
17370   if (VT == MVT::i1)
17371     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17372
17373   // Decompose 256-bit ops into smaller 128-bit ops.
17374   if (VT.is256BitVector() && !Subtarget->hasInt256())
17375     return Lower256IntArith(Op, DAG);
17376
17377   SDValue A = Op.getOperand(0);
17378   SDValue B = Op.getOperand(1);
17379
17380   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17381   // pairs, multiply and truncate.
17382   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17383     if (Subtarget->hasInt256()) {
17384       if (VT == MVT::v32i8) {
17385         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17386         SDValue Lo = DAG.getIntPtrConstant(0, dl);
17387         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17388         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17389         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17390         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17391         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17392         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17393                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17394                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17395       }
17396
17397       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17398       return DAG.getNode(
17399           ISD::TRUNCATE, dl, VT,
17400           DAG.getNode(ISD::MUL, dl, ExVT,
17401                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17402                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17403     }
17404
17405     assert(VT == MVT::v16i8 &&
17406            "Pre-AVX2 support only supports v16i8 multiplication");
17407     MVT ExVT = MVT::v8i16;
17408
17409     // Extract the lo parts and sign extend to i16
17410     SDValue ALo, BLo;
17411     if (Subtarget->hasSSE41()) {
17412       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17413       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17414     } else {
17415       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17416                               -1, 4, -1, 5, -1, 6, -1, 7};
17417       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17418       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17419       ALo = DAG.getBitcast(ExVT, ALo);
17420       BLo = DAG.getBitcast(ExVT, BLo);
17421       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17422       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17423     }
17424
17425     // Extract the hi parts and sign extend to i16
17426     SDValue AHi, BHi;
17427     if (Subtarget->hasSSE41()) {
17428       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17429                               -1, -1, -1, -1, -1, -1, -1, -1};
17430       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17431       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17432       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17433       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17434     } else {
17435       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17436                               -1, 12, -1, 13, -1, 14, -1, 15};
17437       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17438       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17439       AHi = DAG.getBitcast(ExVT, AHi);
17440       BHi = DAG.getBitcast(ExVT, BHi);
17441       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17442       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17443     }
17444
17445     // Multiply, mask the lower 8bits of the lo/hi results and pack
17446     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17447     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17448     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17449     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17450     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17451   }
17452
17453   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17454   if (VT == MVT::v4i32) {
17455     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17456            "Should not custom lower when pmuldq is available!");
17457
17458     // Extract the odd parts.
17459     static const int UnpackMask[] = { 1, -1, 3, -1 };
17460     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17461     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17462
17463     // Multiply the even parts.
17464     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17465     // Now multiply odd parts.
17466     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17467
17468     Evens = DAG.getBitcast(VT, Evens);
17469     Odds = DAG.getBitcast(VT, Odds);
17470
17471     // Merge the two vectors back together with a shuffle. This expands into 2
17472     // shuffles.
17473     static const int ShufMask[] = { 0, 4, 2, 6 };
17474     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17475   }
17476
17477   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17478          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17479
17480   //  Ahi = psrlqi(a, 32);
17481   //  Bhi = psrlqi(b, 32);
17482   //
17483   //  AloBlo = pmuludq(a, b);
17484   //  AloBhi = pmuludq(a, Bhi);
17485   //  AhiBlo = pmuludq(Ahi, b);
17486
17487   //  AloBhi = psllqi(AloBhi, 32);
17488   //  AhiBlo = psllqi(AhiBlo, 32);
17489   //  return AloBlo + AloBhi + AhiBlo;
17490
17491   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17492   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17493
17494   SDValue AhiBlo = Ahi;
17495   SDValue AloBhi = Bhi;
17496   // Bit cast to 32-bit vectors for MULUDQ
17497   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17498                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17499   A = DAG.getBitcast(MulVT, A);
17500   B = DAG.getBitcast(MulVT, B);
17501   Ahi = DAG.getBitcast(MulVT, Ahi);
17502   Bhi = DAG.getBitcast(MulVT, Bhi);
17503
17504   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17505   // After shifting right const values the result may be all-zero.
17506   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17507     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17508     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17509   }
17510   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17511     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17512     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17513   }
17514
17515   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17516   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17517 }
17518
17519 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17520   assert(Subtarget->isTargetWin64() && "Unexpected target");
17521   EVT VT = Op.getValueType();
17522   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17523          "Unexpected return type for lowering");
17524
17525   RTLIB::Libcall LC;
17526   bool isSigned;
17527   switch (Op->getOpcode()) {
17528   default: llvm_unreachable("Unexpected request for libcall!");
17529   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17530   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17531   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17532   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17533   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17534   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17535   }
17536
17537   SDLoc dl(Op);
17538   SDValue InChain = DAG.getEntryNode();
17539
17540   TargetLowering::ArgListTy Args;
17541   TargetLowering::ArgListEntry Entry;
17542   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17543     EVT ArgVT = Op->getOperand(i).getValueType();
17544     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17545            "Unexpected argument type for lowering");
17546     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17547     Entry.Node = StackPtr;
17548     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17549                            false, false, 16);
17550     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17551     Entry.Ty = PointerType::get(ArgTy,0);
17552     Entry.isSExt = false;
17553     Entry.isZExt = false;
17554     Args.push_back(Entry);
17555   }
17556
17557   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17558                                          getPointerTy(DAG.getDataLayout()));
17559
17560   TargetLowering::CallLoweringInfo CLI(DAG);
17561   CLI.setDebugLoc(dl).setChain(InChain)
17562     .setCallee(getLibcallCallingConv(LC),
17563                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17564                Callee, std::move(Args), 0)
17565     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17566
17567   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17568   return DAG.getBitcast(VT, CallInfo.first);
17569 }
17570
17571 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17572                              SelectionDAG &DAG) {
17573   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17574   EVT VT = Op0.getValueType();
17575   SDLoc dl(Op);
17576
17577   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17578          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17579
17580   // PMULxD operations multiply each even value (starting at 0) of LHS with
17581   // the related value of RHS and produce a widen result.
17582   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17583   // => <2 x i64> <ae|cg>
17584   //
17585   // In other word, to have all the results, we need to perform two PMULxD:
17586   // 1. one with the even values.
17587   // 2. one with the odd values.
17588   // To achieve #2, with need to place the odd values at an even position.
17589   //
17590   // Place the odd value at an even position (basically, shift all values 1
17591   // step to the left):
17592   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17593   // <a|b|c|d> => <b|undef|d|undef>
17594   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17595   // <e|f|g|h> => <f|undef|h|undef>
17596   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17597
17598   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17599   // ints.
17600   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17601   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17602   unsigned Opcode =
17603       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17604   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17605   // => <2 x i64> <ae|cg>
17606   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17607   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17608   // => <2 x i64> <bf|dh>
17609   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17610
17611   // Shuffle it back into the right order.
17612   SDValue Highs, Lows;
17613   if (VT == MVT::v8i32) {
17614     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17615     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17616     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17617     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17618   } else {
17619     const int HighMask[] = {1, 5, 3, 7};
17620     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17621     const int LowMask[] = {0, 4, 2, 6};
17622     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17623   }
17624
17625   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17626   // unsigned multiply.
17627   if (IsSigned && !Subtarget->hasSSE41()) {
17628     SDValue ShAmt = DAG.getConstant(
17629         31, dl,
17630         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17631     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17632                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17633     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17634                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17635
17636     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17637     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17638   }
17639
17640   // The first result of MUL_LOHI is actually the low value, followed by the
17641   // high value.
17642   SDValue Ops[] = {Lows, Highs};
17643   return DAG.getMergeValues(Ops, dl);
17644 }
17645
17646 // Return true if the required (according to Opcode) shift-imm form is natively
17647 // supported by the Subtarget
17648 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17649                                         unsigned Opcode) {
17650   if (VT.getScalarSizeInBits() < 16)
17651     return false;
17652
17653   if (VT.is512BitVector() &&
17654       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17655     return true;
17656
17657   bool LShift = VT.is128BitVector() ||
17658     (VT.is256BitVector() && Subtarget->hasInt256());
17659
17660   bool AShift = LShift && (Subtarget->hasVLX() ||
17661     (VT != MVT::v2i64 && VT != MVT::v4i64));
17662   return (Opcode == ISD::SRA) ? AShift : LShift;
17663 }
17664
17665 // The shift amount is a variable, but it is the same for all vector lanes.
17666 // These instructions are defined together with shift-immediate.
17667 static
17668 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17669                                       unsigned Opcode) {
17670   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17671 }
17672
17673 // Return true if the required (according to Opcode) variable-shift form is
17674 // natively supported by the Subtarget
17675 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17676                                     unsigned Opcode) {
17677
17678   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17679     return false;
17680
17681   // vXi16 supported only on AVX-512, BWI
17682   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17683     return false;
17684
17685   if (VT.is512BitVector() || Subtarget->hasVLX())
17686     return true;
17687
17688   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17689   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17690   return (Opcode == ISD::SRA) ? AShift : LShift;
17691 }
17692
17693 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17694                                          const X86Subtarget *Subtarget) {
17695   MVT VT = Op.getSimpleValueType();
17696   SDLoc dl(Op);
17697   SDValue R = Op.getOperand(0);
17698   SDValue Amt = Op.getOperand(1);
17699
17700   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17701     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17702
17703   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17704     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17705     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17706     SDValue Ex = DAG.getBitcast(ExVT, R);
17707
17708     if (ShiftAmt >= 32) {
17709       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17710       SDValue Upper =
17711           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17712       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17713                                                  ShiftAmt - 32, DAG);
17714       if (VT == MVT::v2i64)
17715         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17716       if (VT == MVT::v4i64)
17717         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17718                                   {9, 1, 11, 3, 13, 5, 15, 7});
17719     } else {
17720       // SRA upper i32, SHL whole i64 and select lower i32.
17721       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17722                                                  ShiftAmt, DAG);
17723       SDValue Lower =
17724           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17725       Lower = DAG.getBitcast(ExVT, Lower);
17726       if (VT == MVT::v2i64)
17727         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17728       if (VT == MVT::v4i64)
17729         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17730                                   {8, 1, 10, 3, 12, 5, 14, 7});
17731     }
17732     return DAG.getBitcast(VT, Ex);
17733   };
17734
17735   // Optimize shl/srl/sra with constant shift amount.
17736   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17737     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17738       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17739
17740       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17741         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17742
17743       // i64 SRA needs to be performed as partial shifts.
17744       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17745           Op.getOpcode() == ISD::SRA)
17746         return ArithmeticShiftRight64(ShiftAmt);
17747
17748       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17749         unsigned NumElts = VT.getVectorNumElements();
17750         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17751
17752         if (Op.getOpcode() == ISD::SHL) {
17753           // Simple i8 add case
17754           if (ShiftAmt == 1)
17755             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17756
17757           // Make a large shift.
17758           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17759                                                    R, ShiftAmt, DAG);
17760           SHL = DAG.getBitcast(VT, SHL);
17761           // Zero out the rightmost bits.
17762           SmallVector<SDValue, 32> V(
17763               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17764           return DAG.getNode(ISD::AND, dl, VT, SHL,
17765                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17766         }
17767         if (Op.getOpcode() == ISD::SRL) {
17768           // Make a large shift.
17769           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17770                                                    R, ShiftAmt, DAG);
17771           SRL = DAG.getBitcast(VT, SRL);
17772           // Zero out the leftmost bits.
17773           SmallVector<SDValue, 32> V(
17774               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17775           return DAG.getNode(ISD::AND, dl, VT, SRL,
17776                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17777         }
17778         if (Op.getOpcode() == ISD::SRA) {
17779           if (ShiftAmt == 7) {
17780             // ashr(R, 7)  === cmp_slt(R, 0)
17781             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17782             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17783           }
17784
17785           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17786           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17787           SmallVector<SDValue, 32> V(NumElts,
17788                                      DAG.getConstant(128 >> ShiftAmt, dl,
17789                                                      MVT::i8));
17790           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17791           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17792           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17793           return Res;
17794         }
17795         llvm_unreachable("Unknown shift opcode.");
17796       }
17797     }
17798   }
17799
17800   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17801   if (!Subtarget->is64Bit() &&
17802       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17803
17804     // Peek through any splat that was introduced for i64 shift vectorization.
17805     int SplatIndex = -1;
17806     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17807       if (SVN->isSplat()) {
17808         SplatIndex = SVN->getSplatIndex();
17809         Amt = Amt.getOperand(0);
17810         assert(SplatIndex < (int)VT.getVectorNumElements() &&
17811                "Splat shuffle referencing second operand");
17812       }
17813
17814     if (Amt.getOpcode() != ISD::BITCAST ||
17815         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17816       return SDValue();
17817
17818     Amt = Amt.getOperand(0);
17819     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17820                      VT.getVectorNumElements();
17821     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17822     uint64_t ShiftAmt = 0;
17823     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17824     for (unsigned i = 0; i != Ratio; ++i) {
17825       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17826       if (!C)
17827         return SDValue();
17828       // 6 == Log2(64)
17829       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17830     }
17831
17832     // Check remaining shift amounts (if not a splat).
17833     if (SplatIndex < 0) {
17834       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17835         uint64_t ShAmt = 0;
17836         for (unsigned j = 0; j != Ratio; ++j) {
17837           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17838           if (!C)
17839             return SDValue();
17840           // 6 == Log2(64)
17841           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17842         }
17843         if (ShAmt != ShiftAmt)
17844           return SDValue();
17845       }
17846     }
17847
17848     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17849       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17850
17851     if (Op.getOpcode() == ISD::SRA)
17852       return ArithmeticShiftRight64(ShiftAmt);
17853   }
17854
17855   return SDValue();
17856 }
17857
17858 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17859                                         const X86Subtarget* Subtarget) {
17860   MVT VT = Op.getSimpleValueType();
17861   SDLoc dl(Op);
17862   SDValue R = Op.getOperand(0);
17863   SDValue Amt = Op.getOperand(1);
17864
17865   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17866     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17867
17868   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17869     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17870
17871   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17872     SDValue BaseShAmt;
17873     EVT EltVT = VT.getVectorElementType();
17874
17875     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17876       // Check if this build_vector node is doing a splat.
17877       // If so, then set BaseShAmt equal to the splat value.
17878       BaseShAmt = BV->getSplatValue();
17879       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17880         BaseShAmt = SDValue();
17881     } else {
17882       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17883         Amt = Amt.getOperand(0);
17884
17885       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17886       if (SVN && SVN->isSplat()) {
17887         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17888         SDValue InVec = Amt.getOperand(0);
17889         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17890           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17891                  "Unexpected shuffle index found!");
17892           BaseShAmt = InVec.getOperand(SplatIdx);
17893         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17894            if (ConstantSDNode *C =
17895                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17896              if (C->getZExtValue() == SplatIdx)
17897                BaseShAmt = InVec.getOperand(1);
17898            }
17899         }
17900
17901         if (!BaseShAmt)
17902           // Avoid introducing an extract element from a shuffle.
17903           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17904                                   DAG.getIntPtrConstant(SplatIdx, dl));
17905       }
17906     }
17907
17908     if (BaseShAmt.getNode()) {
17909       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17910       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17911         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17912       else if (EltVT.bitsLT(MVT::i32))
17913         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17914
17915       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17916     }
17917   }
17918
17919   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17920   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17921       Amt.getOpcode() == ISD::BITCAST &&
17922       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17923     Amt = Amt.getOperand(0);
17924     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17925                      VT.getVectorNumElements();
17926     std::vector<SDValue> Vals(Ratio);
17927     for (unsigned i = 0; i != Ratio; ++i)
17928       Vals[i] = Amt.getOperand(i);
17929     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17930       for (unsigned j = 0; j != Ratio; ++j)
17931         if (Vals[j] != Amt.getOperand(i + j))
17932           return SDValue();
17933     }
17934
17935     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17936       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17937   }
17938   return SDValue();
17939 }
17940
17941 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17942                           SelectionDAG &DAG) {
17943   MVT VT = Op.getSimpleValueType();
17944   SDLoc dl(Op);
17945   SDValue R = Op.getOperand(0);
17946   SDValue Amt = Op.getOperand(1);
17947
17948   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17949   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17950
17951   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17952     return V;
17953
17954   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17955       return V;
17956
17957   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17958     return Op;
17959
17960   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17961   // shifts per-lane and then shuffle the partial results back together.
17962   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17963     // Splat the shift amounts so the scalar shifts above will catch it.
17964     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17965     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17966     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17967     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17968     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17969   }
17970
17971   // i64 vector arithmetic shift can be emulated with the transform:
17972   // M = lshr(SIGN_BIT, Amt)
17973   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
17974   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
17975       Op.getOpcode() == ISD::SRA) {
17976     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
17977     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
17978     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17979     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
17980     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
17981     return R;
17982   }
17983
17984   // If possible, lower this packed shift into a vector multiply instead of
17985   // expanding it into a sequence of scalar shifts.
17986   // Do this only if the vector shift count is a constant build_vector.
17987   if (Op.getOpcode() == ISD::SHL &&
17988       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17989        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17990       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17991     SmallVector<SDValue, 8> Elts;
17992     EVT SVT = VT.getScalarType();
17993     unsigned SVTBits = SVT.getSizeInBits();
17994     const APInt &One = APInt(SVTBits, 1);
17995     unsigned NumElems = VT.getVectorNumElements();
17996
17997     for (unsigned i=0; i !=NumElems; ++i) {
17998       SDValue Op = Amt->getOperand(i);
17999       if (Op->getOpcode() == ISD::UNDEF) {
18000         Elts.push_back(Op);
18001         continue;
18002       }
18003
18004       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18005       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
18006       uint64_t ShAmt = C.getZExtValue();
18007       if (ShAmt >= SVTBits) {
18008         Elts.push_back(DAG.getUNDEF(SVT));
18009         continue;
18010       }
18011       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18012     }
18013     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18014     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18015   }
18016
18017   // Lower SHL with variable shift amount.
18018   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18019     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18020
18021     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18022                      DAG.getConstant(0x3f800000U, dl, VT));
18023     Op = DAG.getBitcast(MVT::v4f32, Op);
18024     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18025     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18026   }
18027
18028   // If possible, lower this shift as a sequence of two shifts by
18029   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18030   // Example:
18031   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18032   //
18033   // Could be rewritten as:
18034   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18035   //
18036   // The advantage is that the two shifts from the example would be
18037   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18038   // the vector shift into four scalar shifts plus four pairs of vector
18039   // insert/extract.
18040   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18041       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18042     unsigned TargetOpcode = X86ISD::MOVSS;
18043     bool CanBeSimplified;
18044     // The splat value for the first packed shift (the 'X' from the example).
18045     SDValue Amt1 = Amt->getOperand(0);
18046     // The splat value for the second packed shift (the 'Y' from the example).
18047     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18048                                         Amt->getOperand(2);
18049
18050     // See if it is possible to replace this node with a sequence of
18051     // two shifts followed by a MOVSS/MOVSD
18052     if (VT == MVT::v4i32) {
18053       // Check if it is legal to use a MOVSS.
18054       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18055                         Amt2 == Amt->getOperand(3);
18056       if (!CanBeSimplified) {
18057         // Otherwise, check if we can still simplify this node using a MOVSD.
18058         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18059                           Amt->getOperand(2) == Amt->getOperand(3);
18060         TargetOpcode = X86ISD::MOVSD;
18061         Amt2 = Amt->getOperand(2);
18062       }
18063     } else {
18064       // Do similar checks for the case where the machine value type
18065       // is MVT::v8i16.
18066       CanBeSimplified = Amt1 == Amt->getOperand(1);
18067       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18068         CanBeSimplified = Amt2 == Amt->getOperand(i);
18069
18070       if (!CanBeSimplified) {
18071         TargetOpcode = X86ISD::MOVSD;
18072         CanBeSimplified = true;
18073         Amt2 = Amt->getOperand(4);
18074         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18075           CanBeSimplified = Amt1 == Amt->getOperand(i);
18076         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18077           CanBeSimplified = Amt2 == Amt->getOperand(j);
18078       }
18079     }
18080
18081     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18082         isa<ConstantSDNode>(Amt2)) {
18083       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18084       EVT CastVT = MVT::v4i32;
18085       SDValue Splat1 =
18086         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18087       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18088       SDValue Splat2 =
18089         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18090       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18091       if (TargetOpcode == X86ISD::MOVSD)
18092         CastVT = MVT::v2i64;
18093       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18094       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18095       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18096                                             BitCast1, DAG);
18097       return DAG.getBitcast(VT, Result);
18098     }
18099   }
18100
18101   // v4i32 Non Uniform Shifts.
18102   // If the shift amount is constant we can shift each lane using the SSE2
18103   // immediate shifts, else we need to zero-extend each lane to the lower i64
18104   // and shift using the SSE2 variable shifts.
18105   // The separate results can then be blended together.
18106   if (VT == MVT::v4i32) {
18107     unsigned Opc = Op.getOpcode();
18108     SDValue Amt0, Amt1, Amt2, Amt3;
18109     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18110       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18111       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18112       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18113       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18114     } else {
18115       // ISD::SHL is handled above but we include it here for completeness.
18116       switch (Opc) {
18117       default:
18118         llvm_unreachable("Unknown target vector shift node");
18119       case ISD::SHL:
18120         Opc = X86ISD::VSHL;
18121         break;
18122       case ISD::SRL:
18123         Opc = X86ISD::VSRL;
18124         break;
18125       case ISD::SRA:
18126         Opc = X86ISD::VSRA;
18127         break;
18128       }
18129       // The SSE2 shifts use the lower i64 as the same shift amount for
18130       // all lanes and the upper i64 is ignored. These shuffle masks
18131       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18132       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18133       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18134       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18135       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18136       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18137     }
18138
18139     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18140     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18141     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18142     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18143     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18144     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18145     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18146   }
18147
18148   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
18149     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18150     unsigned ShiftOpcode = Op->getOpcode();
18151
18152     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18153       // On SSE41 targets we make use of the fact that VSELECT lowers
18154       // to PBLENDVB which selects bytes based just on the sign bit.
18155       if (Subtarget->hasSSE41()) {
18156         V0 = DAG.getBitcast(VT, V0);
18157         V1 = DAG.getBitcast(VT, V1);
18158         Sel = DAG.getBitcast(VT, Sel);
18159         return DAG.getBitcast(SelVT,
18160                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18161       }
18162       // On pre-SSE41 targets we test for the sign bit by comparing to
18163       // zero - a negative value will set all bits of the lanes to true
18164       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18165       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18166       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18167       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18168     };
18169
18170     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18171     // We can safely do this using i16 shifts as we're only interested in
18172     // the 3 lower bits of each byte.
18173     Amt = DAG.getBitcast(ExtVT, Amt);
18174     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18175     Amt = DAG.getBitcast(VT, Amt);
18176
18177     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18178       // r = VSELECT(r, shift(r, 4), a);
18179       SDValue M =
18180           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18181       R = SignBitSelect(VT, Amt, M, R);
18182
18183       // a += a
18184       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18185
18186       // r = VSELECT(r, shift(r, 2), a);
18187       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18188       R = SignBitSelect(VT, Amt, M, R);
18189
18190       // a += a
18191       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18192
18193       // return VSELECT(r, shift(r, 1), a);
18194       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18195       R = SignBitSelect(VT, Amt, M, R);
18196       return R;
18197     }
18198
18199     if (Op->getOpcode() == ISD::SRA) {
18200       // For SRA we need to unpack each byte to the higher byte of a i16 vector
18201       // so we can correctly sign extend. We don't care what happens to the
18202       // lower byte.
18203       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18204       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18205       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18206       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18207       ALo = DAG.getBitcast(ExtVT, ALo);
18208       AHi = DAG.getBitcast(ExtVT, AHi);
18209       RLo = DAG.getBitcast(ExtVT, RLo);
18210       RHi = DAG.getBitcast(ExtVT, RHi);
18211
18212       // r = VSELECT(r, shift(r, 4), a);
18213       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18214                                 DAG.getConstant(4, dl, ExtVT));
18215       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18216                                 DAG.getConstant(4, dl, ExtVT));
18217       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18218       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18219
18220       // a += a
18221       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18222       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18223
18224       // r = VSELECT(r, shift(r, 2), a);
18225       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18226                         DAG.getConstant(2, dl, ExtVT));
18227       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18228                         DAG.getConstant(2, dl, ExtVT));
18229       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18230       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18231
18232       // a += a
18233       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18234       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18235
18236       // r = VSELECT(r, shift(r, 1), a);
18237       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18238                         DAG.getConstant(1, dl, ExtVT));
18239       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18240                         DAG.getConstant(1, dl, ExtVT));
18241       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18242       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18243
18244       // Logical shift the result back to the lower byte, leaving a zero upper
18245       // byte
18246       // meaning that we can safely pack with PACKUSWB.
18247       RLo =
18248           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18249       RHi =
18250           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18251       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18252     }
18253   }
18254
18255   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18256   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18257   // solution better.
18258   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18259     MVT ExtVT = MVT::v8i32;
18260     unsigned ExtOpc =
18261         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18262     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18263     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18264     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18265                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18266   }
18267
18268   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
18269     MVT ExtVT = MVT::v8i32;
18270     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18271     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18272     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18273     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18274     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18275     ALo = DAG.getBitcast(ExtVT, ALo);
18276     AHi = DAG.getBitcast(ExtVT, AHi);
18277     RLo = DAG.getBitcast(ExtVT, RLo);
18278     RHi = DAG.getBitcast(ExtVT, RHi);
18279     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18280     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18281     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18282     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18283     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18284   }
18285
18286   if (VT == MVT::v8i16) {
18287     unsigned ShiftOpcode = Op->getOpcode();
18288
18289     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18290       // On SSE41 targets we make use of the fact that VSELECT lowers
18291       // to PBLENDVB which selects bytes based just on the sign bit.
18292       if (Subtarget->hasSSE41()) {
18293         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18294         V0 = DAG.getBitcast(ExtVT, V0);
18295         V1 = DAG.getBitcast(ExtVT, V1);
18296         Sel = DAG.getBitcast(ExtVT, Sel);
18297         return DAG.getBitcast(
18298             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18299       }
18300       // On pre-SSE41 targets we splat the sign bit - a negative value will
18301       // set all bits of the lanes to true and VSELECT uses that in
18302       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18303       SDValue C =
18304           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18305       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18306     };
18307
18308     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18309     if (Subtarget->hasSSE41()) {
18310       // On SSE41 targets we need to replicate the shift mask in both
18311       // bytes for PBLENDVB.
18312       Amt = DAG.getNode(
18313           ISD::OR, dl, VT,
18314           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18315           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18316     } else {
18317       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18318     }
18319
18320     // r = VSELECT(r, shift(r, 8), a);
18321     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18322     R = SignBitSelect(Amt, M, R);
18323
18324     // a += a
18325     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18326
18327     // r = VSELECT(r, shift(r, 4), a);
18328     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18329     R = SignBitSelect(Amt, M, R);
18330
18331     // a += a
18332     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18333
18334     // r = VSELECT(r, shift(r, 2), a);
18335     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18336     R = SignBitSelect(Amt, M, R);
18337
18338     // a += a
18339     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18340
18341     // return VSELECT(r, shift(r, 1), a);
18342     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18343     R = SignBitSelect(Amt, M, R);
18344     return R;
18345   }
18346
18347   // Decompose 256-bit shifts into smaller 128-bit shifts.
18348   if (VT.is256BitVector()) {
18349     unsigned NumElems = VT.getVectorNumElements();
18350     MVT EltVT = VT.getVectorElementType();
18351     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18352
18353     // Extract the two vectors
18354     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18355     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18356
18357     // Recreate the shift amount vectors
18358     SDValue Amt1, Amt2;
18359     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18360       // Constant shift amount
18361       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18362       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18363       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18364
18365       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18366       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18367     } else {
18368       // Variable shift amount
18369       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18370       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18371     }
18372
18373     // Issue new vector shifts for the smaller types
18374     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18375     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18376
18377     // Concatenate the result back
18378     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18379   }
18380
18381   return SDValue();
18382 }
18383
18384 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18385   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18386   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18387   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18388   // has only one use.
18389   SDNode *N = Op.getNode();
18390   SDValue LHS = N->getOperand(0);
18391   SDValue RHS = N->getOperand(1);
18392   unsigned BaseOp = 0;
18393   unsigned Cond = 0;
18394   SDLoc DL(Op);
18395   switch (Op.getOpcode()) {
18396   default: llvm_unreachable("Unknown ovf instruction!");
18397   case ISD::SADDO:
18398     // A subtract of one will be selected as a INC. Note that INC doesn't
18399     // set CF, so we can't do this for UADDO.
18400     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18401       if (C->isOne()) {
18402         BaseOp = X86ISD::INC;
18403         Cond = X86::COND_O;
18404         break;
18405       }
18406     BaseOp = X86ISD::ADD;
18407     Cond = X86::COND_O;
18408     break;
18409   case ISD::UADDO:
18410     BaseOp = X86ISD::ADD;
18411     Cond = X86::COND_B;
18412     break;
18413   case ISD::SSUBO:
18414     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18415     // set CF, so we can't do this for USUBO.
18416     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18417       if (C->isOne()) {
18418         BaseOp = X86ISD::DEC;
18419         Cond = X86::COND_O;
18420         break;
18421       }
18422     BaseOp = X86ISD::SUB;
18423     Cond = X86::COND_O;
18424     break;
18425   case ISD::USUBO:
18426     BaseOp = X86ISD::SUB;
18427     Cond = X86::COND_B;
18428     break;
18429   case ISD::SMULO:
18430     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18431     Cond = X86::COND_O;
18432     break;
18433   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18434     if (N->getValueType(0) == MVT::i8) {
18435       BaseOp = X86ISD::UMUL8;
18436       Cond = X86::COND_O;
18437       break;
18438     }
18439     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18440                                  MVT::i32);
18441     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18442
18443     SDValue SetCC =
18444       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18445                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18446                   SDValue(Sum.getNode(), 2));
18447
18448     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18449   }
18450   }
18451
18452   // Also sets EFLAGS.
18453   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18454   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18455
18456   SDValue SetCC =
18457     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18458                 DAG.getConstant(Cond, DL, MVT::i32),
18459                 SDValue(Sum.getNode(), 1));
18460
18461   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18462 }
18463
18464 /// Returns true if the operand type is exactly twice the native width, and
18465 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18466 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18467 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18468 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18469   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18470
18471   if (OpWidth == 64)
18472     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18473   else if (OpWidth == 128)
18474     return Subtarget->hasCmpxchg16b();
18475   else
18476     return false;
18477 }
18478
18479 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18480   return needsCmpXchgNb(SI->getValueOperand()->getType());
18481 }
18482
18483 // Note: this turns large loads into lock cmpxchg8b/16b.
18484 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18485 TargetLowering::AtomicExpansionKind
18486 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18487   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18488   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
18489                                                : AtomicExpansionKind::None;
18490 }
18491
18492 TargetLowering::AtomicExpansionKind
18493 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18494   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18495   Type *MemType = AI->getType();
18496
18497   // If the operand is too big, we must see if cmpxchg8/16b is available
18498   // and default to library calls otherwise.
18499   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18500     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
18501                                    : AtomicExpansionKind::None;
18502   }
18503
18504   AtomicRMWInst::BinOp Op = AI->getOperation();
18505   switch (Op) {
18506   default:
18507     llvm_unreachable("Unknown atomic operation");
18508   case AtomicRMWInst::Xchg:
18509   case AtomicRMWInst::Add:
18510   case AtomicRMWInst::Sub:
18511     // It's better to use xadd, xsub or xchg for these in all cases.
18512     return AtomicExpansionKind::None;
18513   case AtomicRMWInst::Or:
18514   case AtomicRMWInst::And:
18515   case AtomicRMWInst::Xor:
18516     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18517     // prefix to a normal instruction for these operations.
18518     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
18519                             : AtomicExpansionKind::None;
18520   case AtomicRMWInst::Nand:
18521   case AtomicRMWInst::Max:
18522   case AtomicRMWInst::Min:
18523   case AtomicRMWInst::UMax:
18524   case AtomicRMWInst::UMin:
18525     // These always require a non-trivial set of data operations on x86. We must
18526     // use a cmpxchg loop.
18527     return AtomicExpansionKind::CmpXChg;
18528   }
18529 }
18530
18531 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18532   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18533   // no-sse2). There isn't any reason to disable it if the target processor
18534   // supports it.
18535   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18536 }
18537
18538 LoadInst *
18539 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18540   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18541   Type *MemType = AI->getType();
18542   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18543   // there is no benefit in turning such RMWs into loads, and it is actually
18544   // harmful as it introduces a mfence.
18545   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18546     return nullptr;
18547
18548   auto Builder = IRBuilder<>(AI);
18549   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18550   auto SynchScope = AI->getSynchScope();
18551   // We must restrict the ordering to avoid generating loads with Release or
18552   // ReleaseAcquire orderings.
18553   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18554   auto Ptr = AI->getPointerOperand();
18555
18556   // Before the load we need a fence. Here is an example lifted from
18557   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18558   // is required:
18559   // Thread 0:
18560   //   x.store(1, relaxed);
18561   //   r1 = y.fetch_add(0, release);
18562   // Thread 1:
18563   //   y.fetch_add(42, acquire);
18564   //   r2 = x.load(relaxed);
18565   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18566   // lowered to just a load without a fence. A mfence flushes the store buffer,
18567   // making the optimization clearly correct.
18568   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18569   // otherwise, we might be able to be more aggressive on relaxed idempotent
18570   // rmw. In practice, they do not look useful, so we don't try to be
18571   // especially clever.
18572   if (SynchScope == SingleThread)
18573     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18574     // the IR level, so we must wrap it in an intrinsic.
18575     return nullptr;
18576
18577   if (!hasMFENCE(*Subtarget))
18578     // FIXME: it might make sense to use a locked operation here but on a
18579     // different cache-line to prevent cache-line bouncing. In practice it
18580     // is probably a small win, and x86 processors without mfence are rare
18581     // enough that we do not bother.
18582     return nullptr;
18583
18584   Function *MFence =
18585       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18586   Builder.CreateCall(MFence, {});
18587
18588   // Finally we can emit the atomic load.
18589   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18590           AI->getType()->getPrimitiveSizeInBits());
18591   Loaded->setAtomic(Order, SynchScope);
18592   AI->replaceAllUsesWith(Loaded);
18593   AI->eraseFromParent();
18594   return Loaded;
18595 }
18596
18597 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18598                                  SelectionDAG &DAG) {
18599   SDLoc dl(Op);
18600   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18601     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18602   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18603     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18604
18605   // The only fence that needs an instruction is a sequentially-consistent
18606   // cross-thread fence.
18607   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18608     if (hasMFENCE(*Subtarget))
18609       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18610
18611     SDValue Chain = Op.getOperand(0);
18612     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18613     SDValue Ops[] = {
18614       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18615       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18616       DAG.getRegister(0, MVT::i32),            // Index
18617       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18618       DAG.getRegister(0, MVT::i32),            // Segment.
18619       Zero,
18620       Chain
18621     };
18622     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18623     return SDValue(Res, 0);
18624   }
18625
18626   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18627   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18628 }
18629
18630 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18631                              SelectionDAG &DAG) {
18632   MVT T = Op.getSimpleValueType();
18633   SDLoc DL(Op);
18634   unsigned Reg = 0;
18635   unsigned size = 0;
18636   switch(T.SimpleTy) {
18637   default: llvm_unreachable("Invalid value type!");
18638   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18639   case MVT::i16: Reg = X86::AX;  size = 2; break;
18640   case MVT::i32: Reg = X86::EAX; size = 4; break;
18641   case MVT::i64:
18642     assert(Subtarget->is64Bit() && "Node not type legal!");
18643     Reg = X86::RAX; size = 8;
18644     break;
18645   }
18646   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18647                                   Op.getOperand(2), SDValue());
18648   SDValue Ops[] = { cpIn.getValue(0),
18649                     Op.getOperand(1),
18650                     Op.getOperand(3),
18651                     DAG.getTargetConstant(size, DL, MVT::i8),
18652                     cpIn.getValue(1) };
18653   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18654   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18655   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18656                                            Ops, T, MMO);
18657
18658   SDValue cpOut =
18659     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18660   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18661                                       MVT::i32, cpOut.getValue(2));
18662   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18663                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18664                                 EFLAGS);
18665
18666   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18667   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18668   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18669   return SDValue();
18670 }
18671
18672 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18673                             SelectionDAG &DAG) {
18674   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18675   MVT DstVT = Op.getSimpleValueType();
18676
18677   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18678     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18679     if (DstVT != MVT::f64)
18680       // This conversion needs to be expanded.
18681       return SDValue();
18682
18683     SDValue InVec = Op->getOperand(0);
18684     SDLoc dl(Op);
18685     unsigned NumElts = SrcVT.getVectorNumElements();
18686     EVT SVT = SrcVT.getVectorElementType();
18687
18688     // Widen the vector in input in the case of MVT::v2i32.
18689     // Example: from MVT::v2i32 to MVT::v4i32.
18690     SmallVector<SDValue, 16> Elts;
18691     for (unsigned i = 0, e = NumElts; i != e; ++i)
18692       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18693                                  DAG.getIntPtrConstant(i, dl)));
18694
18695     // Explicitly mark the extra elements as Undef.
18696     Elts.append(NumElts, DAG.getUNDEF(SVT));
18697
18698     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18699     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18700     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18701     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18702                        DAG.getIntPtrConstant(0, dl));
18703   }
18704
18705   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18706          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18707   assert((DstVT == MVT::i64 ||
18708           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18709          "Unexpected custom BITCAST");
18710   // i64 <=> MMX conversions are Legal.
18711   if (SrcVT==MVT::i64 && DstVT.isVector())
18712     return Op;
18713   if (DstVT==MVT::i64 && SrcVT.isVector())
18714     return Op;
18715   // MMX <=> MMX conversions are Legal.
18716   if (SrcVT.isVector() && DstVT.isVector())
18717     return Op;
18718   // All other conversions need to be expanded.
18719   return SDValue();
18720 }
18721
18722 /// Compute the horizontal sum of bytes in V for the elements of VT.
18723 ///
18724 /// Requires V to be a byte vector and VT to be an integer vector type with
18725 /// wider elements than V's type. The width of the elements of VT determines
18726 /// how many bytes of V are summed horizontally to produce each element of the
18727 /// result.
18728 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18729                                       const X86Subtarget *Subtarget,
18730                                       SelectionDAG &DAG) {
18731   SDLoc DL(V);
18732   MVT ByteVecVT = V.getSimpleValueType();
18733   MVT EltVT = VT.getVectorElementType();
18734   int NumElts = VT.getVectorNumElements();
18735   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18736          "Expected value to have byte element type.");
18737   assert(EltVT != MVT::i8 &&
18738          "Horizontal byte sum only makes sense for wider elements!");
18739   unsigned VecSize = VT.getSizeInBits();
18740   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18741
18742   // PSADBW instruction horizontally add all bytes and leave the result in i64
18743   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18744   if (EltVT == MVT::i64) {
18745     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18746     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18747     return DAG.getBitcast(VT, V);
18748   }
18749
18750   if (EltVT == MVT::i32) {
18751     // We unpack the low half and high half into i32s interleaved with zeros so
18752     // that we can use PSADBW to horizontally sum them. The most useful part of
18753     // this is that it lines up the results of two PSADBW instructions to be
18754     // two v2i64 vectors which concatenated are the 4 population counts. We can
18755     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18756     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18757     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18758     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18759
18760     // Do the horizontal sums into two v2i64s.
18761     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18762     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18763                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18764     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18765                        DAG.getBitcast(ByteVecVT, High), Zeros);
18766
18767     // Merge them together.
18768     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18769     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18770                     DAG.getBitcast(ShortVecVT, Low),
18771                     DAG.getBitcast(ShortVecVT, High));
18772
18773     return DAG.getBitcast(VT, V);
18774   }
18775
18776   // The only element type left is i16.
18777   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18778
18779   // To obtain pop count for each i16 element starting from the pop count for
18780   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18781   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18782   // directly supported.
18783   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18784   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18785   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18786   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18787                   DAG.getBitcast(ByteVecVT, V));
18788   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18789 }
18790
18791 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18792                                         const X86Subtarget *Subtarget,
18793                                         SelectionDAG &DAG) {
18794   MVT VT = Op.getSimpleValueType();
18795   MVT EltVT = VT.getVectorElementType();
18796   unsigned VecSize = VT.getSizeInBits();
18797
18798   // Implement a lookup table in register by using an algorithm based on:
18799   // http://wm.ite.pl/articles/sse-popcount.html
18800   //
18801   // The general idea is that every lower byte nibble in the input vector is an
18802   // index into a in-register pre-computed pop count table. We then split up the
18803   // input vector in two new ones: (1) a vector with only the shifted-right
18804   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18805   // masked out higher ones) for each byte. PSHUB is used separately with both
18806   // to index the in-register table. Next, both are added and the result is a
18807   // i8 vector where each element contains the pop count for input byte.
18808   //
18809   // To obtain the pop count for elements != i8, we follow up with the same
18810   // approach and use additional tricks as described below.
18811   //
18812   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18813                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18814                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18815                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18816
18817   int NumByteElts = VecSize / 8;
18818   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18819   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18820   SmallVector<SDValue, 16> LUTVec;
18821   for (int i = 0; i < NumByteElts; ++i)
18822     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18823   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18824   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18825                                   DAG.getConstant(0x0F, DL, MVT::i8));
18826   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18827
18828   // High nibbles
18829   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18830   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18831   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18832
18833   // Low nibbles
18834   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18835
18836   // The input vector is used as the shuffle mask that index elements into the
18837   // LUT. After counting low and high nibbles, add the vector to obtain the
18838   // final pop count per i8 element.
18839   SDValue HighPopCnt =
18840       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18841   SDValue LowPopCnt =
18842       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18843   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18844
18845   if (EltVT == MVT::i8)
18846     return PopCnt;
18847
18848   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18849 }
18850
18851 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18852                                        const X86Subtarget *Subtarget,
18853                                        SelectionDAG &DAG) {
18854   MVT VT = Op.getSimpleValueType();
18855   assert(VT.is128BitVector() &&
18856          "Only 128-bit vector bitmath lowering supported.");
18857
18858   int VecSize = VT.getSizeInBits();
18859   MVT EltVT = VT.getVectorElementType();
18860   int Len = EltVT.getSizeInBits();
18861
18862   // This is the vectorized version of the "best" algorithm from
18863   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18864   // with a minor tweak to use a series of adds + shifts instead of vector
18865   // multiplications. Implemented for all integer vector types. We only use
18866   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18867   // much faster, even faster than using native popcnt instructions.
18868
18869   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18870     MVT VT = V.getSimpleValueType();
18871     SmallVector<SDValue, 32> Shifters(
18872         VT.getVectorNumElements(),
18873         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18874     return DAG.getNode(OpCode, DL, VT, V,
18875                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18876   };
18877   auto GetMask = [&](SDValue V, APInt Mask) {
18878     MVT VT = V.getSimpleValueType();
18879     SmallVector<SDValue, 32> Masks(
18880         VT.getVectorNumElements(),
18881         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18882     return DAG.getNode(ISD::AND, DL, VT, V,
18883                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18884   };
18885
18886   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18887   // x86, so set the SRL type to have elements at least i16 wide. This is
18888   // correct because all of our SRLs are followed immediately by a mask anyways
18889   // that handles any bits that sneak into the high bits of the byte elements.
18890   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18891
18892   SDValue V = Op;
18893
18894   // v = v - ((v >> 1) & 0x55555555...)
18895   SDValue Srl =
18896       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18897   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18898   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18899
18900   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18901   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18902   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18903   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18904   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18905
18906   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18907   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18908   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18909   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18910
18911   // At this point, V contains the byte-wise population count, and we are
18912   // merely doing a horizontal sum if necessary to get the wider element
18913   // counts.
18914   if (EltVT == MVT::i8)
18915     return V;
18916
18917   return LowerHorizontalByteSum(
18918       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18919       DAG);
18920 }
18921
18922 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18923                                 SelectionDAG &DAG) {
18924   MVT VT = Op.getSimpleValueType();
18925   // FIXME: Need to add AVX-512 support here!
18926   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18927          "Unknown CTPOP type to handle");
18928   SDLoc DL(Op.getNode());
18929   SDValue Op0 = Op.getOperand(0);
18930
18931   if (!Subtarget->hasSSSE3()) {
18932     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18933     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18934     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18935   }
18936
18937   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18938     unsigned NumElems = VT.getVectorNumElements();
18939
18940     // Extract each 128-bit vector, compute pop count and concat the result.
18941     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18942     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18943
18944     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18945                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18946                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18947   }
18948
18949   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18950 }
18951
18952 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18953                           SelectionDAG &DAG) {
18954   assert(Op.getValueType().isVector() &&
18955          "We only do custom lowering for vector population count.");
18956   return LowerVectorCTPOP(Op, Subtarget, DAG);
18957 }
18958
18959 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18960   SDNode *Node = Op.getNode();
18961   SDLoc dl(Node);
18962   EVT T = Node->getValueType(0);
18963   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18964                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18965   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18966                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18967                        Node->getOperand(0),
18968                        Node->getOperand(1), negOp,
18969                        cast<AtomicSDNode>(Node)->getMemOperand(),
18970                        cast<AtomicSDNode>(Node)->getOrdering(),
18971                        cast<AtomicSDNode>(Node)->getSynchScope());
18972 }
18973
18974 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18975   SDNode *Node = Op.getNode();
18976   SDLoc dl(Node);
18977   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18978
18979   // Convert seq_cst store -> xchg
18980   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18981   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18982   //        (The only way to get a 16-byte store is cmpxchg16b)
18983   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18984   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18985       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18986     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18987                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18988                                  Node->getOperand(0),
18989                                  Node->getOperand(1), Node->getOperand(2),
18990                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18991                                  cast<AtomicSDNode>(Node)->getOrdering(),
18992                                  cast<AtomicSDNode>(Node)->getSynchScope());
18993     return Swap.getValue(1);
18994   }
18995   // Other atomic stores have a simple pattern.
18996   return Op;
18997 }
18998
18999 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19000   EVT VT = Op.getNode()->getSimpleValueType(0);
19001
19002   // Let legalize expand this if it isn't a legal type yet.
19003   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19004     return SDValue();
19005
19006   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19007
19008   unsigned Opc;
19009   bool ExtraOp = false;
19010   switch (Op.getOpcode()) {
19011   default: llvm_unreachable("Invalid code");
19012   case ISD::ADDC: Opc = X86ISD::ADD; break;
19013   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19014   case ISD::SUBC: Opc = X86ISD::SUB; break;
19015   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19016   }
19017
19018   if (!ExtraOp)
19019     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19020                        Op.getOperand(1));
19021   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19022                      Op.getOperand(1), Op.getOperand(2));
19023 }
19024
19025 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19026                             SelectionDAG &DAG) {
19027   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19028
19029   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19030   // which returns the values as { float, float } (in XMM0) or
19031   // { double, double } (which is returned in XMM0, XMM1).
19032   SDLoc dl(Op);
19033   SDValue Arg = Op.getOperand(0);
19034   EVT ArgVT = Arg.getValueType();
19035   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19036
19037   TargetLowering::ArgListTy Args;
19038   TargetLowering::ArgListEntry Entry;
19039
19040   Entry.Node = Arg;
19041   Entry.Ty = ArgTy;
19042   Entry.isSExt = false;
19043   Entry.isZExt = false;
19044   Args.push_back(Entry);
19045
19046   bool isF64 = ArgVT == MVT::f64;
19047   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19048   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19049   // the results are returned via SRet in memory.
19050   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19051   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19052   SDValue Callee =
19053       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19054
19055   Type *RetTy = isF64
19056     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19057     : (Type*)VectorType::get(ArgTy, 4);
19058
19059   TargetLowering::CallLoweringInfo CLI(DAG);
19060   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19061     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19062
19063   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19064
19065   if (isF64)
19066     // Returned in xmm0 and xmm1.
19067     return CallResult.first;
19068
19069   // Returned in bits 0:31 and 32:64 xmm0.
19070   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19071                                CallResult.first, DAG.getIntPtrConstant(0, dl));
19072   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19073                                CallResult.first, DAG.getIntPtrConstant(1, dl));
19074   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19075   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19076 }
19077
19078 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19079                              SelectionDAG &DAG) {
19080   assert(Subtarget->hasAVX512() &&
19081          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19082
19083   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19084   EVT VT = N->getValue().getValueType();
19085   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19086   SDLoc dl(Op);
19087
19088   // X86 scatter kills mask register, so its type should be added to
19089   // the list of return values
19090   if (N->getNumValues() == 1) {
19091     SDValue Index = N->getIndex();
19092     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19093         !Index.getValueType().is512BitVector())
19094       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19095
19096     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19097     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19098                       N->getOperand(3), Index };
19099
19100     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19101     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19102     return SDValue(NewScatter.getNode(), 0);
19103   }
19104   return Op;
19105 }
19106
19107 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19108                             SelectionDAG &DAG) {
19109   assert(Subtarget->hasAVX512() &&
19110          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19111
19112   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19113   EVT VT = Op.getValueType();
19114   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19115   SDLoc dl(Op);
19116
19117   SDValue Index = N->getIndex();
19118   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19119       !Index.getValueType().is512BitVector()) {
19120     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19121     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19122                       N->getOperand(3), Index };
19123     DAG.UpdateNodeOperands(N, Ops);
19124   }
19125   return Op;
19126 }
19127
19128 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19129                                                     SelectionDAG &DAG) const {
19130   // TODO: Eventually, the lowering of these nodes should be informed by or
19131   // deferred to the GC strategy for the function in which they appear. For
19132   // now, however, they must be lowered to something. Since they are logically
19133   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19134   // require special handling for these nodes), lower them as literal NOOPs for
19135   // the time being.
19136   SmallVector<SDValue, 2> Ops;
19137
19138   Ops.push_back(Op.getOperand(0));
19139   if (Op->getGluedNode())
19140     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19141
19142   SDLoc OpDL(Op);
19143   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19144   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19145
19146   return NOOP;
19147 }
19148
19149 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19150                                                   SelectionDAG &DAG) const {
19151   // TODO: Eventually, the lowering of these nodes should be informed by or
19152   // deferred to the GC strategy for the function in which they appear. For
19153   // now, however, they must be lowered to something. Since they are logically
19154   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19155   // require special handling for these nodes), lower them as literal NOOPs for
19156   // the time being.
19157   SmallVector<SDValue, 2> Ops;
19158
19159   Ops.push_back(Op.getOperand(0));
19160   if (Op->getGluedNode())
19161     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19162
19163   SDLoc OpDL(Op);
19164   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19165   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19166
19167   return NOOP;
19168 }
19169
19170 /// LowerOperation - Provide custom lowering hooks for some operations.
19171 ///
19172 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19173   switch (Op.getOpcode()) {
19174   default: llvm_unreachable("Should not custom lower this!");
19175   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19176   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19177     return LowerCMP_SWAP(Op, Subtarget, DAG);
19178   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
19179   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19180   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19181   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19182   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19183   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
19184   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19185   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19186   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19187   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19188   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19189   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19190   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19191   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19192   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19193   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19194   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19195   case ISD::SHL_PARTS:
19196   case ISD::SRA_PARTS:
19197   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19198   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19199   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19200   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19201   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19202   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19203   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19204   case ISD::SIGN_EXTEND_VECTOR_INREG:
19205     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19206   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19207   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19208   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19209   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19210   case ISD::FABS:
19211   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19212   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19213   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19214   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19215   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19216   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19217   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19218   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19219   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19220   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19221   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19222   case ISD::INTRINSIC_VOID:
19223   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19224   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19225   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19226   case ISD::FRAME_TO_ARGS_OFFSET:
19227                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19228   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19229   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19230   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19231   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19232   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19233   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19234   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19235   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
19236   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
19237   case ISD::CTTZ:
19238   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
19239   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19240   case ISD::UMUL_LOHI:
19241   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19242   case ISD::SRA:
19243   case ISD::SRL:
19244   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19245   case ISD::SADDO:
19246   case ISD::UADDO:
19247   case ISD::SSUBO:
19248   case ISD::USUBO:
19249   case ISD::SMULO:
19250   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19251   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19252   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19253   case ISD::ADDC:
19254   case ISD::ADDE:
19255   case ISD::SUBC:
19256   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19257   case ISD::ADD:                return LowerADD(Op, DAG);
19258   case ISD::SUB:                return LowerSUB(Op, DAG);
19259   case ISD::SMAX:
19260   case ISD::SMIN:
19261   case ISD::UMAX:
19262   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
19263   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19264   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
19265   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
19266   case ISD::GC_TRANSITION_START:
19267                                 return LowerGC_TRANSITION_START(Op, DAG);
19268   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
19269   }
19270 }
19271
19272 /// ReplaceNodeResults - Replace a node with an illegal result type
19273 /// with a new node built out of custom code.
19274 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19275                                            SmallVectorImpl<SDValue>&Results,
19276                                            SelectionDAG &DAG) const {
19277   SDLoc dl(N);
19278   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19279   switch (N->getOpcode()) {
19280   default:
19281     llvm_unreachable("Do not know how to custom type legalize this operation!");
19282   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19283   case X86ISD::FMINC:
19284   case X86ISD::FMIN:
19285   case X86ISD::FMAXC:
19286   case X86ISD::FMAX: {
19287     EVT VT = N->getValueType(0);
19288     if (VT != MVT::v2f32)
19289       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
19290     SDValue UNDEF = DAG.getUNDEF(VT);
19291     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19292                               N->getOperand(0), UNDEF);
19293     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19294                               N->getOperand(1), UNDEF);
19295     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19296     return;
19297   }
19298   case ISD::SIGN_EXTEND_INREG:
19299   case ISD::ADDC:
19300   case ISD::ADDE:
19301   case ISD::SUBC:
19302   case ISD::SUBE:
19303     // We don't want to expand or promote these.
19304     return;
19305   case ISD::SDIV:
19306   case ISD::UDIV:
19307   case ISD::SREM:
19308   case ISD::UREM:
19309   case ISD::SDIVREM:
19310   case ISD::UDIVREM: {
19311     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19312     Results.push_back(V);
19313     return;
19314   }
19315   case ISD::FP_TO_SINT:
19316   case ISD::FP_TO_UINT: {
19317     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19318
19319     std::pair<SDValue,SDValue> Vals =
19320         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19321     SDValue FIST = Vals.first, StackSlot = Vals.second;
19322     if (FIST.getNode()) {
19323       EVT VT = N->getValueType(0);
19324       // Return a load from the stack slot.
19325       if (StackSlot.getNode())
19326         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19327                                       MachinePointerInfo(),
19328                                       false, false, false, 0));
19329       else
19330         Results.push_back(FIST);
19331     }
19332     return;
19333   }
19334   case ISD::UINT_TO_FP: {
19335     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19336     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19337         N->getValueType(0) != MVT::v2f32)
19338       return;
19339     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19340                                  N->getOperand(0));
19341     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19342                                      MVT::f64);
19343     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19344     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19345                              DAG.getBitcast(MVT::v2i64, VBias));
19346     Or = DAG.getBitcast(MVT::v2f64, Or);
19347     // TODO: Are there any fast-math-flags to propagate here?
19348     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19349     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19350     return;
19351   }
19352   case ISD::FP_ROUND: {
19353     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19354         return;
19355     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19356     Results.push_back(V);
19357     return;
19358   }
19359   case ISD::FP_EXTEND: {
19360     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19361     // No other ValueType for FP_EXTEND should reach this point.
19362     assert(N->getValueType(0) == MVT::v2f32 &&
19363            "Do not know how to legalize this Node");
19364     return;
19365   }
19366   case ISD::INTRINSIC_W_CHAIN: {
19367     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19368     switch (IntNo) {
19369     default : llvm_unreachable("Do not know how to custom type "
19370                                "legalize this intrinsic operation!");
19371     case Intrinsic::x86_rdtsc:
19372       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19373                                      Results);
19374     case Intrinsic::x86_rdtscp:
19375       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19376                                      Results);
19377     case Intrinsic::x86_rdpmc:
19378       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19379     }
19380   }
19381   case ISD::READCYCLECOUNTER: {
19382     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19383                                    Results);
19384   }
19385   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19386     EVT T = N->getValueType(0);
19387     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19388     bool Regs64bit = T == MVT::i128;
19389     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19390     SDValue cpInL, cpInH;
19391     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19392                         DAG.getConstant(0, dl, HalfT));
19393     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19394                         DAG.getConstant(1, dl, HalfT));
19395     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19396                              Regs64bit ? X86::RAX : X86::EAX,
19397                              cpInL, SDValue());
19398     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19399                              Regs64bit ? X86::RDX : X86::EDX,
19400                              cpInH, cpInL.getValue(1));
19401     SDValue swapInL, swapInH;
19402     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19403                           DAG.getConstant(0, dl, HalfT));
19404     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19405                           DAG.getConstant(1, dl, HalfT));
19406     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19407                                Regs64bit ? X86::RBX : X86::EBX,
19408                                swapInL, cpInH.getValue(1));
19409     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19410                                Regs64bit ? X86::RCX : X86::ECX,
19411                                swapInH, swapInL.getValue(1));
19412     SDValue Ops[] = { swapInH.getValue(0),
19413                       N->getOperand(1),
19414                       swapInH.getValue(1) };
19415     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19416     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19417     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19418                                   X86ISD::LCMPXCHG8_DAG;
19419     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19420     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19421                                         Regs64bit ? X86::RAX : X86::EAX,
19422                                         HalfT, Result.getValue(1));
19423     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19424                                         Regs64bit ? X86::RDX : X86::EDX,
19425                                         HalfT, cpOutL.getValue(2));
19426     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19427
19428     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19429                                         MVT::i32, cpOutH.getValue(2));
19430     SDValue Success =
19431         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19432                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19433     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19434
19435     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19436     Results.push_back(Success);
19437     Results.push_back(EFLAGS.getValue(1));
19438     return;
19439   }
19440   case ISD::ATOMIC_SWAP:
19441   case ISD::ATOMIC_LOAD_ADD:
19442   case ISD::ATOMIC_LOAD_SUB:
19443   case ISD::ATOMIC_LOAD_AND:
19444   case ISD::ATOMIC_LOAD_OR:
19445   case ISD::ATOMIC_LOAD_XOR:
19446   case ISD::ATOMIC_LOAD_NAND:
19447   case ISD::ATOMIC_LOAD_MIN:
19448   case ISD::ATOMIC_LOAD_MAX:
19449   case ISD::ATOMIC_LOAD_UMIN:
19450   case ISD::ATOMIC_LOAD_UMAX:
19451   case ISD::ATOMIC_LOAD: {
19452     // Delegate to generic TypeLegalization. Situations we can really handle
19453     // should have already been dealt with by AtomicExpandPass.cpp.
19454     break;
19455   }
19456   case ISD::BITCAST: {
19457     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19458     EVT DstVT = N->getValueType(0);
19459     EVT SrcVT = N->getOperand(0)->getValueType(0);
19460
19461     if (SrcVT != MVT::f64 ||
19462         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19463       return;
19464
19465     unsigned NumElts = DstVT.getVectorNumElements();
19466     EVT SVT = DstVT.getVectorElementType();
19467     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19468     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19469                                    MVT::v2f64, N->getOperand(0));
19470     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19471
19472     if (ExperimentalVectorWideningLegalization) {
19473       // If we are legalizing vectors by widening, we already have the desired
19474       // legal vector type, just return it.
19475       Results.push_back(ToVecInt);
19476       return;
19477     }
19478
19479     SmallVector<SDValue, 8> Elts;
19480     for (unsigned i = 0, e = NumElts; i != e; ++i)
19481       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19482                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19483
19484     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19485   }
19486   }
19487 }
19488
19489 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19490   switch ((X86ISD::NodeType)Opcode) {
19491   case X86ISD::FIRST_NUMBER:       break;
19492   case X86ISD::BSF:                return "X86ISD::BSF";
19493   case X86ISD::BSR:                return "X86ISD::BSR";
19494   case X86ISD::SHLD:               return "X86ISD::SHLD";
19495   case X86ISD::SHRD:               return "X86ISD::SHRD";
19496   case X86ISD::FAND:               return "X86ISD::FAND";
19497   case X86ISD::FANDN:              return "X86ISD::FANDN";
19498   case X86ISD::FOR:                return "X86ISD::FOR";
19499   case X86ISD::FXOR:               return "X86ISD::FXOR";
19500   case X86ISD::FILD:               return "X86ISD::FILD";
19501   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19502   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19503   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19504   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19505   case X86ISD::FLD:                return "X86ISD::FLD";
19506   case X86ISD::FST:                return "X86ISD::FST";
19507   case X86ISD::CALL:               return "X86ISD::CALL";
19508   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19509   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19510   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19511   case X86ISD::BT:                 return "X86ISD::BT";
19512   case X86ISD::CMP:                return "X86ISD::CMP";
19513   case X86ISD::COMI:               return "X86ISD::COMI";
19514   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19515   case X86ISD::CMPM:               return "X86ISD::CMPM";
19516   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19517   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19518   case X86ISD::SETCC:              return "X86ISD::SETCC";
19519   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19520   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19521   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19522   case X86ISD::CMOV:               return "X86ISD::CMOV";
19523   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19524   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19525   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19526   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19527   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19528   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19529   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19530   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19531   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19532   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19533   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19534   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19535   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19536   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19537   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19538   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19539   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19540   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19541   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19542   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19543   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19544   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19545   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19546   case X86ISD::HADD:               return "X86ISD::HADD";
19547   case X86ISD::HSUB:               return "X86ISD::HSUB";
19548   case X86ISD::FHADD:              return "X86ISD::FHADD";
19549   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19550   case X86ISD::ABS:                return "X86ISD::ABS";
19551   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
19552   case X86ISD::FMAX:               return "X86ISD::FMAX";
19553   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19554   case X86ISD::FMIN:               return "X86ISD::FMIN";
19555   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19556   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19557   case X86ISD::FMINC:              return "X86ISD::FMINC";
19558   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19559   case X86ISD::FRCP:               return "X86ISD::FRCP";
19560   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19561   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19562   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19563   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19564   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19565   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19566   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19567   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19568   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19569   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19570   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19571   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19572   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19573   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19574   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19575   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19576   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19577   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19578   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19579   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19580   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19581   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19582   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19583   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19584   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19585   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19586   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19587   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19588   case X86ISD::VSHL:               return "X86ISD::VSHL";
19589   case X86ISD::VSRL:               return "X86ISD::VSRL";
19590   case X86ISD::VSRA:               return "X86ISD::VSRA";
19591   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19592   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19593   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19594   case X86ISD::CMPP:               return "X86ISD::CMPP";
19595   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19596   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19597   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19598   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19599   case X86ISD::ADD:                return "X86ISD::ADD";
19600   case X86ISD::SUB:                return "X86ISD::SUB";
19601   case X86ISD::ADC:                return "X86ISD::ADC";
19602   case X86ISD::SBB:                return "X86ISD::SBB";
19603   case X86ISD::SMUL:               return "X86ISD::SMUL";
19604   case X86ISD::UMUL:               return "X86ISD::UMUL";
19605   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19606   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19607   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19608   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19609   case X86ISD::INC:                return "X86ISD::INC";
19610   case X86ISD::DEC:                return "X86ISD::DEC";
19611   case X86ISD::OR:                 return "X86ISD::OR";
19612   case X86ISD::XOR:                return "X86ISD::XOR";
19613   case X86ISD::AND:                return "X86ISD::AND";
19614   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19615   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19616   case X86ISD::PTEST:              return "X86ISD::PTEST";
19617   case X86ISD::TESTP:              return "X86ISD::TESTP";
19618   case X86ISD::TESTM:              return "X86ISD::TESTM";
19619   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19620   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19621   case X86ISD::KTEST:              return "X86ISD::KTEST";
19622   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19623   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19624   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19625   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19626   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19627   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19628   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19629   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19630   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19631   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19632   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19633   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19634   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19635   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19636   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19637   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19638   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19639   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19640   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19641   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19642   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19643   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19644   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19645   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19646   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19647   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19648   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19649   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19650   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19651   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19652   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19653   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19654   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19655   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19656   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19657   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19658   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
19659   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19660   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19661   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19662   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19663   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19664   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19665   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19666   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19667   case X86ISD::SAHF:               return "X86ISD::SAHF";
19668   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19669   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19670   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19671   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19672   case X86ISD::FMADD:              return "X86ISD::FMADD";
19673   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19674   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19675   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19676   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19677   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19678   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19679   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19680   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19681   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19682   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19683   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19684   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19685   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19686   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
19687   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19688   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19689   case X86ISD::XTEST:              return "X86ISD::XTEST";
19690   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19691   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19692   case X86ISD::SELECT:             return "X86ISD::SELECT";
19693   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19694   case X86ISD::RCP28:              return "X86ISD::RCP28";
19695   case X86ISD::EXP2:               return "X86ISD::EXP2";
19696   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19697   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19698   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19699   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19700   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19701   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19702   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19703   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19704   case X86ISD::ADDS:               return "X86ISD::ADDS";
19705   case X86ISD::SUBS:               return "X86ISD::SUBS";
19706   case X86ISD::AVG:                return "X86ISD::AVG";
19707   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19708   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19709   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19710   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19711   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19712   }
19713   return nullptr;
19714 }
19715
19716 // isLegalAddressingMode - Return true if the addressing mode represented
19717 // by AM is legal for this target, for a load/store of the specified type.
19718 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19719                                               const AddrMode &AM, Type *Ty,
19720                                               unsigned AS) const {
19721   // X86 supports extremely general addressing modes.
19722   CodeModel::Model M = getTargetMachine().getCodeModel();
19723   Reloc::Model R = getTargetMachine().getRelocationModel();
19724
19725   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19726   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19727     return false;
19728
19729   if (AM.BaseGV) {
19730     unsigned GVFlags =
19731       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19732
19733     // If a reference to this global requires an extra load, we can't fold it.
19734     if (isGlobalStubReference(GVFlags))
19735       return false;
19736
19737     // If BaseGV requires a register for the PIC base, we cannot also have a
19738     // BaseReg specified.
19739     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19740       return false;
19741
19742     // If lower 4G is not available, then we must use rip-relative addressing.
19743     if ((M != CodeModel::Small || R != Reloc::Static) &&
19744         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19745       return false;
19746   }
19747
19748   switch (AM.Scale) {
19749   case 0:
19750   case 1:
19751   case 2:
19752   case 4:
19753   case 8:
19754     // These scales always work.
19755     break;
19756   case 3:
19757   case 5:
19758   case 9:
19759     // These scales are formed with basereg+scalereg.  Only accept if there is
19760     // no basereg yet.
19761     if (AM.HasBaseReg)
19762       return false;
19763     break;
19764   default:  // Other stuff never works.
19765     return false;
19766   }
19767
19768   return true;
19769 }
19770
19771 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19772   unsigned Bits = Ty->getScalarSizeInBits();
19773
19774   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19775   // particularly cheaper than those without.
19776   if (Bits == 8)
19777     return false;
19778
19779   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19780   // variable shifts just as cheap as scalar ones.
19781   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19782     return false;
19783
19784   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19785   // fully general vector.
19786   return true;
19787 }
19788
19789 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19790   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19791     return false;
19792   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19793   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19794   return NumBits1 > NumBits2;
19795 }
19796
19797 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19798   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19799     return false;
19800
19801   if (!isTypeLegal(EVT::getEVT(Ty1)))
19802     return false;
19803
19804   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19805
19806   // Assuming the caller doesn't have a zeroext or signext return parameter,
19807   // truncation all the way down to i1 is valid.
19808   return true;
19809 }
19810
19811 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19812   return isInt<32>(Imm);
19813 }
19814
19815 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19816   // Can also use sub to handle negated immediates.
19817   return isInt<32>(Imm);
19818 }
19819
19820 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19821   if (!VT1.isInteger() || !VT2.isInteger())
19822     return false;
19823   unsigned NumBits1 = VT1.getSizeInBits();
19824   unsigned NumBits2 = VT2.getSizeInBits();
19825   return NumBits1 > NumBits2;
19826 }
19827
19828 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19829   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19830   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19831 }
19832
19833 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19834   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19835   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19836 }
19837
19838 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19839   EVT VT1 = Val.getValueType();
19840   if (isZExtFree(VT1, VT2))
19841     return true;
19842
19843   if (Val.getOpcode() != ISD::LOAD)
19844     return false;
19845
19846   if (!VT1.isSimple() || !VT1.isInteger() ||
19847       !VT2.isSimple() || !VT2.isInteger())
19848     return false;
19849
19850   switch (VT1.getSimpleVT().SimpleTy) {
19851   default: break;
19852   case MVT::i8:
19853   case MVT::i16:
19854   case MVT::i32:
19855     // X86 has 8, 16, and 32-bit zero-extending loads.
19856     return true;
19857   }
19858
19859   return false;
19860 }
19861
19862 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19863
19864 bool
19865 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19866   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19867     return false;
19868
19869   VT = VT.getScalarType();
19870
19871   if (!VT.isSimple())
19872     return false;
19873
19874   switch (VT.getSimpleVT().SimpleTy) {
19875   case MVT::f32:
19876   case MVT::f64:
19877     return true;
19878   default:
19879     break;
19880   }
19881
19882   return false;
19883 }
19884
19885 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19886   // i16 instructions are longer (0x66 prefix) and potentially slower.
19887   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19888 }
19889
19890 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19891 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19892 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19893 /// are assumed to be legal.
19894 bool
19895 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19896                                       EVT VT) const {
19897   if (!VT.isSimple())
19898     return false;
19899
19900   // Not for i1 vectors
19901   if (VT.getScalarType() == MVT::i1)
19902     return false;
19903
19904   // Very little shuffling can be done for 64-bit vectors right now.
19905   if (VT.getSizeInBits() == 64)
19906     return false;
19907
19908   // We only care that the types being shuffled are legal. The lowering can
19909   // handle any possible shuffle mask that results.
19910   return isTypeLegal(VT.getSimpleVT());
19911 }
19912
19913 bool
19914 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19915                                           EVT VT) const {
19916   // Just delegate to the generic legality, clear masks aren't special.
19917   return isShuffleMaskLegal(Mask, VT);
19918 }
19919
19920 //===----------------------------------------------------------------------===//
19921 //                           X86 Scheduler Hooks
19922 //===----------------------------------------------------------------------===//
19923
19924 /// Utility function to emit xbegin specifying the start of an RTM region.
19925 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19926                                      const TargetInstrInfo *TII) {
19927   DebugLoc DL = MI->getDebugLoc();
19928
19929   const BasicBlock *BB = MBB->getBasicBlock();
19930   MachineFunction::iterator I = MBB;
19931   ++I;
19932
19933   // For the v = xbegin(), we generate
19934   //
19935   // thisMBB:
19936   //  xbegin sinkMBB
19937   //
19938   // mainMBB:
19939   //  eax = -1
19940   //
19941   // sinkMBB:
19942   //  v = eax
19943
19944   MachineBasicBlock *thisMBB = MBB;
19945   MachineFunction *MF = MBB->getParent();
19946   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19947   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19948   MF->insert(I, mainMBB);
19949   MF->insert(I, sinkMBB);
19950
19951   // Transfer the remainder of BB and its successor edges to sinkMBB.
19952   sinkMBB->splice(sinkMBB->begin(), MBB,
19953                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19954   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19955
19956   // thisMBB:
19957   //  xbegin sinkMBB
19958   //  # fallthrough to mainMBB
19959   //  # abortion to sinkMBB
19960   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19961   thisMBB->addSuccessor(mainMBB);
19962   thisMBB->addSuccessor(sinkMBB);
19963
19964   // mainMBB:
19965   //  EAX = -1
19966   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19967   mainMBB->addSuccessor(sinkMBB);
19968
19969   // sinkMBB:
19970   // EAX is live into the sinkMBB
19971   sinkMBB->addLiveIn(X86::EAX);
19972   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19973           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19974     .addReg(X86::EAX);
19975
19976   MI->eraseFromParent();
19977   return sinkMBB;
19978 }
19979
19980 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19981 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19982 // in the .td file.
19983 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19984                                        const TargetInstrInfo *TII) {
19985   unsigned Opc;
19986   switch (MI->getOpcode()) {
19987   default: llvm_unreachable("illegal opcode!");
19988   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19989   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19990   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19991   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19992   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19993   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19994   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19995   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19996   }
19997
19998   DebugLoc dl = MI->getDebugLoc();
19999   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20000
20001   unsigned NumArgs = MI->getNumOperands();
20002   for (unsigned i = 1; i < NumArgs; ++i) {
20003     MachineOperand &Op = MI->getOperand(i);
20004     if (!(Op.isReg() && Op.isImplicit()))
20005       MIB.addOperand(Op);
20006   }
20007   if (MI->hasOneMemOperand())
20008     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20009
20010   BuildMI(*BB, MI, dl,
20011     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20012     .addReg(X86::XMM0);
20013
20014   MI->eraseFromParent();
20015   return BB;
20016 }
20017
20018 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20019 // defs in an instruction pattern
20020 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20021                                        const TargetInstrInfo *TII) {
20022   unsigned Opc;
20023   switch (MI->getOpcode()) {
20024   default: llvm_unreachable("illegal opcode!");
20025   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
20026   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20027   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
20028   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20029   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
20030   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20031   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
20032   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20033   }
20034
20035   DebugLoc dl = MI->getDebugLoc();
20036   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20037
20038   unsigned NumArgs = MI->getNumOperands(); // remove the results
20039   for (unsigned i = 1; i < NumArgs; ++i) {
20040     MachineOperand &Op = MI->getOperand(i);
20041     if (!(Op.isReg() && Op.isImplicit()))
20042       MIB.addOperand(Op);
20043   }
20044   if (MI->hasOneMemOperand())
20045     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20046
20047   BuildMI(*BB, MI, dl,
20048     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20049     .addReg(X86::ECX);
20050
20051   MI->eraseFromParent();
20052   return BB;
20053 }
20054
20055 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20056                                       const X86Subtarget *Subtarget) {
20057   DebugLoc dl = MI->getDebugLoc();
20058   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20059   // Address into RAX/EAX, other two args into ECX, EDX.
20060   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20061   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20062   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20063   for (int i = 0; i < X86::AddrNumOperands; ++i)
20064     MIB.addOperand(MI->getOperand(i));
20065
20066   unsigned ValOps = X86::AddrNumOperands;
20067   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20068     .addReg(MI->getOperand(ValOps).getReg());
20069   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20070     .addReg(MI->getOperand(ValOps+1).getReg());
20071
20072   // The instruction doesn't actually take any operands though.
20073   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20074
20075   MI->eraseFromParent(); // The pseudo is gone now.
20076   return BB;
20077 }
20078
20079 MachineBasicBlock *
20080 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20081                                                  MachineBasicBlock *MBB) const {
20082   // Emit va_arg instruction on X86-64.
20083
20084   // Operands to this pseudo-instruction:
20085   // 0  ) Output        : destination address (reg)
20086   // 1-5) Input         : va_list address (addr, i64mem)
20087   // 6  ) ArgSize       : Size (in bytes) of vararg type
20088   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20089   // 8  ) Align         : Alignment of type
20090   // 9  ) EFLAGS (implicit-def)
20091
20092   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20093   static_assert(X86::AddrNumOperands == 5,
20094                 "VAARG_64 assumes 5 address operands");
20095
20096   unsigned DestReg = MI->getOperand(0).getReg();
20097   MachineOperand &Base = MI->getOperand(1);
20098   MachineOperand &Scale = MI->getOperand(2);
20099   MachineOperand &Index = MI->getOperand(3);
20100   MachineOperand &Disp = MI->getOperand(4);
20101   MachineOperand &Segment = MI->getOperand(5);
20102   unsigned ArgSize = MI->getOperand(6).getImm();
20103   unsigned ArgMode = MI->getOperand(7).getImm();
20104   unsigned Align = MI->getOperand(8).getImm();
20105
20106   // Memory Reference
20107   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20108   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20109   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20110
20111   // Machine Information
20112   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20113   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20114   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20115   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20116   DebugLoc DL = MI->getDebugLoc();
20117
20118   // struct va_list {
20119   //   i32   gp_offset
20120   //   i32   fp_offset
20121   //   i64   overflow_area (address)
20122   //   i64   reg_save_area (address)
20123   // }
20124   // sizeof(va_list) = 24
20125   // alignment(va_list) = 8
20126
20127   unsigned TotalNumIntRegs = 6;
20128   unsigned TotalNumXMMRegs = 8;
20129   bool UseGPOffset = (ArgMode == 1);
20130   bool UseFPOffset = (ArgMode == 2);
20131   unsigned MaxOffset = TotalNumIntRegs * 8 +
20132                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20133
20134   /* Align ArgSize to a multiple of 8 */
20135   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20136   bool NeedsAlign = (Align > 8);
20137
20138   MachineBasicBlock *thisMBB = MBB;
20139   MachineBasicBlock *overflowMBB;
20140   MachineBasicBlock *offsetMBB;
20141   MachineBasicBlock *endMBB;
20142
20143   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20144   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20145   unsigned OffsetReg = 0;
20146
20147   if (!UseGPOffset && !UseFPOffset) {
20148     // If we only pull from the overflow region, we don't create a branch.
20149     // We don't need to alter control flow.
20150     OffsetDestReg = 0; // unused
20151     OverflowDestReg = DestReg;
20152
20153     offsetMBB = nullptr;
20154     overflowMBB = thisMBB;
20155     endMBB = thisMBB;
20156   } else {
20157     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20158     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20159     // If not, pull from overflow_area. (branch to overflowMBB)
20160     //
20161     //       thisMBB
20162     //         |     .
20163     //         |        .
20164     //     offsetMBB   overflowMBB
20165     //         |        .
20166     //         |     .
20167     //        endMBB
20168
20169     // Registers for the PHI in endMBB
20170     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20171     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20172
20173     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20174     MachineFunction *MF = MBB->getParent();
20175     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20176     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20177     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20178
20179     MachineFunction::iterator MBBIter = MBB;
20180     ++MBBIter;
20181
20182     // Insert the new basic blocks
20183     MF->insert(MBBIter, offsetMBB);
20184     MF->insert(MBBIter, overflowMBB);
20185     MF->insert(MBBIter, endMBB);
20186
20187     // Transfer the remainder of MBB and its successor edges to endMBB.
20188     endMBB->splice(endMBB->begin(), thisMBB,
20189                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20190     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20191
20192     // Make offsetMBB and overflowMBB successors of thisMBB
20193     thisMBB->addSuccessor(offsetMBB);
20194     thisMBB->addSuccessor(overflowMBB);
20195
20196     // endMBB is a successor of both offsetMBB and overflowMBB
20197     offsetMBB->addSuccessor(endMBB);
20198     overflowMBB->addSuccessor(endMBB);
20199
20200     // Load the offset value into a register
20201     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20202     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20203       .addOperand(Base)
20204       .addOperand(Scale)
20205       .addOperand(Index)
20206       .addDisp(Disp, UseFPOffset ? 4 : 0)
20207       .addOperand(Segment)
20208       .setMemRefs(MMOBegin, MMOEnd);
20209
20210     // Check if there is enough room left to pull this argument.
20211     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20212       .addReg(OffsetReg)
20213       .addImm(MaxOffset + 8 - ArgSizeA8);
20214
20215     // Branch to "overflowMBB" if offset >= max
20216     // Fall through to "offsetMBB" otherwise
20217     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20218       .addMBB(overflowMBB);
20219   }
20220
20221   // In offsetMBB, emit code to use the reg_save_area.
20222   if (offsetMBB) {
20223     assert(OffsetReg != 0);
20224
20225     // Read the reg_save_area address.
20226     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20227     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20228       .addOperand(Base)
20229       .addOperand(Scale)
20230       .addOperand(Index)
20231       .addDisp(Disp, 16)
20232       .addOperand(Segment)
20233       .setMemRefs(MMOBegin, MMOEnd);
20234
20235     // Zero-extend the offset
20236     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20237       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20238         .addImm(0)
20239         .addReg(OffsetReg)
20240         .addImm(X86::sub_32bit);
20241
20242     // Add the offset to the reg_save_area to get the final address.
20243     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20244       .addReg(OffsetReg64)
20245       .addReg(RegSaveReg);
20246
20247     // Compute the offset for the next argument
20248     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20249     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20250       .addReg(OffsetReg)
20251       .addImm(UseFPOffset ? 16 : 8);
20252
20253     // Store it back into the va_list.
20254     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20255       .addOperand(Base)
20256       .addOperand(Scale)
20257       .addOperand(Index)
20258       .addDisp(Disp, UseFPOffset ? 4 : 0)
20259       .addOperand(Segment)
20260       .addReg(NextOffsetReg)
20261       .setMemRefs(MMOBegin, MMOEnd);
20262
20263     // Jump to endMBB
20264     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20265       .addMBB(endMBB);
20266   }
20267
20268   //
20269   // Emit code to use overflow area
20270   //
20271
20272   // Load the overflow_area address into a register.
20273   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20274   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20275     .addOperand(Base)
20276     .addOperand(Scale)
20277     .addOperand(Index)
20278     .addDisp(Disp, 8)
20279     .addOperand(Segment)
20280     .setMemRefs(MMOBegin, MMOEnd);
20281
20282   // If we need to align it, do so. Otherwise, just copy the address
20283   // to OverflowDestReg.
20284   if (NeedsAlign) {
20285     // Align the overflow address
20286     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20287     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20288
20289     // aligned_addr = (addr + (align-1)) & ~(align-1)
20290     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20291       .addReg(OverflowAddrReg)
20292       .addImm(Align-1);
20293
20294     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20295       .addReg(TmpReg)
20296       .addImm(~(uint64_t)(Align-1));
20297   } else {
20298     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20299       .addReg(OverflowAddrReg);
20300   }
20301
20302   // Compute the next overflow address after this argument.
20303   // (the overflow address should be kept 8-byte aligned)
20304   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20305   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20306     .addReg(OverflowDestReg)
20307     .addImm(ArgSizeA8);
20308
20309   // Store the new overflow address.
20310   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20311     .addOperand(Base)
20312     .addOperand(Scale)
20313     .addOperand(Index)
20314     .addDisp(Disp, 8)
20315     .addOperand(Segment)
20316     .addReg(NextAddrReg)
20317     .setMemRefs(MMOBegin, MMOEnd);
20318
20319   // If we branched, emit the PHI to the front of endMBB.
20320   if (offsetMBB) {
20321     BuildMI(*endMBB, endMBB->begin(), DL,
20322             TII->get(X86::PHI), DestReg)
20323       .addReg(OffsetDestReg).addMBB(offsetMBB)
20324       .addReg(OverflowDestReg).addMBB(overflowMBB);
20325   }
20326
20327   // Erase the pseudo instruction
20328   MI->eraseFromParent();
20329
20330   return endMBB;
20331 }
20332
20333 MachineBasicBlock *
20334 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20335                                                  MachineInstr *MI,
20336                                                  MachineBasicBlock *MBB) const {
20337   // Emit code to save XMM registers to the stack. The ABI says that the
20338   // number of registers to save is given in %al, so it's theoretically
20339   // possible to do an indirect jump trick to avoid saving all of them,
20340   // however this code takes a simpler approach and just executes all
20341   // of the stores if %al is non-zero. It's less code, and it's probably
20342   // easier on the hardware branch predictor, and stores aren't all that
20343   // expensive anyway.
20344
20345   // Create the new basic blocks. One block contains all the XMM stores,
20346   // and one block is the final destination regardless of whether any
20347   // stores were performed.
20348   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20349   MachineFunction *F = MBB->getParent();
20350   MachineFunction::iterator MBBIter = MBB;
20351   ++MBBIter;
20352   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20353   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20354   F->insert(MBBIter, XMMSaveMBB);
20355   F->insert(MBBIter, EndMBB);
20356
20357   // Transfer the remainder of MBB and its successor edges to EndMBB.
20358   EndMBB->splice(EndMBB->begin(), MBB,
20359                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20360   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20361
20362   // The original block will now fall through to the XMM save block.
20363   MBB->addSuccessor(XMMSaveMBB);
20364   // The XMMSaveMBB will fall through to the end block.
20365   XMMSaveMBB->addSuccessor(EndMBB);
20366
20367   // Now add the instructions.
20368   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20369   DebugLoc DL = MI->getDebugLoc();
20370
20371   unsigned CountReg = MI->getOperand(0).getReg();
20372   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20373   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20374
20375   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20376     // If %al is 0, branch around the XMM save block.
20377     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20378     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20379     MBB->addSuccessor(EndMBB);
20380   }
20381
20382   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20383   // that was just emitted, but clearly shouldn't be "saved".
20384   assert((MI->getNumOperands() <= 3 ||
20385           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20386           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20387          && "Expected last argument to be EFLAGS");
20388   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20389   // In the XMM save block, save all the XMM argument registers.
20390   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20391     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20392     MachineMemOperand *MMO = F->getMachineMemOperand(
20393         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20394         MachineMemOperand::MOStore,
20395         /*Size=*/16, /*Align=*/16);
20396     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20397       .addFrameIndex(RegSaveFrameIndex)
20398       .addImm(/*Scale=*/1)
20399       .addReg(/*IndexReg=*/0)
20400       .addImm(/*Disp=*/Offset)
20401       .addReg(/*Segment=*/0)
20402       .addReg(MI->getOperand(i).getReg())
20403       .addMemOperand(MMO);
20404   }
20405
20406   MI->eraseFromParent();   // The pseudo instruction is gone now.
20407
20408   return EndMBB;
20409 }
20410
20411 // The EFLAGS operand of SelectItr might be missing a kill marker
20412 // because there were multiple uses of EFLAGS, and ISel didn't know
20413 // which to mark. Figure out whether SelectItr should have had a
20414 // kill marker, and set it if it should. Returns the correct kill
20415 // marker value.
20416 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20417                                      MachineBasicBlock* BB,
20418                                      const TargetRegisterInfo* TRI) {
20419   // Scan forward through BB for a use/def of EFLAGS.
20420   MachineBasicBlock::iterator miI(std::next(SelectItr));
20421   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20422     const MachineInstr& mi = *miI;
20423     if (mi.readsRegister(X86::EFLAGS))
20424       return false;
20425     if (mi.definesRegister(X86::EFLAGS))
20426       break; // Should have kill-flag - update below.
20427   }
20428
20429   // If we hit the end of the block, check whether EFLAGS is live into a
20430   // successor.
20431   if (miI == BB->end()) {
20432     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20433                                           sEnd = BB->succ_end();
20434          sItr != sEnd; ++sItr) {
20435       MachineBasicBlock* succ = *sItr;
20436       if (succ->isLiveIn(X86::EFLAGS))
20437         return false;
20438     }
20439   }
20440
20441   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20442   // out. SelectMI should have a kill flag on EFLAGS.
20443   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20444   return true;
20445 }
20446
20447 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20448 // together with other CMOV pseudo-opcodes into a single basic-block with
20449 // conditional jump around it.
20450 static bool isCMOVPseudo(MachineInstr *MI) {
20451   switch (MI->getOpcode()) {
20452   case X86::CMOV_FR32:
20453   case X86::CMOV_FR64:
20454   case X86::CMOV_GR8:
20455   case X86::CMOV_GR16:
20456   case X86::CMOV_GR32:
20457   case X86::CMOV_RFP32:
20458   case X86::CMOV_RFP64:
20459   case X86::CMOV_RFP80:
20460   case X86::CMOV_V2F64:
20461   case X86::CMOV_V2I64:
20462   case X86::CMOV_V4F32:
20463   case X86::CMOV_V4F64:
20464   case X86::CMOV_V4I64:
20465   case X86::CMOV_V16F32:
20466   case X86::CMOV_V8F32:
20467   case X86::CMOV_V8F64:
20468   case X86::CMOV_V8I64:
20469   case X86::CMOV_V8I1:
20470   case X86::CMOV_V16I1:
20471   case X86::CMOV_V32I1:
20472   case X86::CMOV_V64I1:
20473     return true;
20474
20475   default:
20476     return false;
20477   }
20478 }
20479
20480 MachineBasicBlock *
20481 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20482                                      MachineBasicBlock *BB) const {
20483   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20484   DebugLoc DL = MI->getDebugLoc();
20485
20486   // To "insert" a SELECT_CC instruction, we actually have to insert the
20487   // diamond control-flow pattern.  The incoming instruction knows the
20488   // destination vreg to set, the condition code register to branch on, the
20489   // true/false values to select between, and a branch opcode to use.
20490   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20491   MachineFunction::iterator It = BB;
20492   ++It;
20493
20494   //  thisMBB:
20495   //  ...
20496   //   TrueVal = ...
20497   //   cmpTY ccX, r1, r2
20498   //   bCC copy1MBB
20499   //   fallthrough --> copy0MBB
20500   MachineBasicBlock *thisMBB = BB;
20501   MachineFunction *F = BB->getParent();
20502
20503   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20504   // as described above, by inserting a BB, and then making a PHI at the join
20505   // point to select the true and false operands of the CMOV in the PHI.
20506   //
20507   // The code also handles two different cases of multiple CMOV opcodes
20508   // in a row.
20509   //
20510   // Case 1:
20511   // In this case, there are multiple CMOVs in a row, all which are based on
20512   // the same condition setting (or the exact opposite condition setting).
20513   // In this case we can lower all the CMOVs using a single inserted BB, and
20514   // then make a number of PHIs at the join point to model the CMOVs. The only
20515   // trickiness here, is that in a case like:
20516   //
20517   // t2 = CMOV cond1 t1, f1
20518   // t3 = CMOV cond1 t2, f2
20519   //
20520   // when rewriting this into PHIs, we have to perform some renaming on the
20521   // temps since you cannot have a PHI operand refer to a PHI result earlier
20522   // in the same block.  The "simple" but wrong lowering would be:
20523   //
20524   // t2 = PHI t1(BB1), f1(BB2)
20525   // t3 = PHI t2(BB1), f2(BB2)
20526   //
20527   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20528   // renaming is to note that on the path through BB1, t2 is really just a
20529   // copy of t1, and do that renaming, properly generating:
20530   //
20531   // t2 = PHI t1(BB1), f1(BB2)
20532   // t3 = PHI t1(BB1), f2(BB2)
20533   //
20534   // Case 2, we lower cascaded CMOVs such as
20535   //
20536   //   (CMOV (CMOV F, T, cc1), T, cc2)
20537   //
20538   // to two successives branches.  For that, we look for another CMOV as the
20539   // following instruction.
20540   //
20541   // Without this, we would add a PHI between the two jumps, which ends up
20542   // creating a few copies all around. For instance, for
20543   //
20544   //    (sitofp (zext (fcmp une)))
20545   //
20546   // we would generate:
20547   //
20548   //         ucomiss %xmm1, %xmm0
20549   //         movss  <1.0f>, %xmm0
20550   //         movaps  %xmm0, %xmm1
20551   //         jne     .LBB5_2
20552   //         xorps   %xmm1, %xmm1
20553   // .LBB5_2:
20554   //         jp      .LBB5_4
20555   //         movaps  %xmm1, %xmm0
20556   // .LBB5_4:
20557   //         retq
20558   //
20559   // because this custom-inserter would have generated:
20560   //
20561   //   A
20562   //   | \
20563   //   |  B
20564   //   | /
20565   //   C
20566   //   | \
20567   //   |  D
20568   //   | /
20569   //   E
20570   //
20571   // A: X = ...; Y = ...
20572   // B: empty
20573   // C: Z = PHI [X, A], [Y, B]
20574   // D: empty
20575   // E: PHI [X, C], [Z, D]
20576   //
20577   // If we lower both CMOVs in a single step, we can instead generate:
20578   //
20579   //   A
20580   //   | \
20581   //   |  C
20582   //   | /|
20583   //   |/ |
20584   //   |  |
20585   //   |  D
20586   //   | /
20587   //   E
20588   //
20589   // A: X = ...; Y = ...
20590   // D: empty
20591   // E: PHI [X, A], [X, C], [Y, D]
20592   //
20593   // Which, in our sitofp/fcmp example, gives us something like:
20594   //
20595   //         ucomiss %xmm1, %xmm0
20596   //         movss  <1.0f>, %xmm0
20597   //         jne     .LBB5_4
20598   //         jp      .LBB5_4
20599   //         xorps   %xmm0, %xmm0
20600   // .LBB5_4:
20601   //         retq
20602   //
20603   MachineInstr *CascadedCMOV = nullptr;
20604   MachineInstr *LastCMOV = MI;
20605   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20606   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20607   MachineBasicBlock::iterator NextMIIt =
20608       std::next(MachineBasicBlock::iterator(MI));
20609
20610   // Check for case 1, where there are multiple CMOVs with the same condition
20611   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
20612   // number of jumps the most.
20613
20614   if (isCMOVPseudo(MI)) {
20615     // See if we have a string of CMOVS with the same condition.
20616     while (NextMIIt != BB->end() &&
20617            isCMOVPseudo(NextMIIt) &&
20618            (NextMIIt->getOperand(3).getImm() == CC ||
20619             NextMIIt->getOperand(3).getImm() == OppCC)) {
20620       LastCMOV = &*NextMIIt;
20621       ++NextMIIt;
20622     }
20623   }
20624
20625   // This checks for case 2, but only do this if we didn't already find
20626   // case 1, as indicated by LastCMOV == MI.
20627   if (LastCMOV == MI &&
20628       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20629       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20630       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20631     CascadedCMOV = &*NextMIIt;
20632   }
20633
20634   MachineBasicBlock *jcc1MBB = nullptr;
20635
20636   // If we have a cascaded CMOV, we lower it to two successive branches to
20637   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20638   if (CascadedCMOV) {
20639     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20640     F->insert(It, jcc1MBB);
20641     jcc1MBB->addLiveIn(X86::EFLAGS);
20642   }
20643
20644   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20645   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20646   F->insert(It, copy0MBB);
20647   F->insert(It, sinkMBB);
20648
20649   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20650   // live into the sink and copy blocks.
20651   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20652
20653   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20654   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20655       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20656     copy0MBB->addLiveIn(X86::EFLAGS);
20657     sinkMBB->addLiveIn(X86::EFLAGS);
20658   }
20659
20660   // Transfer the remainder of BB and its successor edges to sinkMBB.
20661   sinkMBB->splice(sinkMBB->begin(), BB,
20662                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20663   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20664
20665   // Add the true and fallthrough blocks as its successors.
20666   if (CascadedCMOV) {
20667     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20668     BB->addSuccessor(jcc1MBB);
20669
20670     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20671     // jump to the sinkMBB.
20672     jcc1MBB->addSuccessor(copy0MBB);
20673     jcc1MBB->addSuccessor(sinkMBB);
20674   } else {
20675     BB->addSuccessor(copy0MBB);
20676   }
20677
20678   // The true block target of the first (or only) branch is always sinkMBB.
20679   BB->addSuccessor(sinkMBB);
20680
20681   // Create the conditional branch instruction.
20682   unsigned Opc = X86::GetCondBranchFromCond(CC);
20683   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20684
20685   if (CascadedCMOV) {
20686     unsigned Opc2 = X86::GetCondBranchFromCond(
20687         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20688     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20689   }
20690
20691   //  copy0MBB:
20692   //   %FalseValue = ...
20693   //   # fallthrough to sinkMBB
20694   copy0MBB->addSuccessor(sinkMBB);
20695
20696   //  sinkMBB:
20697   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20698   //  ...
20699   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20700   MachineBasicBlock::iterator MIItEnd =
20701     std::next(MachineBasicBlock::iterator(LastCMOV));
20702   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20703   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20704   MachineInstrBuilder MIB;
20705
20706   // As we are creating the PHIs, we have to be careful if there is more than
20707   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
20708   // PHIs have to reference the individual true/false inputs from earlier PHIs.
20709   // That also means that PHI construction must work forward from earlier to
20710   // later, and that the code must maintain a mapping from earlier PHI's
20711   // destination registers, and the registers that went into the PHI.
20712
20713   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20714     unsigned DestReg = MIIt->getOperand(0).getReg();
20715     unsigned Op1Reg = MIIt->getOperand(1).getReg();
20716     unsigned Op2Reg = MIIt->getOperand(2).getReg();
20717
20718     // If this CMOV we are generating is the opposite condition from
20719     // the jump we generated, then we have to swap the operands for the
20720     // PHI that is going to be generated.
20721     if (MIIt->getOperand(3).getImm() == OppCC)
20722         std::swap(Op1Reg, Op2Reg);
20723
20724     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20725       Op1Reg = RegRewriteTable[Op1Reg].first;
20726
20727     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20728       Op2Reg = RegRewriteTable[Op2Reg].second;
20729
20730     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20731                   TII->get(X86::PHI), DestReg)
20732           .addReg(Op1Reg).addMBB(copy0MBB)
20733           .addReg(Op2Reg).addMBB(thisMBB);
20734
20735     // Add this PHI to the rewrite table.
20736     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20737   }
20738
20739   // If we have a cascaded CMOV, the second Jcc provides the same incoming
20740   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20741   if (CascadedCMOV) {
20742     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20743     // Copy the PHI result to the register defined by the second CMOV.
20744     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20745             DL, TII->get(TargetOpcode::COPY),
20746             CascadedCMOV->getOperand(0).getReg())
20747         .addReg(MI->getOperand(0).getReg());
20748     CascadedCMOV->eraseFromParent();
20749   }
20750
20751   // Now remove the CMOV(s).
20752   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20753     (MIIt++)->eraseFromParent();
20754
20755   return sinkMBB;
20756 }
20757
20758 MachineBasicBlock *
20759 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20760                                        MachineBasicBlock *BB) const {
20761   // Combine the following atomic floating-point modification pattern:
20762   //   a.store(reg OP a.load(acquire), release)
20763   // Transform them into:
20764   //   OPss (%gpr), %xmm
20765   //   movss %xmm, (%gpr)
20766   // Or sd equivalent for 64-bit operations.
20767   unsigned MOp, FOp;
20768   switch (MI->getOpcode()) {
20769   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20770   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20771   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20772   }
20773   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20774   DebugLoc DL = MI->getDebugLoc();
20775   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20776   unsigned MSrc = MI->getOperand(0).getReg();
20777   unsigned VSrc = MI->getOperand(5).getReg();
20778   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20779                                 .addReg(/*Base=*/MSrc)
20780                                 .addImm(/*Scale=*/1)
20781                                 .addReg(/*Index=*/0)
20782                                 .addImm(0)
20783                                 .addReg(0);
20784   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20785                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20786                           .addReg(VSrc)
20787                           .addReg(/*Base=*/MSrc)
20788                           .addImm(/*Scale=*/1)
20789                           .addReg(/*Index=*/0)
20790                           .addImm(/*Disp=*/0)
20791                           .addReg(/*Segment=*/0);
20792   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20793   MI->eraseFromParent(); // The pseudo instruction is gone now.
20794   return BB;
20795 }
20796
20797 MachineBasicBlock *
20798 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20799                                         MachineBasicBlock *BB) const {
20800   MachineFunction *MF = BB->getParent();
20801   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20802   DebugLoc DL = MI->getDebugLoc();
20803   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20804
20805   assert(MF->shouldSplitStack());
20806
20807   const bool Is64Bit = Subtarget->is64Bit();
20808   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20809
20810   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20811   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20812
20813   // BB:
20814   //  ... [Till the alloca]
20815   // If stacklet is not large enough, jump to mallocMBB
20816   //
20817   // bumpMBB:
20818   //  Allocate by subtracting from RSP
20819   //  Jump to continueMBB
20820   //
20821   // mallocMBB:
20822   //  Allocate by call to runtime
20823   //
20824   // continueMBB:
20825   //  ...
20826   //  [rest of original BB]
20827   //
20828
20829   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20830   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20831   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20832
20833   MachineRegisterInfo &MRI = MF->getRegInfo();
20834   const TargetRegisterClass *AddrRegClass =
20835       getRegClassFor(getPointerTy(MF->getDataLayout()));
20836
20837   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20838     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20839     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20840     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20841     sizeVReg = MI->getOperand(1).getReg(),
20842     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20843
20844   MachineFunction::iterator MBBIter = BB;
20845   ++MBBIter;
20846
20847   MF->insert(MBBIter, bumpMBB);
20848   MF->insert(MBBIter, mallocMBB);
20849   MF->insert(MBBIter, continueMBB);
20850
20851   continueMBB->splice(continueMBB->begin(), BB,
20852                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20853   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20854
20855   // Add code to the main basic block to check if the stack limit has been hit,
20856   // and if so, jump to mallocMBB otherwise to bumpMBB.
20857   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20858   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20859     .addReg(tmpSPVReg).addReg(sizeVReg);
20860   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20861     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20862     .addReg(SPLimitVReg);
20863   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20864
20865   // bumpMBB simply decreases the stack pointer, since we know the current
20866   // stacklet has enough space.
20867   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20868     .addReg(SPLimitVReg);
20869   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20870     .addReg(SPLimitVReg);
20871   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20872
20873   // Calls into a routine in libgcc to allocate more space from the heap.
20874   const uint32_t *RegMask =
20875       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20876   if (IsLP64) {
20877     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20878       .addReg(sizeVReg);
20879     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20880       .addExternalSymbol("__morestack_allocate_stack_space")
20881       .addRegMask(RegMask)
20882       .addReg(X86::RDI, RegState::Implicit)
20883       .addReg(X86::RAX, RegState::ImplicitDefine);
20884   } else if (Is64Bit) {
20885     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20886       .addReg(sizeVReg);
20887     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20888       .addExternalSymbol("__morestack_allocate_stack_space")
20889       .addRegMask(RegMask)
20890       .addReg(X86::EDI, RegState::Implicit)
20891       .addReg(X86::EAX, RegState::ImplicitDefine);
20892   } else {
20893     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20894       .addImm(12);
20895     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20896     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20897       .addExternalSymbol("__morestack_allocate_stack_space")
20898       .addRegMask(RegMask)
20899       .addReg(X86::EAX, RegState::ImplicitDefine);
20900   }
20901
20902   if (!Is64Bit)
20903     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20904       .addImm(16);
20905
20906   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20907     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20908   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20909
20910   // Set up the CFG correctly.
20911   BB->addSuccessor(bumpMBB);
20912   BB->addSuccessor(mallocMBB);
20913   mallocMBB->addSuccessor(continueMBB);
20914   bumpMBB->addSuccessor(continueMBB);
20915
20916   // Take care of the PHI nodes.
20917   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20918           MI->getOperand(0).getReg())
20919     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20920     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20921
20922   // Delete the original pseudo instruction.
20923   MI->eraseFromParent();
20924
20925   // And we're done.
20926   return continueMBB;
20927 }
20928
20929 MachineBasicBlock *
20930 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20931                                         MachineBasicBlock *BB) const {
20932   DebugLoc DL = MI->getDebugLoc();
20933
20934   assert(!Subtarget->isTargetMachO());
20935
20936   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20937                                                     DL);
20938
20939   MI->eraseFromParent();   // The pseudo instruction is gone now.
20940   return BB;
20941 }
20942
20943 MachineBasicBlock *
20944 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20945                                       MachineBasicBlock *BB) const {
20946   // This is pretty easy.  We're taking the value that we received from
20947   // our load from the relocation, sticking it in either RDI (x86-64)
20948   // or EAX and doing an indirect call.  The return value will then
20949   // be in the normal return register.
20950   MachineFunction *F = BB->getParent();
20951   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20952   DebugLoc DL = MI->getDebugLoc();
20953
20954   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20955   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20956
20957   // Get a register mask for the lowered call.
20958   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20959   // proper register mask.
20960   const uint32_t *RegMask =
20961       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20962   if (Subtarget->is64Bit()) {
20963     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20964                                       TII->get(X86::MOV64rm), X86::RDI)
20965     .addReg(X86::RIP)
20966     .addImm(0).addReg(0)
20967     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20968                       MI->getOperand(3).getTargetFlags())
20969     .addReg(0);
20970     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20971     addDirectMem(MIB, X86::RDI);
20972     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20973   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20974     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20975                                       TII->get(X86::MOV32rm), X86::EAX)
20976     .addReg(0)
20977     .addImm(0).addReg(0)
20978     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20979                       MI->getOperand(3).getTargetFlags())
20980     .addReg(0);
20981     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20982     addDirectMem(MIB, X86::EAX);
20983     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20984   } else {
20985     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20986                                       TII->get(X86::MOV32rm), X86::EAX)
20987     .addReg(TII->getGlobalBaseReg(F))
20988     .addImm(0).addReg(0)
20989     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20990                       MI->getOperand(3).getTargetFlags())
20991     .addReg(0);
20992     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20993     addDirectMem(MIB, X86::EAX);
20994     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20995   }
20996
20997   MI->eraseFromParent(); // The pseudo instruction is gone now.
20998   return BB;
20999 }
21000
21001 MachineBasicBlock *
21002 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21003                                     MachineBasicBlock *MBB) const {
21004   DebugLoc DL = MI->getDebugLoc();
21005   MachineFunction *MF = MBB->getParent();
21006   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21007   MachineRegisterInfo &MRI = MF->getRegInfo();
21008
21009   const BasicBlock *BB = MBB->getBasicBlock();
21010   MachineFunction::iterator I = MBB;
21011   ++I;
21012
21013   // Memory Reference
21014   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21015   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21016
21017   unsigned DstReg;
21018   unsigned MemOpndSlot = 0;
21019
21020   unsigned CurOp = 0;
21021
21022   DstReg = MI->getOperand(CurOp++).getReg();
21023   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21024   assert(RC->hasType(MVT::i32) && "Invalid destination!");
21025   unsigned mainDstReg = MRI.createVirtualRegister(RC);
21026   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21027
21028   MemOpndSlot = CurOp;
21029
21030   MVT PVT = getPointerTy(MF->getDataLayout());
21031   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21032          "Invalid Pointer Size!");
21033
21034   // For v = setjmp(buf), we generate
21035   //
21036   // thisMBB:
21037   //  buf[LabelOffset] = restoreMBB
21038   //  SjLjSetup restoreMBB
21039   //
21040   // mainMBB:
21041   //  v_main = 0
21042   //
21043   // sinkMBB:
21044   //  v = phi(main, restore)
21045   //
21046   // restoreMBB:
21047   //  if base pointer being used, load it from frame
21048   //  v_restore = 1
21049
21050   MachineBasicBlock *thisMBB = MBB;
21051   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21052   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21053   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21054   MF->insert(I, mainMBB);
21055   MF->insert(I, sinkMBB);
21056   MF->push_back(restoreMBB);
21057
21058   MachineInstrBuilder MIB;
21059
21060   // Transfer the remainder of BB and its successor edges to sinkMBB.
21061   sinkMBB->splice(sinkMBB->begin(), MBB,
21062                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21063   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21064
21065   // thisMBB:
21066   unsigned PtrStoreOpc = 0;
21067   unsigned LabelReg = 0;
21068   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21069   Reloc::Model RM = MF->getTarget().getRelocationModel();
21070   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21071                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21072
21073   // Prepare IP either in reg or imm.
21074   if (!UseImmLabel) {
21075     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21076     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21077     LabelReg = MRI.createVirtualRegister(PtrRC);
21078     if (Subtarget->is64Bit()) {
21079       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21080               .addReg(X86::RIP)
21081               .addImm(0)
21082               .addReg(0)
21083               .addMBB(restoreMBB)
21084               .addReg(0);
21085     } else {
21086       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21087       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21088               .addReg(XII->getGlobalBaseReg(MF))
21089               .addImm(0)
21090               .addReg(0)
21091               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21092               .addReg(0);
21093     }
21094   } else
21095     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21096   // Store IP
21097   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21098   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21099     if (i == X86::AddrDisp)
21100       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21101     else
21102       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21103   }
21104   if (!UseImmLabel)
21105     MIB.addReg(LabelReg);
21106   else
21107     MIB.addMBB(restoreMBB);
21108   MIB.setMemRefs(MMOBegin, MMOEnd);
21109   // Setup
21110   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21111           .addMBB(restoreMBB);
21112
21113   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21114   MIB.addRegMask(RegInfo->getNoPreservedMask());
21115   thisMBB->addSuccessor(mainMBB);
21116   thisMBB->addSuccessor(restoreMBB);
21117
21118   // mainMBB:
21119   //  EAX = 0
21120   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21121   mainMBB->addSuccessor(sinkMBB);
21122
21123   // sinkMBB:
21124   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21125           TII->get(X86::PHI), DstReg)
21126     .addReg(mainDstReg).addMBB(mainMBB)
21127     .addReg(restoreDstReg).addMBB(restoreMBB);
21128
21129   // restoreMBB:
21130   if (RegInfo->hasBasePointer(*MF)) {
21131     const bool Uses64BitFramePtr =
21132         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21133     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21134     X86FI->setRestoreBasePointer(MF);
21135     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21136     unsigned BasePtr = RegInfo->getBaseRegister();
21137     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21138     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21139                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
21140       .setMIFlag(MachineInstr::FrameSetup);
21141   }
21142   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21143   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21144   restoreMBB->addSuccessor(sinkMBB);
21145
21146   MI->eraseFromParent();
21147   return sinkMBB;
21148 }
21149
21150 MachineBasicBlock *
21151 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21152                                      MachineBasicBlock *MBB) const {
21153   DebugLoc DL = MI->getDebugLoc();
21154   MachineFunction *MF = MBB->getParent();
21155   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21156   MachineRegisterInfo &MRI = MF->getRegInfo();
21157
21158   // Memory Reference
21159   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21160   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21161
21162   MVT PVT = getPointerTy(MF->getDataLayout());
21163   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21164          "Invalid Pointer Size!");
21165
21166   const TargetRegisterClass *RC =
21167     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21168   unsigned Tmp = MRI.createVirtualRegister(RC);
21169   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21170   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21171   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21172   unsigned SP = RegInfo->getStackRegister();
21173
21174   MachineInstrBuilder MIB;
21175
21176   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21177   const int64_t SPOffset = 2 * PVT.getStoreSize();
21178
21179   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21180   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21181
21182   // Reload FP
21183   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21184   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21185     MIB.addOperand(MI->getOperand(i));
21186   MIB.setMemRefs(MMOBegin, MMOEnd);
21187   // Reload IP
21188   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21189   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21190     if (i == X86::AddrDisp)
21191       MIB.addDisp(MI->getOperand(i), LabelOffset);
21192     else
21193       MIB.addOperand(MI->getOperand(i));
21194   }
21195   MIB.setMemRefs(MMOBegin, MMOEnd);
21196   // Reload SP
21197   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21198   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21199     if (i == X86::AddrDisp)
21200       MIB.addDisp(MI->getOperand(i), SPOffset);
21201     else
21202       MIB.addOperand(MI->getOperand(i));
21203   }
21204   MIB.setMemRefs(MMOBegin, MMOEnd);
21205   // Jump
21206   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21207
21208   MI->eraseFromParent();
21209   return MBB;
21210 }
21211
21212 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21213 // accumulator loops. Writing back to the accumulator allows the coalescer
21214 // to remove extra copies in the loop.
21215 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
21216 MachineBasicBlock *
21217 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21218                                  MachineBasicBlock *MBB) const {
21219   MachineOperand &AddendOp = MI->getOperand(3);
21220
21221   // Bail out early if the addend isn't a register - we can't switch these.
21222   if (!AddendOp.isReg())
21223     return MBB;
21224
21225   MachineFunction &MF = *MBB->getParent();
21226   MachineRegisterInfo &MRI = MF.getRegInfo();
21227
21228   // Check whether the addend is defined by a PHI:
21229   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21230   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21231   if (!AddendDef.isPHI())
21232     return MBB;
21233
21234   // Look for the following pattern:
21235   // loop:
21236   //   %addend = phi [%entry, 0], [%loop, %result]
21237   //   ...
21238   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21239
21240   // Replace with:
21241   //   loop:
21242   //   %addend = phi [%entry, 0], [%loop, %result]
21243   //   ...
21244   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21245
21246   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21247     assert(AddendDef.getOperand(i).isReg());
21248     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21249     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21250     if (&PHISrcInst == MI) {
21251       // Found a matching instruction.
21252       unsigned NewFMAOpc = 0;
21253       switch (MI->getOpcode()) {
21254         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21255         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21256         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21257         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21258         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21259         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21260         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21261         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21262         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21263         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21264         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21265         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21266         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21267         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21268         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21269         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21270         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21271         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21272         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21273         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21274
21275         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21276         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21277         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21278         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21279         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21280         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21281         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21282         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21283         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21284         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21285         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21286         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21287         default: llvm_unreachable("Unrecognized FMA variant.");
21288       }
21289
21290       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21291       MachineInstrBuilder MIB =
21292         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21293         .addOperand(MI->getOperand(0))
21294         .addOperand(MI->getOperand(3))
21295         .addOperand(MI->getOperand(2))
21296         .addOperand(MI->getOperand(1));
21297       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21298       MI->eraseFromParent();
21299     }
21300   }
21301
21302   return MBB;
21303 }
21304
21305 MachineBasicBlock *
21306 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21307                                                MachineBasicBlock *BB) const {
21308   switch (MI->getOpcode()) {
21309   default: llvm_unreachable("Unexpected instr type to insert");
21310   case X86::TAILJMPd64:
21311   case X86::TAILJMPr64:
21312   case X86::TAILJMPm64:
21313   case X86::TAILJMPd64_REX:
21314   case X86::TAILJMPr64_REX:
21315   case X86::TAILJMPm64_REX:
21316     llvm_unreachable("TAILJMP64 would not be touched here.");
21317   case X86::TCRETURNdi64:
21318   case X86::TCRETURNri64:
21319   case X86::TCRETURNmi64:
21320     return BB;
21321   case X86::WIN_ALLOCA:
21322     return EmitLoweredWinAlloca(MI, BB);
21323   case X86::SEG_ALLOCA_32:
21324   case X86::SEG_ALLOCA_64:
21325     return EmitLoweredSegAlloca(MI, BB);
21326   case X86::TLSCall_32:
21327   case X86::TLSCall_64:
21328     return EmitLoweredTLSCall(MI, BB);
21329   case X86::CMOV_FR32:
21330   case X86::CMOV_FR64:
21331   case X86::CMOV_GR8:
21332   case X86::CMOV_GR16:
21333   case X86::CMOV_GR32:
21334   case X86::CMOV_RFP32:
21335   case X86::CMOV_RFP64:
21336   case X86::CMOV_RFP80:
21337   case X86::CMOV_V2F64:
21338   case X86::CMOV_V2I64:
21339   case X86::CMOV_V4F32:
21340   case X86::CMOV_V4F64:
21341   case X86::CMOV_V4I64:
21342   case X86::CMOV_V16F32:
21343   case X86::CMOV_V8F32:
21344   case X86::CMOV_V8F64:
21345   case X86::CMOV_V8I64:
21346   case X86::CMOV_V8I1:
21347   case X86::CMOV_V16I1:
21348   case X86::CMOV_V32I1:
21349   case X86::CMOV_V64I1:
21350     return EmitLoweredSelect(MI, BB);
21351
21352   case X86::RELEASE_FADD32mr:
21353   case X86::RELEASE_FADD64mr:
21354     return EmitLoweredAtomicFP(MI, BB);
21355
21356   case X86::FP32_TO_INT16_IN_MEM:
21357   case X86::FP32_TO_INT32_IN_MEM:
21358   case X86::FP32_TO_INT64_IN_MEM:
21359   case X86::FP64_TO_INT16_IN_MEM:
21360   case X86::FP64_TO_INT32_IN_MEM:
21361   case X86::FP64_TO_INT64_IN_MEM:
21362   case X86::FP80_TO_INT16_IN_MEM:
21363   case X86::FP80_TO_INT32_IN_MEM:
21364   case X86::FP80_TO_INT64_IN_MEM: {
21365     MachineFunction *F = BB->getParent();
21366     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21367     DebugLoc DL = MI->getDebugLoc();
21368
21369     // Change the floating point control register to use "round towards zero"
21370     // mode when truncating to an integer value.
21371     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21372     addFrameReference(BuildMI(*BB, MI, DL,
21373                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21374
21375     // Load the old value of the high byte of the control word...
21376     unsigned OldCW =
21377       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21378     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21379                       CWFrameIdx);
21380
21381     // Set the high part to be round to zero...
21382     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21383       .addImm(0xC7F);
21384
21385     // Reload the modified control word now...
21386     addFrameReference(BuildMI(*BB, MI, DL,
21387                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21388
21389     // Restore the memory image of control word to original value
21390     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21391       .addReg(OldCW);
21392
21393     // Get the X86 opcode to use.
21394     unsigned Opc;
21395     switch (MI->getOpcode()) {
21396     default: llvm_unreachable("illegal opcode!");
21397     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21398     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21399     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21400     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21401     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21402     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21403     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21404     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21405     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21406     }
21407
21408     X86AddressMode AM;
21409     MachineOperand &Op = MI->getOperand(0);
21410     if (Op.isReg()) {
21411       AM.BaseType = X86AddressMode::RegBase;
21412       AM.Base.Reg = Op.getReg();
21413     } else {
21414       AM.BaseType = X86AddressMode::FrameIndexBase;
21415       AM.Base.FrameIndex = Op.getIndex();
21416     }
21417     Op = MI->getOperand(1);
21418     if (Op.isImm())
21419       AM.Scale = Op.getImm();
21420     Op = MI->getOperand(2);
21421     if (Op.isImm())
21422       AM.IndexReg = Op.getImm();
21423     Op = MI->getOperand(3);
21424     if (Op.isGlobal()) {
21425       AM.GV = Op.getGlobal();
21426     } else {
21427       AM.Disp = Op.getImm();
21428     }
21429     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21430                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21431
21432     // Reload the original control word now.
21433     addFrameReference(BuildMI(*BB, MI, DL,
21434                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21435
21436     MI->eraseFromParent();   // The pseudo instruction is gone now.
21437     return BB;
21438   }
21439     // String/text processing lowering.
21440   case X86::PCMPISTRM128REG:
21441   case X86::VPCMPISTRM128REG:
21442   case X86::PCMPISTRM128MEM:
21443   case X86::VPCMPISTRM128MEM:
21444   case X86::PCMPESTRM128REG:
21445   case X86::VPCMPESTRM128REG:
21446   case X86::PCMPESTRM128MEM:
21447   case X86::VPCMPESTRM128MEM:
21448     assert(Subtarget->hasSSE42() &&
21449            "Target must have SSE4.2 or AVX features enabled");
21450     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21451
21452   // String/text processing lowering.
21453   case X86::PCMPISTRIREG:
21454   case X86::VPCMPISTRIREG:
21455   case X86::PCMPISTRIMEM:
21456   case X86::VPCMPISTRIMEM:
21457   case X86::PCMPESTRIREG:
21458   case X86::VPCMPESTRIREG:
21459   case X86::PCMPESTRIMEM:
21460   case X86::VPCMPESTRIMEM:
21461     assert(Subtarget->hasSSE42() &&
21462            "Target must have SSE4.2 or AVX features enabled");
21463     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21464
21465   // Thread synchronization.
21466   case X86::MONITOR:
21467     return EmitMonitor(MI, BB, Subtarget);
21468
21469   // xbegin
21470   case X86::XBEGIN:
21471     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21472
21473   case X86::VASTART_SAVE_XMM_REGS:
21474     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21475
21476   case X86::VAARG_64:
21477     return EmitVAARG64WithCustomInserter(MI, BB);
21478
21479   case X86::EH_SjLj_SetJmp32:
21480   case X86::EH_SjLj_SetJmp64:
21481     return emitEHSjLjSetJmp(MI, BB);
21482
21483   case X86::EH_SjLj_LongJmp32:
21484   case X86::EH_SjLj_LongJmp64:
21485     return emitEHSjLjLongJmp(MI, BB);
21486
21487   case TargetOpcode::STATEPOINT:
21488     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21489     // this point in the process.  We diverge later.
21490     return emitPatchPoint(MI, BB);
21491
21492   case TargetOpcode::STACKMAP:
21493   case TargetOpcode::PATCHPOINT:
21494     return emitPatchPoint(MI, BB);
21495
21496   case X86::VFMADDPDr213r:
21497   case X86::VFMADDPSr213r:
21498   case X86::VFMADDSDr213r:
21499   case X86::VFMADDSSr213r:
21500   case X86::VFMSUBPDr213r:
21501   case X86::VFMSUBPSr213r:
21502   case X86::VFMSUBSDr213r:
21503   case X86::VFMSUBSSr213r:
21504   case X86::VFNMADDPDr213r:
21505   case X86::VFNMADDPSr213r:
21506   case X86::VFNMADDSDr213r:
21507   case X86::VFNMADDSSr213r:
21508   case X86::VFNMSUBPDr213r:
21509   case X86::VFNMSUBPSr213r:
21510   case X86::VFNMSUBSDr213r:
21511   case X86::VFNMSUBSSr213r:
21512   case X86::VFMADDSUBPDr213r:
21513   case X86::VFMADDSUBPSr213r:
21514   case X86::VFMSUBADDPDr213r:
21515   case X86::VFMSUBADDPSr213r:
21516   case X86::VFMADDPDr213rY:
21517   case X86::VFMADDPSr213rY:
21518   case X86::VFMSUBPDr213rY:
21519   case X86::VFMSUBPSr213rY:
21520   case X86::VFNMADDPDr213rY:
21521   case X86::VFNMADDPSr213rY:
21522   case X86::VFNMSUBPDr213rY:
21523   case X86::VFNMSUBPSr213rY:
21524   case X86::VFMADDSUBPDr213rY:
21525   case X86::VFMADDSUBPSr213rY:
21526   case X86::VFMSUBADDPDr213rY:
21527   case X86::VFMSUBADDPSr213rY:
21528     return emitFMA3Instr(MI, BB);
21529   }
21530 }
21531
21532 //===----------------------------------------------------------------------===//
21533 //                           X86 Optimization Hooks
21534 //===----------------------------------------------------------------------===//
21535
21536 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21537                                                       APInt &KnownZero,
21538                                                       APInt &KnownOne,
21539                                                       const SelectionDAG &DAG,
21540                                                       unsigned Depth) const {
21541   unsigned BitWidth = KnownZero.getBitWidth();
21542   unsigned Opc = Op.getOpcode();
21543   assert((Opc >= ISD::BUILTIN_OP_END ||
21544           Opc == ISD::INTRINSIC_WO_CHAIN ||
21545           Opc == ISD::INTRINSIC_W_CHAIN ||
21546           Opc == ISD::INTRINSIC_VOID) &&
21547          "Should use MaskedValueIsZero if you don't know whether Op"
21548          " is a target node!");
21549
21550   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21551   switch (Opc) {
21552   default: break;
21553   case X86ISD::ADD:
21554   case X86ISD::SUB:
21555   case X86ISD::ADC:
21556   case X86ISD::SBB:
21557   case X86ISD::SMUL:
21558   case X86ISD::UMUL:
21559   case X86ISD::INC:
21560   case X86ISD::DEC:
21561   case X86ISD::OR:
21562   case X86ISD::XOR:
21563   case X86ISD::AND:
21564     // These nodes' second result is a boolean.
21565     if (Op.getResNo() == 0)
21566       break;
21567     // Fallthrough
21568   case X86ISD::SETCC:
21569     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21570     break;
21571   case ISD::INTRINSIC_WO_CHAIN: {
21572     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21573     unsigned NumLoBits = 0;
21574     switch (IntId) {
21575     default: break;
21576     case Intrinsic::x86_sse_movmsk_ps:
21577     case Intrinsic::x86_avx_movmsk_ps_256:
21578     case Intrinsic::x86_sse2_movmsk_pd:
21579     case Intrinsic::x86_avx_movmsk_pd_256:
21580     case Intrinsic::x86_mmx_pmovmskb:
21581     case Intrinsic::x86_sse2_pmovmskb_128:
21582     case Intrinsic::x86_avx2_pmovmskb: {
21583       // High bits of movmskp{s|d}, pmovmskb are known zero.
21584       switch (IntId) {
21585         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21586         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21587         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21588         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21589         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21590         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21591         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21592         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21593       }
21594       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21595       break;
21596     }
21597     }
21598     break;
21599   }
21600   }
21601 }
21602
21603 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21604   SDValue Op,
21605   const SelectionDAG &,
21606   unsigned Depth) const {
21607   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21608   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21609     return Op.getValueType().getScalarType().getSizeInBits();
21610
21611   // Fallback case.
21612   return 1;
21613 }
21614
21615 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21616 /// node is a GlobalAddress + offset.
21617 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21618                                        const GlobalValue* &GA,
21619                                        int64_t &Offset) const {
21620   if (N->getOpcode() == X86ISD::Wrapper) {
21621     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21622       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21623       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21624       return true;
21625     }
21626   }
21627   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21628 }
21629
21630 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21631 /// same as extracting the high 128-bit part of 256-bit vector and then
21632 /// inserting the result into the low part of a new 256-bit vector
21633 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21634   EVT VT = SVOp->getValueType(0);
21635   unsigned NumElems = VT.getVectorNumElements();
21636
21637   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21638   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21639     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21640         SVOp->getMaskElt(j) >= 0)
21641       return false;
21642
21643   return true;
21644 }
21645
21646 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21647 /// same as extracting the low 128-bit part of 256-bit vector and then
21648 /// inserting the result into the high part of a new 256-bit vector
21649 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21650   EVT VT = SVOp->getValueType(0);
21651   unsigned NumElems = VT.getVectorNumElements();
21652
21653   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21654   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21655     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21656         SVOp->getMaskElt(j) >= 0)
21657       return false;
21658
21659   return true;
21660 }
21661
21662 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21663 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21664                                         TargetLowering::DAGCombinerInfo &DCI,
21665                                         const X86Subtarget* Subtarget) {
21666   SDLoc dl(N);
21667   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21668   SDValue V1 = SVOp->getOperand(0);
21669   SDValue V2 = SVOp->getOperand(1);
21670   EVT VT = SVOp->getValueType(0);
21671   unsigned NumElems = VT.getVectorNumElements();
21672
21673   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21674       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21675     //
21676     //                   0,0,0,...
21677     //                      |
21678     //    V      UNDEF    BUILD_VECTOR    UNDEF
21679     //     \      /           \           /
21680     //  CONCAT_VECTOR         CONCAT_VECTOR
21681     //         \                  /
21682     //          \                /
21683     //          RESULT: V + zero extended
21684     //
21685     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21686         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21687         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21688       return SDValue();
21689
21690     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21691       return SDValue();
21692
21693     // To match the shuffle mask, the first half of the mask should
21694     // be exactly the first vector, and all the rest a splat with the
21695     // first element of the second one.
21696     for (unsigned i = 0; i != NumElems/2; ++i)
21697       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21698           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21699         return SDValue();
21700
21701     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21702     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21703       if (Ld->hasNUsesOfValue(1, 0)) {
21704         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21705         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21706         SDValue ResNode =
21707           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21708                                   Ld->getMemoryVT(),
21709                                   Ld->getPointerInfo(),
21710                                   Ld->getAlignment(),
21711                                   false/*isVolatile*/, true/*ReadMem*/,
21712                                   false/*WriteMem*/);
21713
21714         // Make sure the newly-created LOAD is in the same position as Ld in
21715         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21716         // and update uses of Ld's output chain to use the TokenFactor.
21717         if (Ld->hasAnyUseOfValue(1)) {
21718           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21719                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21720           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21721           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21722                                  SDValue(ResNode.getNode(), 1));
21723         }
21724
21725         return DAG.getBitcast(VT, ResNode);
21726       }
21727     }
21728
21729     // Emit a zeroed vector and insert the desired subvector on its
21730     // first half.
21731     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21732     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21733     return DCI.CombineTo(N, InsV);
21734   }
21735
21736   //===--------------------------------------------------------------------===//
21737   // Combine some shuffles into subvector extracts and inserts:
21738   //
21739
21740   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21741   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21742     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21743     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21744     return DCI.CombineTo(N, InsV);
21745   }
21746
21747   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21748   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21749     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21750     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21751     return DCI.CombineTo(N, InsV);
21752   }
21753
21754   return SDValue();
21755 }
21756
21757 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21758 /// possible.
21759 ///
21760 /// This is the leaf of the recursive combinine below. When we have found some
21761 /// chain of single-use x86 shuffle instructions and accumulated the combined
21762 /// shuffle mask represented by them, this will try to pattern match that mask
21763 /// into either a single instruction if there is a special purpose instruction
21764 /// for this operation, or into a PSHUFB instruction which is a fully general
21765 /// instruction but should only be used to replace chains over a certain depth.
21766 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21767                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21768                                    TargetLowering::DAGCombinerInfo &DCI,
21769                                    const X86Subtarget *Subtarget) {
21770   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21771
21772   // Find the operand that enters the chain. Note that multiple uses are OK
21773   // here, we're not going to remove the operand we find.
21774   SDValue Input = Op.getOperand(0);
21775   while (Input.getOpcode() == ISD::BITCAST)
21776     Input = Input.getOperand(0);
21777
21778   MVT VT = Input.getSimpleValueType();
21779   MVT RootVT = Root.getSimpleValueType();
21780   SDLoc DL(Root);
21781
21782   // Just remove no-op shuffle masks.
21783   if (Mask.size() == 1) {
21784     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21785                   /*AddTo*/ true);
21786     return true;
21787   }
21788
21789   // Use the float domain if the operand type is a floating point type.
21790   bool FloatDomain = VT.isFloatingPoint();
21791
21792   // For floating point shuffles, we don't have free copies in the shuffle
21793   // instructions or the ability to load as part of the instruction, so
21794   // canonicalize their shuffles to UNPCK or MOV variants.
21795   //
21796   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21797   // vectors because it can have a load folded into it that UNPCK cannot. This
21798   // doesn't preclude something switching to the shorter encoding post-RA.
21799   //
21800   // FIXME: Should teach these routines about AVX vector widths.
21801   if (FloatDomain && VT.getSizeInBits() == 128) {
21802     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21803       bool Lo = Mask.equals({0, 0});
21804       unsigned Shuffle;
21805       MVT ShuffleVT;
21806       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21807       // is no slower than UNPCKLPD but has the option to fold the input operand
21808       // into even an unaligned memory load.
21809       if (Lo && Subtarget->hasSSE3()) {
21810         Shuffle = X86ISD::MOVDDUP;
21811         ShuffleVT = MVT::v2f64;
21812       } else {
21813         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21814         // than the UNPCK variants.
21815         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21816         ShuffleVT = MVT::v4f32;
21817       }
21818       if (Depth == 1 && Root->getOpcode() == Shuffle)
21819         return false; // Nothing to do!
21820       Op = DAG.getBitcast(ShuffleVT, Input);
21821       DCI.AddToWorklist(Op.getNode());
21822       if (Shuffle == X86ISD::MOVDDUP)
21823         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21824       else
21825         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21826       DCI.AddToWorklist(Op.getNode());
21827       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21828                     /*AddTo*/ true);
21829       return true;
21830     }
21831     if (Subtarget->hasSSE3() &&
21832         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21833       bool Lo = Mask.equals({0, 0, 2, 2});
21834       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21835       MVT ShuffleVT = MVT::v4f32;
21836       if (Depth == 1 && Root->getOpcode() == Shuffle)
21837         return false; // Nothing to do!
21838       Op = DAG.getBitcast(ShuffleVT, Input);
21839       DCI.AddToWorklist(Op.getNode());
21840       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21841       DCI.AddToWorklist(Op.getNode());
21842       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21843                     /*AddTo*/ true);
21844       return true;
21845     }
21846     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21847       bool Lo = Mask.equals({0, 0, 1, 1});
21848       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21849       MVT ShuffleVT = MVT::v4f32;
21850       if (Depth == 1 && Root->getOpcode() == Shuffle)
21851         return false; // Nothing to do!
21852       Op = DAG.getBitcast(ShuffleVT, Input);
21853       DCI.AddToWorklist(Op.getNode());
21854       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21855       DCI.AddToWorklist(Op.getNode());
21856       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21857                     /*AddTo*/ true);
21858       return true;
21859     }
21860   }
21861
21862   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21863   // variants as none of these have single-instruction variants that are
21864   // superior to the UNPCK formulation.
21865   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21866       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21867        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21868        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21869        Mask.equals(
21870            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21871     bool Lo = Mask[0] == 0;
21872     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21873     if (Depth == 1 && Root->getOpcode() == Shuffle)
21874       return false; // Nothing to do!
21875     MVT ShuffleVT;
21876     switch (Mask.size()) {
21877     case 8:
21878       ShuffleVT = MVT::v8i16;
21879       break;
21880     case 16:
21881       ShuffleVT = MVT::v16i8;
21882       break;
21883     default:
21884       llvm_unreachable("Impossible mask size!");
21885     };
21886     Op = DAG.getBitcast(ShuffleVT, Input);
21887     DCI.AddToWorklist(Op.getNode());
21888     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21889     DCI.AddToWorklist(Op.getNode());
21890     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21891                   /*AddTo*/ true);
21892     return true;
21893   }
21894
21895   // Don't try to re-form single instruction chains under any circumstances now
21896   // that we've done encoding canonicalization for them.
21897   if (Depth < 2)
21898     return false;
21899
21900   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21901   // can replace them with a single PSHUFB instruction profitably. Intel's
21902   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21903   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21904   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21905     SmallVector<SDValue, 16> PSHUFBMask;
21906     int NumBytes = VT.getSizeInBits() / 8;
21907     int Ratio = NumBytes / Mask.size();
21908     for (int i = 0; i < NumBytes; ++i) {
21909       if (Mask[i / Ratio] == SM_SentinelUndef) {
21910         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21911         continue;
21912       }
21913       int M = Mask[i / Ratio] != SM_SentinelZero
21914                   ? Ratio * Mask[i / Ratio] + i % Ratio
21915                   : 255;
21916       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21917     }
21918     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21919     Op = DAG.getBitcast(ByteVT, Input);
21920     DCI.AddToWorklist(Op.getNode());
21921     SDValue PSHUFBMaskOp =
21922         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21923     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21924     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21925     DCI.AddToWorklist(Op.getNode());
21926     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21927                   /*AddTo*/ true);
21928     return true;
21929   }
21930
21931   // Failed to find any combines.
21932   return false;
21933 }
21934
21935 /// \brief Fully generic combining of x86 shuffle instructions.
21936 ///
21937 /// This should be the last combine run over the x86 shuffle instructions. Once
21938 /// they have been fully optimized, this will recursively consider all chains
21939 /// of single-use shuffle instructions, build a generic model of the cumulative
21940 /// shuffle operation, and check for simpler instructions which implement this
21941 /// operation. We use this primarily for two purposes:
21942 ///
21943 /// 1) Collapse generic shuffles to specialized single instructions when
21944 ///    equivalent. In most cases, this is just an encoding size win, but
21945 ///    sometimes we will collapse multiple generic shuffles into a single
21946 ///    special-purpose shuffle.
21947 /// 2) Look for sequences of shuffle instructions with 3 or more total
21948 ///    instructions, and replace them with the slightly more expensive SSSE3
21949 ///    PSHUFB instruction if available. We do this as the last combining step
21950 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21951 ///    a suitable short sequence of other instructions. The PHUFB will either
21952 ///    use a register or have to read from memory and so is slightly (but only
21953 ///    slightly) more expensive than the other shuffle instructions.
21954 ///
21955 /// Because this is inherently a quadratic operation (for each shuffle in
21956 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21957 /// This should never be an issue in practice as the shuffle lowering doesn't
21958 /// produce sequences of more than 8 instructions.
21959 ///
21960 /// FIXME: We will currently miss some cases where the redundant shuffling
21961 /// would simplify under the threshold for PSHUFB formation because of
21962 /// combine-ordering. To fix this, we should do the redundant instruction
21963 /// combining in this recursive walk.
21964 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21965                                           ArrayRef<int> RootMask,
21966                                           int Depth, bool HasPSHUFB,
21967                                           SelectionDAG &DAG,
21968                                           TargetLowering::DAGCombinerInfo &DCI,
21969                                           const X86Subtarget *Subtarget) {
21970   // Bound the depth of our recursive combine because this is ultimately
21971   // quadratic in nature.
21972   if (Depth > 8)
21973     return false;
21974
21975   // Directly rip through bitcasts to find the underlying operand.
21976   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21977     Op = Op.getOperand(0);
21978
21979   MVT VT = Op.getSimpleValueType();
21980   if (!VT.isVector())
21981     return false; // Bail if we hit a non-vector.
21982
21983   assert(Root.getSimpleValueType().isVector() &&
21984          "Shuffles operate on vector types!");
21985   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21986          "Can only combine shuffles of the same vector register size.");
21987
21988   if (!isTargetShuffle(Op.getOpcode()))
21989     return false;
21990   SmallVector<int, 16> OpMask;
21991   bool IsUnary;
21992   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21993   // We only can combine unary shuffles which we can decode the mask for.
21994   if (!HaveMask || !IsUnary)
21995     return false;
21996
21997   assert(VT.getVectorNumElements() == OpMask.size() &&
21998          "Different mask size from vector size!");
21999   assert(((RootMask.size() > OpMask.size() &&
22000            RootMask.size() % OpMask.size() == 0) ||
22001           (OpMask.size() > RootMask.size() &&
22002            OpMask.size() % RootMask.size() == 0) ||
22003           OpMask.size() == RootMask.size()) &&
22004          "The smaller number of elements must divide the larger.");
22005   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22006   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22007   assert(((RootRatio == 1 && OpRatio == 1) ||
22008           (RootRatio == 1) != (OpRatio == 1)) &&
22009          "Must not have a ratio for both incoming and op masks!");
22010
22011   SmallVector<int, 16> Mask;
22012   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22013
22014   // Merge this shuffle operation's mask into our accumulated mask. Note that
22015   // this shuffle's mask will be the first applied to the input, followed by the
22016   // root mask to get us all the way to the root value arrangement. The reason
22017   // for this order is that we are recursing up the operation chain.
22018   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22019     int RootIdx = i / RootRatio;
22020     if (RootMask[RootIdx] < 0) {
22021       // This is a zero or undef lane, we're done.
22022       Mask.push_back(RootMask[RootIdx]);
22023       continue;
22024     }
22025
22026     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22027     int OpIdx = RootMaskedIdx / OpRatio;
22028     if (OpMask[OpIdx] < 0) {
22029       // The incoming lanes are zero or undef, it doesn't matter which ones we
22030       // are using.
22031       Mask.push_back(OpMask[OpIdx]);
22032       continue;
22033     }
22034
22035     // Ok, we have non-zero lanes, map them through.
22036     Mask.push_back(OpMask[OpIdx] * OpRatio +
22037                    RootMaskedIdx % OpRatio);
22038   }
22039
22040   // See if we can recurse into the operand to combine more things.
22041   switch (Op.getOpcode()) {
22042     case X86ISD::PSHUFB:
22043       HasPSHUFB = true;
22044     case X86ISD::PSHUFD:
22045     case X86ISD::PSHUFHW:
22046     case X86ISD::PSHUFLW:
22047       if (Op.getOperand(0).hasOneUse() &&
22048           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22049                                         HasPSHUFB, DAG, DCI, Subtarget))
22050         return true;
22051       break;
22052
22053     case X86ISD::UNPCKL:
22054     case X86ISD::UNPCKH:
22055       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
22056       // We can't check for single use, we have to check that this shuffle is the only user.
22057       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22058           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22059                                         HasPSHUFB, DAG, DCI, Subtarget))
22060           return true;
22061       break;
22062   }
22063
22064   // Minor canonicalization of the accumulated shuffle mask to make it easier
22065   // to match below. All this does is detect masks with squential pairs of
22066   // elements, and shrink them to the half-width mask. It does this in a loop
22067   // so it will reduce the size of the mask to the minimal width mask which
22068   // performs an equivalent shuffle.
22069   SmallVector<int, 16> WidenedMask;
22070   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22071     Mask = std::move(WidenedMask);
22072     WidenedMask.clear();
22073   }
22074
22075   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22076                                 Subtarget);
22077 }
22078
22079 /// \brief Get the PSHUF-style mask from PSHUF node.
22080 ///
22081 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22082 /// PSHUF-style masks that can be reused with such instructions.
22083 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22084   MVT VT = N.getSimpleValueType();
22085   SmallVector<int, 4> Mask;
22086   bool IsUnary;
22087   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22088   (void)HaveMask;
22089   assert(HaveMask);
22090
22091   // If we have more than 128-bits, only the low 128-bits of shuffle mask
22092   // matter. Check that the upper masks are repeats and remove them.
22093   if (VT.getSizeInBits() > 128) {
22094     int LaneElts = 128 / VT.getScalarSizeInBits();
22095 #ifndef NDEBUG
22096     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22097       for (int j = 0; j < LaneElts; ++j)
22098         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22099                "Mask doesn't repeat in high 128-bit lanes!");
22100 #endif
22101     Mask.resize(LaneElts);
22102   }
22103
22104   switch (N.getOpcode()) {
22105   case X86ISD::PSHUFD:
22106     return Mask;
22107   case X86ISD::PSHUFLW:
22108     Mask.resize(4);
22109     return Mask;
22110   case X86ISD::PSHUFHW:
22111     Mask.erase(Mask.begin(), Mask.begin() + 4);
22112     for (int &M : Mask)
22113       M -= 4;
22114     return Mask;
22115   default:
22116     llvm_unreachable("No valid shuffle instruction found!");
22117   }
22118 }
22119
22120 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22121 ///
22122 /// We walk up the chain and look for a combinable shuffle, skipping over
22123 /// shuffles that we could hoist this shuffle's transformation past without
22124 /// altering anything.
22125 static SDValue
22126 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22127                              SelectionDAG &DAG,
22128                              TargetLowering::DAGCombinerInfo &DCI) {
22129   assert(N.getOpcode() == X86ISD::PSHUFD &&
22130          "Called with something other than an x86 128-bit half shuffle!");
22131   SDLoc DL(N);
22132
22133   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22134   // of the shuffles in the chain so that we can form a fresh chain to replace
22135   // this one.
22136   SmallVector<SDValue, 8> Chain;
22137   SDValue V = N.getOperand(0);
22138   for (; V.hasOneUse(); V = V.getOperand(0)) {
22139     switch (V.getOpcode()) {
22140     default:
22141       return SDValue(); // Nothing combined!
22142
22143     case ISD::BITCAST:
22144       // Skip bitcasts as we always know the type for the target specific
22145       // instructions.
22146       continue;
22147
22148     case X86ISD::PSHUFD:
22149       // Found another dword shuffle.
22150       break;
22151
22152     case X86ISD::PSHUFLW:
22153       // Check that the low words (being shuffled) are the identity in the
22154       // dword shuffle, and the high words are self-contained.
22155       if (Mask[0] != 0 || Mask[1] != 1 ||
22156           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22157         return SDValue();
22158
22159       Chain.push_back(V);
22160       continue;
22161
22162     case X86ISD::PSHUFHW:
22163       // Check that the high words (being shuffled) are the identity in the
22164       // dword shuffle, and the low words are self-contained.
22165       if (Mask[2] != 2 || Mask[3] != 3 ||
22166           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22167         return SDValue();
22168
22169       Chain.push_back(V);
22170       continue;
22171
22172     case X86ISD::UNPCKL:
22173     case X86ISD::UNPCKH:
22174       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22175       // shuffle into a preceding word shuffle.
22176       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
22177           V.getSimpleValueType().getScalarType() != MVT::i16)
22178         return SDValue();
22179
22180       // Search for a half-shuffle which we can combine with.
22181       unsigned CombineOp =
22182           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22183       if (V.getOperand(0) != V.getOperand(1) ||
22184           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22185         return SDValue();
22186       Chain.push_back(V);
22187       V = V.getOperand(0);
22188       do {
22189         switch (V.getOpcode()) {
22190         default:
22191           return SDValue(); // Nothing to combine.
22192
22193         case X86ISD::PSHUFLW:
22194         case X86ISD::PSHUFHW:
22195           if (V.getOpcode() == CombineOp)
22196             break;
22197
22198           Chain.push_back(V);
22199
22200           // Fallthrough!
22201         case ISD::BITCAST:
22202           V = V.getOperand(0);
22203           continue;
22204         }
22205         break;
22206       } while (V.hasOneUse());
22207       break;
22208     }
22209     // Break out of the loop if we break out of the switch.
22210     break;
22211   }
22212
22213   if (!V.hasOneUse())
22214     // We fell out of the loop without finding a viable combining instruction.
22215     return SDValue();
22216
22217   // Merge this node's mask and our incoming mask.
22218   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22219   for (int &M : Mask)
22220     M = VMask[M];
22221   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22222                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22223
22224   // Rebuild the chain around this new shuffle.
22225   while (!Chain.empty()) {
22226     SDValue W = Chain.pop_back_val();
22227
22228     if (V.getValueType() != W.getOperand(0).getValueType())
22229       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
22230
22231     switch (W.getOpcode()) {
22232     default:
22233       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22234
22235     case X86ISD::UNPCKL:
22236     case X86ISD::UNPCKH:
22237       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22238       break;
22239
22240     case X86ISD::PSHUFD:
22241     case X86ISD::PSHUFLW:
22242     case X86ISD::PSHUFHW:
22243       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22244       break;
22245     }
22246   }
22247   if (V.getValueType() != N.getValueType())
22248     V = DAG.getBitcast(N.getValueType(), V);
22249
22250   // Return the new chain to replace N.
22251   return V;
22252 }
22253
22254 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
22255 ///
22256 /// We walk up the chain, skipping shuffles of the other half and looking
22257 /// through shuffles which switch halves trying to find a shuffle of the same
22258 /// pair of dwords.
22259 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22260                                         SelectionDAG &DAG,
22261                                         TargetLowering::DAGCombinerInfo &DCI) {
22262   assert(
22263       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22264       "Called with something other than an x86 128-bit half shuffle!");
22265   SDLoc DL(N);
22266   unsigned CombineOpcode = N.getOpcode();
22267
22268   // Walk up a single-use chain looking for a combinable shuffle.
22269   SDValue V = N.getOperand(0);
22270   for (; V.hasOneUse(); V = V.getOperand(0)) {
22271     switch (V.getOpcode()) {
22272     default:
22273       return false; // Nothing combined!
22274
22275     case ISD::BITCAST:
22276       // Skip bitcasts as we always know the type for the target specific
22277       // instructions.
22278       continue;
22279
22280     case X86ISD::PSHUFLW:
22281     case X86ISD::PSHUFHW:
22282       if (V.getOpcode() == CombineOpcode)
22283         break;
22284
22285       // Other-half shuffles are no-ops.
22286       continue;
22287     }
22288     // Break out of the loop if we break out of the switch.
22289     break;
22290   }
22291
22292   if (!V.hasOneUse())
22293     // We fell out of the loop without finding a viable combining instruction.
22294     return false;
22295
22296   // Combine away the bottom node as its shuffle will be accumulated into
22297   // a preceding shuffle.
22298   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22299
22300   // Record the old value.
22301   SDValue Old = V;
22302
22303   // Merge this node's mask and our incoming mask (adjusted to account for all
22304   // the pshufd instructions encountered).
22305   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22306   for (int &M : Mask)
22307     M = VMask[M];
22308   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22309                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22310
22311   // Check that the shuffles didn't cancel each other out. If not, we need to
22312   // combine to the new one.
22313   if (Old != V)
22314     // Replace the combinable shuffle with the combined one, updating all users
22315     // so that we re-evaluate the chain here.
22316     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22317
22318   return true;
22319 }
22320
22321 /// \brief Try to combine x86 target specific shuffles.
22322 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22323                                            TargetLowering::DAGCombinerInfo &DCI,
22324                                            const X86Subtarget *Subtarget) {
22325   SDLoc DL(N);
22326   MVT VT = N.getSimpleValueType();
22327   SmallVector<int, 4> Mask;
22328
22329   switch (N.getOpcode()) {
22330   case X86ISD::PSHUFD:
22331   case X86ISD::PSHUFLW:
22332   case X86ISD::PSHUFHW:
22333     Mask = getPSHUFShuffleMask(N);
22334     assert(Mask.size() == 4);
22335     break;
22336   default:
22337     return SDValue();
22338   }
22339
22340   // Nuke no-op shuffles that show up after combining.
22341   if (isNoopShuffleMask(Mask))
22342     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22343
22344   // Look for simplifications involving one or two shuffle instructions.
22345   SDValue V = N.getOperand(0);
22346   switch (N.getOpcode()) {
22347   default:
22348     break;
22349   case X86ISD::PSHUFLW:
22350   case X86ISD::PSHUFHW:
22351     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22352
22353     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22354       return SDValue(); // We combined away this shuffle, so we're done.
22355
22356     // See if this reduces to a PSHUFD which is no more expensive and can
22357     // combine with more operations. Note that it has to at least flip the
22358     // dwords as otherwise it would have been removed as a no-op.
22359     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22360       int DMask[] = {0, 1, 2, 3};
22361       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22362       DMask[DOffset + 0] = DOffset + 1;
22363       DMask[DOffset + 1] = DOffset + 0;
22364       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22365       V = DAG.getBitcast(DVT, V);
22366       DCI.AddToWorklist(V.getNode());
22367       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22368                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22369       DCI.AddToWorklist(V.getNode());
22370       return DAG.getBitcast(VT, V);
22371     }
22372
22373     // Look for shuffle patterns which can be implemented as a single unpack.
22374     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22375     // only works when we have a PSHUFD followed by two half-shuffles.
22376     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22377         (V.getOpcode() == X86ISD::PSHUFLW ||
22378          V.getOpcode() == X86ISD::PSHUFHW) &&
22379         V.getOpcode() != N.getOpcode() &&
22380         V.hasOneUse()) {
22381       SDValue D = V.getOperand(0);
22382       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22383         D = D.getOperand(0);
22384       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22385         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22386         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22387         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22388         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22389         int WordMask[8];
22390         for (int i = 0; i < 4; ++i) {
22391           WordMask[i + NOffset] = Mask[i] + NOffset;
22392           WordMask[i + VOffset] = VMask[i] + VOffset;
22393         }
22394         // Map the word mask through the DWord mask.
22395         int MappedMask[8];
22396         for (int i = 0; i < 8; ++i)
22397           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22398         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22399             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22400           // We can replace all three shuffles with an unpack.
22401           V = DAG.getBitcast(VT, D.getOperand(0));
22402           DCI.AddToWorklist(V.getNode());
22403           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22404                                                 : X86ISD::UNPCKH,
22405                              DL, VT, V, V);
22406         }
22407       }
22408     }
22409
22410     break;
22411
22412   case X86ISD::PSHUFD:
22413     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22414       return NewN;
22415
22416     break;
22417   }
22418
22419   return SDValue();
22420 }
22421
22422 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22423 ///
22424 /// We combine this directly on the abstract vector shuffle nodes so it is
22425 /// easier to generically match. We also insert dummy vector shuffle nodes for
22426 /// the operands which explicitly discard the lanes which are unused by this
22427 /// operation to try to flow through the rest of the combiner the fact that
22428 /// they're unused.
22429 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22430   SDLoc DL(N);
22431   EVT VT = N->getValueType(0);
22432
22433   // We only handle target-independent shuffles.
22434   // FIXME: It would be easy and harmless to use the target shuffle mask
22435   // extraction tool to support more.
22436   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22437     return SDValue();
22438
22439   auto *SVN = cast<ShuffleVectorSDNode>(N);
22440   ArrayRef<int> Mask = SVN->getMask();
22441   SDValue V1 = N->getOperand(0);
22442   SDValue V2 = N->getOperand(1);
22443
22444   // We require the first shuffle operand to be the SUB node, and the second to
22445   // be the ADD node.
22446   // FIXME: We should support the commuted patterns.
22447   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22448     return SDValue();
22449
22450   // If there are other uses of these operations we can't fold them.
22451   if (!V1->hasOneUse() || !V2->hasOneUse())
22452     return SDValue();
22453
22454   // Ensure that both operations have the same operands. Note that we can
22455   // commute the FADD operands.
22456   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22457   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22458       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22459     return SDValue();
22460
22461   // We're looking for blends between FADD and FSUB nodes. We insist on these
22462   // nodes being lined up in a specific expected pattern.
22463   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22464         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22465         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22466     return SDValue();
22467
22468   // Only specific types are legal at this point, assert so we notice if and
22469   // when these change.
22470   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22471           VT == MVT::v4f64) &&
22472          "Unknown vector type encountered!");
22473
22474   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22475 }
22476
22477 /// PerformShuffleCombine - Performs several different shuffle combines.
22478 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22479                                      TargetLowering::DAGCombinerInfo &DCI,
22480                                      const X86Subtarget *Subtarget) {
22481   SDLoc dl(N);
22482   SDValue N0 = N->getOperand(0);
22483   SDValue N1 = N->getOperand(1);
22484   EVT VT = N->getValueType(0);
22485
22486   // Don't create instructions with illegal types after legalize types has run.
22487   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22488   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22489     return SDValue();
22490
22491   // If we have legalized the vector types, look for blends of FADD and FSUB
22492   // nodes that we can fuse into an ADDSUB node.
22493   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22494     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22495       return AddSub;
22496
22497   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22498   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22499       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22500     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22501
22502   // During Type Legalization, when promoting illegal vector types,
22503   // the backend might introduce new shuffle dag nodes and bitcasts.
22504   //
22505   // This code performs the following transformation:
22506   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22507   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22508   //
22509   // We do this only if both the bitcast and the BINOP dag nodes have
22510   // one use. Also, perform this transformation only if the new binary
22511   // operation is legal. This is to avoid introducing dag nodes that
22512   // potentially need to be further expanded (or custom lowered) into a
22513   // less optimal sequence of dag nodes.
22514   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22515       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22516       N0.getOpcode() == ISD::BITCAST) {
22517     SDValue BC0 = N0.getOperand(0);
22518     EVT SVT = BC0.getValueType();
22519     unsigned Opcode = BC0.getOpcode();
22520     unsigned NumElts = VT.getVectorNumElements();
22521
22522     if (BC0.hasOneUse() && SVT.isVector() &&
22523         SVT.getVectorNumElements() * 2 == NumElts &&
22524         TLI.isOperationLegal(Opcode, VT)) {
22525       bool CanFold = false;
22526       switch (Opcode) {
22527       default : break;
22528       case ISD::ADD :
22529       case ISD::FADD :
22530       case ISD::SUB :
22531       case ISD::FSUB :
22532       case ISD::MUL :
22533       case ISD::FMUL :
22534         CanFold = true;
22535       }
22536
22537       unsigned SVTNumElts = SVT.getVectorNumElements();
22538       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22539       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22540         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22541       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22542         CanFold = SVOp->getMaskElt(i) < 0;
22543
22544       if (CanFold) {
22545         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22546         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22547         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22548         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22549       }
22550     }
22551   }
22552
22553   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22554   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22555   // consecutive, non-overlapping, and in the right order.
22556   SmallVector<SDValue, 16> Elts;
22557   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22558     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22559
22560   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22561     return LD;
22562
22563   if (isTargetShuffle(N->getOpcode())) {
22564     SDValue Shuffle =
22565         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22566     if (Shuffle.getNode())
22567       return Shuffle;
22568
22569     // Try recursively combining arbitrary sequences of x86 shuffle
22570     // instructions into higher-order shuffles. We do this after combining
22571     // specific PSHUF instruction sequences into their minimal form so that we
22572     // can evaluate how many specialized shuffle instructions are involved in
22573     // a particular chain.
22574     SmallVector<int, 1> NonceMask; // Just a placeholder.
22575     NonceMask.push_back(0);
22576     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22577                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22578                                       DCI, Subtarget))
22579       return SDValue(); // This routine will use CombineTo to replace N.
22580   }
22581
22582   return SDValue();
22583 }
22584
22585 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22586 /// specific shuffle of a load can be folded into a single element load.
22587 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22588 /// shuffles have been custom lowered so we need to handle those here.
22589 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22590                                          TargetLowering::DAGCombinerInfo &DCI) {
22591   if (DCI.isBeforeLegalizeOps())
22592     return SDValue();
22593
22594   SDValue InVec = N->getOperand(0);
22595   SDValue EltNo = N->getOperand(1);
22596
22597   if (!isa<ConstantSDNode>(EltNo))
22598     return SDValue();
22599
22600   EVT OriginalVT = InVec.getValueType();
22601
22602   if (InVec.getOpcode() == ISD::BITCAST) {
22603     // Don't duplicate a load with other uses.
22604     if (!InVec.hasOneUse())
22605       return SDValue();
22606     EVT BCVT = InVec.getOperand(0).getValueType();
22607     if (!BCVT.isVector() ||
22608         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22609       return SDValue();
22610     InVec = InVec.getOperand(0);
22611   }
22612
22613   EVT CurrentVT = InVec.getValueType();
22614
22615   if (!isTargetShuffle(InVec.getOpcode()))
22616     return SDValue();
22617
22618   // Don't duplicate a load with other uses.
22619   if (!InVec.hasOneUse())
22620     return SDValue();
22621
22622   SmallVector<int, 16> ShuffleMask;
22623   bool UnaryShuffle;
22624   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22625                             ShuffleMask, UnaryShuffle))
22626     return SDValue();
22627
22628   // Select the input vector, guarding against out of range extract vector.
22629   unsigned NumElems = CurrentVT.getVectorNumElements();
22630   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22631   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22632   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22633                                          : InVec.getOperand(1);
22634
22635   // If inputs to shuffle are the same for both ops, then allow 2 uses
22636   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22637                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22638
22639   if (LdNode.getOpcode() == ISD::BITCAST) {
22640     // Don't duplicate a load with other uses.
22641     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22642       return SDValue();
22643
22644     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22645     LdNode = LdNode.getOperand(0);
22646   }
22647
22648   if (!ISD::isNormalLoad(LdNode.getNode()))
22649     return SDValue();
22650
22651   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22652
22653   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22654     return SDValue();
22655
22656   EVT EltVT = N->getValueType(0);
22657   // If there's a bitcast before the shuffle, check if the load type and
22658   // alignment is valid.
22659   unsigned Align = LN0->getAlignment();
22660   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22661   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22662       EltVT.getTypeForEVT(*DAG.getContext()));
22663
22664   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22665     return SDValue();
22666
22667   // All checks match so transform back to vector_shuffle so that DAG combiner
22668   // can finish the job
22669   SDLoc dl(N);
22670
22671   // Create shuffle node taking into account the case that its a unary shuffle
22672   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22673                                    : InVec.getOperand(1);
22674   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22675                                  InVec.getOperand(0), Shuffle,
22676                                  &ShuffleMask[0]);
22677   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22678   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22679                      EltNo);
22680 }
22681
22682 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22683 /// special and don't usually play with other vector types, it's better to
22684 /// handle them early to be sure we emit efficient code by avoiding
22685 /// store-load conversions.
22686 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22687   if (N->getValueType(0) != MVT::x86mmx ||
22688       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22689       N->getOperand(0)->getValueType(0) != MVT::v2i32)
22690     return SDValue();
22691
22692   SDValue V = N->getOperand(0);
22693   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22694   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22695     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22696                        N->getValueType(0), V.getOperand(0));
22697
22698   return SDValue();
22699 }
22700
22701 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22702 /// generation and convert it from being a bunch of shuffles and extracts
22703 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22704 /// storing the value and loading scalars back, while for x64 we should
22705 /// use 64-bit extracts and shifts.
22706 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22707                                          TargetLowering::DAGCombinerInfo &DCI) {
22708   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22709     return NewOp;
22710
22711   SDValue InputVector = N->getOperand(0);
22712   SDLoc dl(InputVector);
22713   // Detect mmx to i32 conversion through a v2i32 elt extract.
22714   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22715       N->getValueType(0) == MVT::i32 &&
22716       InputVector.getValueType() == MVT::v2i32) {
22717
22718     // The bitcast source is a direct mmx result.
22719     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22720     if (MMXSrc.getValueType() == MVT::x86mmx)
22721       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22722                          N->getValueType(0),
22723                          InputVector.getNode()->getOperand(0));
22724
22725     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22726     SDValue MMXSrcOp = MMXSrc.getOperand(0);
22727     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22728         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22729         MMXSrcOp.getOpcode() == ISD::BITCAST &&
22730         MMXSrcOp.getValueType() == MVT::v1i64 &&
22731         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22732       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22733                          N->getValueType(0),
22734                          MMXSrcOp.getOperand(0));
22735   }
22736
22737   EVT VT = N->getValueType(0);
22738
22739   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22740       InputVector.getOpcode() == ISD::BITCAST &&
22741       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22742     uint64_t ExtractedElt =
22743           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22744     uint64_t InputValue =
22745           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22746     uint64_t Res = (InputValue >> ExtractedElt) & 1;
22747     return DAG.getConstant(Res, dl, MVT::i1);
22748   }
22749   // Only operate on vectors of 4 elements, where the alternative shuffling
22750   // gets to be more expensive.
22751   if (InputVector.getValueType() != MVT::v4i32)
22752     return SDValue();
22753
22754   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22755   // single use which is a sign-extend or zero-extend, and all elements are
22756   // used.
22757   SmallVector<SDNode *, 4> Uses;
22758   unsigned ExtractedElements = 0;
22759   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22760        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22761     if (UI.getUse().getResNo() != InputVector.getResNo())
22762       return SDValue();
22763
22764     SDNode *Extract = *UI;
22765     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22766       return SDValue();
22767
22768     if (Extract->getValueType(0) != MVT::i32)
22769       return SDValue();
22770     if (!Extract->hasOneUse())
22771       return SDValue();
22772     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22773         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22774       return SDValue();
22775     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22776       return SDValue();
22777
22778     // Record which element was extracted.
22779     ExtractedElements |=
22780       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22781
22782     Uses.push_back(Extract);
22783   }
22784
22785   // If not all the elements were used, this may not be worthwhile.
22786   if (ExtractedElements != 15)
22787     return SDValue();
22788
22789   // Ok, we've now decided to do the transformation.
22790   // If 64-bit shifts are legal, use the extract-shift sequence,
22791   // otherwise bounce the vector off the cache.
22792   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22793   SDValue Vals[4];
22794
22795   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22796     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22797     auto &DL = DAG.getDataLayout();
22798     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22799     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22800       DAG.getConstant(0, dl, VecIdxTy));
22801     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22802       DAG.getConstant(1, dl, VecIdxTy));
22803
22804     SDValue ShAmt = DAG.getConstant(
22805         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22806     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22807     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22808       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22809     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22810     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22811       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22812   } else {
22813     // Store the value to a temporary stack slot.
22814     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22815     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22816       MachinePointerInfo(), false, false, 0);
22817
22818     EVT ElementType = InputVector.getValueType().getVectorElementType();
22819     unsigned EltSize = ElementType.getSizeInBits() / 8;
22820
22821     // Replace each use (extract) with a load of the appropriate element.
22822     for (unsigned i = 0; i < 4; ++i) {
22823       uint64_t Offset = EltSize * i;
22824       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22825       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22826
22827       SDValue ScalarAddr =
22828           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22829
22830       // Load the scalar.
22831       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22832                             ScalarAddr, MachinePointerInfo(),
22833                             false, false, false, 0);
22834
22835     }
22836   }
22837
22838   // Replace the extracts
22839   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22840     UE = Uses.end(); UI != UE; ++UI) {
22841     SDNode *Extract = *UI;
22842
22843     SDValue Idx = Extract->getOperand(1);
22844     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22845     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22846   }
22847
22848   // The replacement was made in place; don't return anything.
22849   return SDValue();
22850 }
22851
22852 static SDValue
22853 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22854                                       const X86Subtarget *Subtarget) {
22855   SDLoc dl(N);
22856   SDValue Cond = N->getOperand(0);
22857   SDValue LHS = N->getOperand(1);
22858   SDValue RHS = N->getOperand(2);
22859
22860   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22861     SDValue CondSrc = Cond->getOperand(0);
22862     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22863       Cond = CondSrc->getOperand(0);
22864   }
22865
22866   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22867     return SDValue();
22868
22869   // A vselect where all conditions and data are constants can be optimized into
22870   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22871   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22872       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22873     return SDValue();
22874
22875   unsigned MaskValue = 0;
22876   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22877     return SDValue();
22878
22879   MVT VT = N->getSimpleValueType(0);
22880   unsigned NumElems = VT.getVectorNumElements();
22881   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22882   for (unsigned i = 0; i < NumElems; ++i) {
22883     // Be sure we emit undef where we can.
22884     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22885       ShuffleMask[i] = -1;
22886     else
22887       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22888   }
22889
22890   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22891   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22892     return SDValue();
22893   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22894 }
22895
22896 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22897 /// nodes.
22898 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22899                                     TargetLowering::DAGCombinerInfo &DCI,
22900                                     const X86Subtarget *Subtarget) {
22901   SDLoc DL(N);
22902   SDValue Cond = N->getOperand(0);
22903   // Get the LHS/RHS of the select.
22904   SDValue LHS = N->getOperand(1);
22905   SDValue RHS = N->getOperand(2);
22906   EVT VT = LHS.getValueType();
22907   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22908
22909   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22910   // instructions match the semantics of the common C idiom x<y?x:y but not
22911   // x<=y?x:y, because of how they handle negative zero (which can be
22912   // ignored in unsafe-math mode).
22913   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22914   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22915       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22916       (Subtarget->hasSSE2() ||
22917        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22918     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22919
22920     unsigned Opcode = 0;
22921     // Check for x CC y ? x : y.
22922     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22923         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22924       switch (CC) {
22925       default: break;
22926       case ISD::SETULT:
22927         // Converting this to a min would handle NaNs incorrectly, and swapping
22928         // the operands would cause it to handle comparisons between positive
22929         // and negative zero incorrectly.
22930         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22931           if (!DAG.getTarget().Options.UnsafeFPMath &&
22932               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22933             break;
22934           std::swap(LHS, RHS);
22935         }
22936         Opcode = X86ISD::FMIN;
22937         break;
22938       case ISD::SETOLE:
22939         // Converting this to a min would handle comparisons between positive
22940         // and negative zero incorrectly.
22941         if (!DAG.getTarget().Options.UnsafeFPMath &&
22942             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22943           break;
22944         Opcode = X86ISD::FMIN;
22945         break;
22946       case ISD::SETULE:
22947         // Converting this to a min would handle both negative zeros and NaNs
22948         // incorrectly, but we can swap the operands to fix both.
22949         std::swap(LHS, RHS);
22950       case ISD::SETOLT:
22951       case ISD::SETLT:
22952       case ISD::SETLE:
22953         Opcode = X86ISD::FMIN;
22954         break;
22955
22956       case ISD::SETOGE:
22957         // Converting this to a max would handle comparisons between positive
22958         // and negative zero incorrectly.
22959         if (!DAG.getTarget().Options.UnsafeFPMath &&
22960             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22961           break;
22962         Opcode = X86ISD::FMAX;
22963         break;
22964       case ISD::SETUGT:
22965         // Converting this to a max would handle NaNs incorrectly, and swapping
22966         // the operands would cause it to handle comparisons between positive
22967         // and negative zero incorrectly.
22968         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22969           if (!DAG.getTarget().Options.UnsafeFPMath &&
22970               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22971             break;
22972           std::swap(LHS, RHS);
22973         }
22974         Opcode = X86ISD::FMAX;
22975         break;
22976       case ISD::SETUGE:
22977         // Converting this to a max would handle both negative zeros and NaNs
22978         // incorrectly, but we can swap the operands to fix both.
22979         std::swap(LHS, RHS);
22980       case ISD::SETOGT:
22981       case ISD::SETGT:
22982       case ISD::SETGE:
22983         Opcode = X86ISD::FMAX;
22984         break;
22985       }
22986     // Check for x CC y ? y : x -- a min/max with reversed arms.
22987     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22988                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22989       switch (CC) {
22990       default: break;
22991       case ISD::SETOGE:
22992         // Converting this to a min would handle comparisons between positive
22993         // and negative zero incorrectly, and swapping the operands would
22994         // cause it to handle NaNs incorrectly.
22995         if (!DAG.getTarget().Options.UnsafeFPMath &&
22996             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22997           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22998             break;
22999           std::swap(LHS, RHS);
23000         }
23001         Opcode = X86ISD::FMIN;
23002         break;
23003       case ISD::SETUGT:
23004         // Converting this to a min would handle NaNs incorrectly.
23005         if (!DAG.getTarget().Options.UnsafeFPMath &&
23006             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23007           break;
23008         Opcode = X86ISD::FMIN;
23009         break;
23010       case ISD::SETUGE:
23011         // Converting this to a min would handle both negative zeros and NaNs
23012         // incorrectly, but we can swap the operands to fix both.
23013         std::swap(LHS, RHS);
23014       case ISD::SETOGT:
23015       case ISD::SETGT:
23016       case ISD::SETGE:
23017         Opcode = X86ISD::FMIN;
23018         break;
23019
23020       case ISD::SETULT:
23021         // Converting this to a max would handle NaNs incorrectly.
23022         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23023           break;
23024         Opcode = X86ISD::FMAX;
23025         break;
23026       case ISD::SETOLE:
23027         // Converting this to a max would handle comparisons between positive
23028         // and negative zero incorrectly, and swapping the operands would
23029         // cause it to handle NaNs incorrectly.
23030         if (!DAG.getTarget().Options.UnsafeFPMath &&
23031             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23032           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23033             break;
23034           std::swap(LHS, RHS);
23035         }
23036         Opcode = X86ISD::FMAX;
23037         break;
23038       case ISD::SETULE:
23039         // Converting this to a max would handle both negative zeros and NaNs
23040         // incorrectly, but we can swap the operands to fix both.
23041         std::swap(LHS, RHS);
23042       case ISD::SETOLT:
23043       case ISD::SETLT:
23044       case ISD::SETLE:
23045         Opcode = X86ISD::FMAX;
23046         break;
23047       }
23048     }
23049
23050     if (Opcode)
23051       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23052   }
23053
23054   EVT CondVT = Cond.getValueType();
23055   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23056       CondVT.getVectorElementType() == MVT::i1) {
23057     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23058     // lowering on KNL. In this case we convert it to
23059     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23060     // The same situation for all 128 and 256-bit vectors of i8 and i16.
23061     // Since SKX these selects have a proper lowering.
23062     EVT OpVT = LHS.getValueType();
23063     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23064         (OpVT.getVectorElementType() == MVT::i8 ||
23065          OpVT.getVectorElementType() == MVT::i16) &&
23066         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23067       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23068       DCI.AddToWorklist(Cond.getNode());
23069       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23070     }
23071   }
23072   // If this is a select between two integer constants, try to do some
23073   // optimizations.
23074   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23075     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23076       // Don't do this for crazy integer types.
23077       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23078         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23079         // so that TrueC (the true value) is larger than FalseC.
23080         bool NeedsCondInvert = false;
23081
23082         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23083             // Efficiently invertible.
23084             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
23085              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
23086               isa<ConstantSDNode>(Cond.getOperand(1))))) {
23087           NeedsCondInvert = true;
23088           std::swap(TrueC, FalseC);
23089         }
23090
23091         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
23092         if (FalseC->getAPIntValue() == 0 &&
23093             TrueC->getAPIntValue().isPowerOf2()) {
23094           if (NeedsCondInvert) // Invert the condition if needed.
23095             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23096                                DAG.getConstant(1, DL, Cond.getValueType()));
23097
23098           // Zero extend the condition if needed.
23099           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23100
23101           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23102           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23103                              DAG.getConstant(ShAmt, DL, MVT::i8));
23104         }
23105
23106         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23107         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23108           if (NeedsCondInvert) // Invert the condition if needed.
23109             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23110                                DAG.getConstant(1, DL, Cond.getValueType()));
23111
23112           // Zero extend the condition if needed.
23113           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23114                              FalseC->getValueType(0), Cond);
23115           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23116                              SDValue(FalseC, 0));
23117         }
23118
23119         // Optimize cases that will turn into an LEA instruction.  This requires
23120         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23121         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23122           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23123           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23124
23125           bool isFastMultiplier = false;
23126           if (Diff < 10) {
23127             switch ((unsigned char)Diff) {
23128               default: break;
23129               case 1:  // result = add base, cond
23130               case 2:  // result = lea base(    , cond*2)
23131               case 3:  // result = lea base(cond, cond*2)
23132               case 4:  // result = lea base(    , cond*4)
23133               case 5:  // result = lea base(cond, cond*4)
23134               case 8:  // result = lea base(    , cond*8)
23135               case 9:  // result = lea base(cond, cond*8)
23136                 isFastMultiplier = true;
23137                 break;
23138             }
23139           }
23140
23141           if (isFastMultiplier) {
23142             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23143             if (NeedsCondInvert) // Invert the condition if needed.
23144               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23145                                  DAG.getConstant(1, DL, Cond.getValueType()));
23146
23147             // Zero extend the condition if needed.
23148             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23149                                Cond);
23150             // Scale the condition by the difference.
23151             if (Diff != 1)
23152               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23153                                  DAG.getConstant(Diff, DL,
23154                                                  Cond.getValueType()));
23155
23156             // Add the base if non-zero.
23157             if (FalseC->getAPIntValue() != 0)
23158               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23159                                  SDValue(FalseC, 0));
23160             return Cond;
23161           }
23162         }
23163       }
23164   }
23165
23166   // Canonicalize max and min:
23167   // (x > y) ? x : y -> (x >= y) ? x : y
23168   // (x < y) ? x : y -> (x <= y) ? x : y
23169   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23170   // the need for an extra compare
23171   // against zero. e.g.
23172   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23173   // subl   %esi, %edi
23174   // testl  %edi, %edi
23175   // movl   $0, %eax
23176   // cmovgl %edi, %eax
23177   // =>
23178   // xorl   %eax, %eax
23179   // subl   %esi, $edi
23180   // cmovsl %eax, %edi
23181   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23182       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23183       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23184     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23185     switch (CC) {
23186     default: break;
23187     case ISD::SETLT:
23188     case ISD::SETGT: {
23189       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23190       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23191                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23192       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23193     }
23194     }
23195   }
23196
23197   // Early exit check
23198   if (!TLI.isTypeLegal(VT))
23199     return SDValue();
23200
23201   // Match VSELECTs into subs with unsigned saturation.
23202   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23203       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23204       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23205        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23206     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23207
23208     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23209     // left side invert the predicate to simplify logic below.
23210     SDValue Other;
23211     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23212       Other = RHS;
23213       CC = ISD::getSetCCInverse(CC, true);
23214     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23215       Other = LHS;
23216     }
23217
23218     if (Other.getNode() && Other->getNumOperands() == 2 &&
23219         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23220       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23221       SDValue CondRHS = Cond->getOperand(1);
23222
23223       // Look for a general sub with unsigned saturation first.
23224       // x >= y ? x-y : 0 --> subus x, y
23225       // x >  y ? x-y : 0 --> subus x, y
23226       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23227           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23228         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23229
23230       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23231         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23232           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23233             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23234               // If the RHS is a constant we have to reverse the const
23235               // canonicalization.
23236               // x > C-1 ? x+-C : 0 --> subus x, C
23237               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23238                   CondRHSConst->getAPIntValue() ==
23239                       (-OpRHSConst->getAPIntValue() - 1))
23240                 return DAG.getNode(
23241                     X86ISD::SUBUS, DL, VT, OpLHS,
23242                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
23243
23244           // Another special case: If C was a sign bit, the sub has been
23245           // canonicalized into a xor.
23246           // FIXME: Would it be better to use computeKnownBits to determine
23247           //        whether it's safe to decanonicalize the xor?
23248           // x s< 0 ? x^C : 0 --> subus x, C
23249           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23250               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23251               OpRHSConst->getAPIntValue().isSignBit())
23252             // Note that we have to rebuild the RHS constant here to ensure we
23253             // don't rely on particular values of undef lanes.
23254             return DAG.getNode(
23255                 X86ISD::SUBUS, DL, VT, OpLHS,
23256                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
23257         }
23258     }
23259   }
23260
23261   // Simplify vector selection if condition value type matches vselect
23262   // operand type
23263   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23264     assert(Cond.getValueType().isVector() &&
23265            "vector select expects a vector selector!");
23266
23267     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23268     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23269
23270     // Try invert the condition if true value is not all 1s and false value
23271     // is not all 0s.
23272     if (!TValIsAllOnes && !FValIsAllZeros &&
23273         // Check if the selector will be produced by CMPP*/PCMP*
23274         Cond.getOpcode() == ISD::SETCC &&
23275         // Check if SETCC has already been promoted
23276         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23277             CondVT) {
23278       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23279       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23280
23281       if (TValIsAllZeros || FValIsAllOnes) {
23282         SDValue CC = Cond.getOperand(2);
23283         ISD::CondCode NewCC =
23284           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23285                                Cond.getOperand(0).getValueType().isInteger());
23286         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23287         std::swap(LHS, RHS);
23288         TValIsAllOnes = FValIsAllOnes;
23289         FValIsAllZeros = TValIsAllZeros;
23290       }
23291     }
23292
23293     if (TValIsAllOnes || FValIsAllZeros) {
23294       SDValue Ret;
23295
23296       if (TValIsAllOnes && FValIsAllZeros)
23297         Ret = Cond;
23298       else if (TValIsAllOnes)
23299         Ret =
23300             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23301       else if (FValIsAllZeros)
23302         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23303                           DAG.getBitcast(CondVT, LHS));
23304
23305       return DAG.getBitcast(VT, Ret);
23306     }
23307   }
23308
23309   // We should generate an X86ISD::BLENDI from a vselect if its argument
23310   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23311   // constants. This specific pattern gets generated when we split a
23312   // selector for a 512 bit vector in a machine without AVX512 (but with
23313   // 256-bit vectors), during legalization:
23314   //
23315   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23316   //
23317   // Iff we find this pattern and the build_vectors are built from
23318   // constants, we translate the vselect into a shuffle_vector that we
23319   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23320   if ((N->getOpcode() == ISD::VSELECT ||
23321        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23322       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23323     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23324     if (Shuffle.getNode())
23325       return Shuffle;
23326   }
23327
23328   // If this is a *dynamic* select (non-constant condition) and we can match
23329   // this node with one of the variable blend instructions, restructure the
23330   // condition so that the blends can use the high bit of each element and use
23331   // SimplifyDemandedBits to simplify the condition operand.
23332   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23333       !DCI.isBeforeLegalize() &&
23334       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23335     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23336
23337     // Don't optimize vector selects that map to mask-registers.
23338     if (BitWidth == 1)
23339       return SDValue();
23340
23341     // We can only handle the cases where VSELECT is directly legal on the
23342     // subtarget. We custom lower VSELECT nodes with constant conditions and
23343     // this makes it hard to see whether a dynamic VSELECT will correctly
23344     // lower, so we both check the operation's status and explicitly handle the
23345     // cases where a *dynamic* blend will fail even though a constant-condition
23346     // blend could be custom lowered.
23347     // FIXME: We should find a better way to handle this class of problems.
23348     // Potentially, we should combine constant-condition vselect nodes
23349     // pre-legalization into shuffles and not mark as many types as custom
23350     // lowered.
23351     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23352       return SDValue();
23353     // FIXME: We don't support i16-element blends currently. We could and
23354     // should support them by making *all* the bits in the condition be set
23355     // rather than just the high bit and using an i8-element blend.
23356     if (VT.getScalarType() == MVT::i16)
23357       return SDValue();
23358     // Dynamic blending was only available from SSE4.1 onward.
23359     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23360       return SDValue();
23361     // Byte blends are only available in AVX2
23362     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23363         !Subtarget->hasAVX2())
23364       return SDValue();
23365
23366     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23367     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23368
23369     APInt KnownZero, KnownOne;
23370     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23371                                           DCI.isBeforeLegalizeOps());
23372     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23373         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23374                                  TLO)) {
23375       // If we changed the computation somewhere in the DAG, this change
23376       // will affect all users of Cond.
23377       // Make sure it is fine and update all the nodes so that we do not
23378       // use the generic VSELECT anymore. Otherwise, we may perform
23379       // wrong optimizations as we messed up with the actual expectation
23380       // for the vector boolean values.
23381       if (Cond != TLO.Old) {
23382         // Check all uses of that condition operand to check whether it will be
23383         // consumed by non-BLEND instructions, which may depend on all bits are
23384         // set properly.
23385         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23386              I != E; ++I)
23387           if (I->getOpcode() != ISD::VSELECT)
23388             // TODO: Add other opcodes eventually lowered into BLEND.
23389             return SDValue();
23390
23391         // Update all the users of the condition, before committing the change,
23392         // so that the VSELECT optimizations that expect the correct vector
23393         // boolean value will not be triggered.
23394         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23395              I != E; ++I)
23396           DAG.ReplaceAllUsesOfValueWith(
23397               SDValue(*I, 0),
23398               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23399                           Cond, I->getOperand(1), I->getOperand(2)));
23400         DCI.CommitTargetLoweringOpt(TLO);
23401         return SDValue();
23402       }
23403       // At this point, only Cond is changed. Change the condition
23404       // just for N to keep the opportunity to optimize all other
23405       // users their own way.
23406       DAG.ReplaceAllUsesOfValueWith(
23407           SDValue(N, 0),
23408           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23409                       TLO.New, N->getOperand(1), N->getOperand(2)));
23410       return SDValue();
23411     }
23412   }
23413
23414   return SDValue();
23415 }
23416
23417 // Check whether a boolean test is testing a boolean value generated by
23418 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23419 // code.
23420 //
23421 // Simplify the following patterns:
23422 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23423 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23424 // to (Op EFLAGS Cond)
23425 //
23426 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23427 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23428 // to (Op EFLAGS !Cond)
23429 //
23430 // where Op could be BRCOND or CMOV.
23431 //
23432 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23433   // Quit if not CMP and SUB with its value result used.
23434   if (Cmp.getOpcode() != X86ISD::CMP &&
23435       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23436       return SDValue();
23437
23438   // Quit if not used as a boolean value.
23439   if (CC != X86::COND_E && CC != X86::COND_NE)
23440     return SDValue();
23441
23442   // Check CMP operands. One of them should be 0 or 1 and the other should be
23443   // an SetCC or extended from it.
23444   SDValue Op1 = Cmp.getOperand(0);
23445   SDValue Op2 = Cmp.getOperand(1);
23446
23447   SDValue SetCC;
23448   const ConstantSDNode* C = nullptr;
23449   bool needOppositeCond = (CC == X86::COND_E);
23450   bool checkAgainstTrue = false; // Is it a comparison against 1?
23451
23452   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23453     SetCC = Op2;
23454   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23455     SetCC = Op1;
23456   else // Quit if all operands are not constants.
23457     return SDValue();
23458
23459   if (C->getZExtValue() == 1) {
23460     needOppositeCond = !needOppositeCond;
23461     checkAgainstTrue = true;
23462   } else if (C->getZExtValue() != 0)
23463     // Quit if the constant is neither 0 or 1.
23464     return SDValue();
23465
23466   bool truncatedToBoolWithAnd = false;
23467   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23468   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23469          SetCC.getOpcode() == ISD::TRUNCATE ||
23470          SetCC.getOpcode() == ISD::AND) {
23471     if (SetCC.getOpcode() == ISD::AND) {
23472       int OpIdx = -1;
23473       ConstantSDNode *CS;
23474       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23475           CS->getZExtValue() == 1)
23476         OpIdx = 1;
23477       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23478           CS->getZExtValue() == 1)
23479         OpIdx = 0;
23480       if (OpIdx == -1)
23481         break;
23482       SetCC = SetCC.getOperand(OpIdx);
23483       truncatedToBoolWithAnd = true;
23484     } else
23485       SetCC = SetCC.getOperand(0);
23486   }
23487
23488   switch (SetCC.getOpcode()) {
23489   case X86ISD::SETCC_CARRY:
23490     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23491     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23492     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23493     // truncated to i1 using 'and'.
23494     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23495       break;
23496     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23497            "Invalid use of SETCC_CARRY!");
23498     // FALL THROUGH
23499   case X86ISD::SETCC:
23500     // Set the condition code or opposite one if necessary.
23501     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23502     if (needOppositeCond)
23503       CC = X86::GetOppositeBranchCondition(CC);
23504     return SetCC.getOperand(1);
23505   case X86ISD::CMOV: {
23506     // Check whether false/true value has canonical one, i.e. 0 or 1.
23507     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23508     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23509     // Quit if true value is not a constant.
23510     if (!TVal)
23511       return SDValue();
23512     // Quit if false value is not a constant.
23513     if (!FVal) {
23514       SDValue Op = SetCC.getOperand(0);
23515       // Skip 'zext' or 'trunc' node.
23516       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23517           Op.getOpcode() == ISD::TRUNCATE)
23518         Op = Op.getOperand(0);
23519       // A special case for rdrand/rdseed, where 0 is set if false cond is
23520       // found.
23521       if ((Op.getOpcode() != X86ISD::RDRAND &&
23522            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23523         return SDValue();
23524     }
23525     // Quit if false value is not the constant 0 or 1.
23526     bool FValIsFalse = true;
23527     if (FVal && FVal->getZExtValue() != 0) {
23528       if (FVal->getZExtValue() != 1)
23529         return SDValue();
23530       // If FVal is 1, opposite cond is needed.
23531       needOppositeCond = !needOppositeCond;
23532       FValIsFalse = false;
23533     }
23534     // Quit if TVal is not the constant opposite of FVal.
23535     if (FValIsFalse && TVal->getZExtValue() != 1)
23536       return SDValue();
23537     if (!FValIsFalse && TVal->getZExtValue() != 0)
23538       return SDValue();
23539     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23540     if (needOppositeCond)
23541       CC = X86::GetOppositeBranchCondition(CC);
23542     return SetCC.getOperand(3);
23543   }
23544   }
23545
23546   return SDValue();
23547 }
23548
23549 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23550 /// Match:
23551 ///   (X86or (X86setcc) (X86setcc))
23552 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
23553 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23554                                            X86::CondCode &CC1, SDValue &Flags,
23555                                            bool &isAnd) {
23556   if (Cond->getOpcode() == X86ISD::CMP) {
23557     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23558     if (!CondOp1C || !CondOp1C->isNullValue())
23559       return false;
23560
23561     Cond = Cond->getOperand(0);
23562   }
23563
23564   isAnd = false;
23565
23566   SDValue SetCC0, SetCC1;
23567   switch (Cond->getOpcode()) {
23568   default: return false;
23569   case ISD::AND:
23570   case X86ISD::AND:
23571     isAnd = true;
23572     // fallthru
23573   case ISD::OR:
23574   case X86ISD::OR:
23575     SetCC0 = Cond->getOperand(0);
23576     SetCC1 = Cond->getOperand(1);
23577     break;
23578   };
23579
23580   // Make sure we have SETCC nodes, using the same flags value.
23581   if (SetCC0.getOpcode() != X86ISD::SETCC ||
23582       SetCC1.getOpcode() != X86ISD::SETCC ||
23583       SetCC0->getOperand(1) != SetCC1->getOperand(1))
23584     return false;
23585
23586   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23587   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23588   Flags = SetCC0->getOperand(1);
23589   return true;
23590 }
23591
23592 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23593 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23594                                   TargetLowering::DAGCombinerInfo &DCI,
23595                                   const X86Subtarget *Subtarget) {
23596   SDLoc DL(N);
23597
23598   // If the flag operand isn't dead, don't touch this CMOV.
23599   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23600     return SDValue();
23601
23602   SDValue FalseOp = N->getOperand(0);
23603   SDValue TrueOp = N->getOperand(1);
23604   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23605   SDValue Cond = N->getOperand(3);
23606
23607   if (CC == X86::COND_E || CC == X86::COND_NE) {
23608     switch (Cond.getOpcode()) {
23609     default: break;
23610     case X86ISD::BSR:
23611     case X86ISD::BSF:
23612       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23613       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23614         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23615     }
23616   }
23617
23618   SDValue Flags;
23619
23620   Flags = checkBoolTestSetCCCombine(Cond, CC);
23621   if (Flags.getNode() &&
23622       // Extra check as FCMOV only supports a subset of X86 cond.
23623       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23624     SDValue Ops[] = { FalseOp, TrueOp,
23625                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23626     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23627   }
23628
23629   // If this is a select between two integer constants, try to do some
23630   // optimizations.  Note that the operands are ordered the opposite of SELECT
23631   // operands.
23632   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23633     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23634       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23635       // larger than FalseC (the false value).
23636       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23637         CC = X86::GetOppositeBranchCondition(CC);
23638         std::swap(TrueC, FalseC);
23639         std::swap(TrueOp, FalseOp);
23640       }
23641
23642       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23643       // This is efficient for any integer data type (including i8/i16) and
23644       // shift amount.
23645       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23646         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23647                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23648
23649         // Zero extend the condition if needed.
23650         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23651
23652         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23653         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23654                            DAG.getConstant(ShAmt, DL, MVT::i8));
23655         if (N->getNumValues() == 2)  // Dead flag value?
23656           return DCI.CombineTo(N, Cond, SDValue());
23657         return Cond;
23658       }
23659
23660       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23661       // for any integer data type, including i8/i16.
23662       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23663         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23664                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23665
23666         // Zero extend the condition if needed.
23667         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23668                            FalseC->getValueType(0), Cond);
23669         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23670                            SDValue(FalseC, 0));
23671
23672         if (N->getNumValues() == 2)  // Dead flag value?
23673           return DCI.CombineTo(N, Cond, SDValue());
23674         return Cond;
23675       }
23676
23677       // Optimize cases that will turn into an LEA instruction.  This requires
23678       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23679       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23680         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23681         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23682
23683         bool isFastMultiplier = false;
23684         if (Diff < 10) {
23685           switch ((unsigned char)Diff) {
23686           default: break;
23687           case 1:  // result = add base, cond
23688           case 2:  // result = lea base(    , cond*2)
23689           case 3:  // result = lea base(cond, cond*2)
23690           case 4:  // result = lea base(    , cond*4)
23691           case 5:  // result = lea base(cond, cond*4)
23692           case 8:  // result = lea base(    , cond*8)
23693           case 9:  // result = lea base(cond, cond*8)
23694             isFastMultiplier = true;
23695             break;
23696           }
23697         }
23698
23699         if (isFastMultiplier) {
23700           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23701           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23702                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23703           // Zero extend the condition if needed.
23704           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23705                              Cond);
23706           // Scale the condition by the difference.
23707           if (Diff != 1)
23708             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23709                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23710
23711           // Add the base if non-zero.
23712           if (FalseC->getAPIntValue() != 0)
23713             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23714                                SDValue(FalseC, 0));
23715           if (N->getNumValues() == 2)  // Dead flag value?
23716             return DCI.CombineTo(N, Cond, SDValue());
23717           return Cond;
23718         }
23719       }
23720     }
23721   }
23722
23723   // Handle these cases:
23724   //   (select (x != c), e, c) -> select (x != c), e, x),
23725   //   (select (x == c), c, e) -> select (x == c), x, e)
23726   // where the c is an integer constant, and the "select" is the combination
23727   // of CMOV and CMP.
23728   //
23729   // The rationale for this change is that the conditional-move from a constant
23730   // needs two instructions, however, conditional-move from a register needs
23731   // only one instruction.
23732   //
23733   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23734   //  some instruction-combining opportunities. This opt needs to be
23735   //  postponed as late as possible.
23736   //
23737   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23738     // the DCI.xxxx conditions are provided to postpone the optimization as
23739     // late as possible.
23740
23741     ConstantSDNode *CmpAgainst = nullptr;
23742     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23743         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23744         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23745
23746       if (CC == X86::COND_NE &&
23747           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23748         CC = X86::GetOppositeBranchCondition(CC);
23749         std::swap(TrueOp, FalseOp);
23750       }
23751
23752       if (CC == X86::COND_E &&
23753           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23754         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23755                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23756         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23757       }
23758     }
23759   }
23760
23761   // Fold and/or of setcc's to double CMOV:
23762   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23763   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23764   //
23765   // This combine lets us generate:
23766   //   cmovcc1 (jcc1 if we don't have CMOV)
23767   //   cmovcc2 (same)
23768   // instead of:
23769   //   setcc1
23770   //   setcc2
23771   //   and/or
23772   //   cmovne (jne if we don't have CMOV)
23773   // When we can't use the CMOV instruction, it might increase branch
23774   // mispredicts.
23775   // When we can use CMOV, or when there is no mispredict, this improves
23776   // throughput and reduces register pressure.
23777   //
23778   if (CC == X86::COND_NE) {
23779     SDValue Flags;
23780     X86::CondCode CC0, CC1;
23781     bool isAndSetCC;
23782     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23783       if (isAndSetCC) {
23784         std::swap(FalseOp, TrueOp);
23785         CC0 = X86::GetOppositeBranchCondition(CC0);
23786         CC1 = X86::GetOppositeBranchCondition(CC1);
23787       }
23788
23789       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23790         Flags};
23791       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23792       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23793       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23794       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23795       return CMOV;
23796     }
23797   }
23798
23799   return SDValue();
23800 }
23801
23802 /// PerformMulCombine - Optimize a single multiply with constant into two
23803 /// in order to implement it with two cheaper instructions, e.g.
23804 /// LEA + SHL, LEA + LEA.
23805 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23806                                  TargetLowering::DAGCombinerInfo &DCI) {
23807   // An imul is usually smaller than the alternative sequence.
23808   if (DAG.getMachineFunction().getFunction()->optForMinSize())
23809     return SDValue();
23810
23811   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23812     return SDValue();
23813
23814   EVT VT = N->getValueType(0);
23815   if (VT != MVT::i64 && VT != MVT::i32)
23816     return SDValue();
23817
23818   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23819   if (!C)
23820     return SDValue();
23821   uint64_t MulAmt = C->getZExtValue();
23822   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23823     return SDValue();
23824
23825   uint64_t MulAmt1 = 0;
23826   uint64_t MulAmt2 = 0;
23827   if ((MulAmt % 9) == 0) {
23828     MulAmt1 = 9;
23829     MulAmt2 = MulAmt / 9;
23830   } else if ((MulAmt % 5) == 0) {
23831     MulAmt1 = 5;
23832     MulAmt2 = MulAmt / 5;
23833   } else if ((MulAmt % 3) == 0) {
23834     MulAmt1 = 3;
23835     MulAmt2 = MulAmt / 3;
23836   }
23837   if (MulAmt2 &&
23838       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23839     SDLoc DL(N);
23840
23841     if (isPowerOf2_64(MulAmt2) &&
23842         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23843       // If second multiplifer is pow2, issue it first. We want the multiply by
23844       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23845       // is an add.
23846       std::swap(MulAmt1, MulAmt2);
23847
23848     SDValue NewMul;
23849     if (isPowerOf2_64(MulAmt1))
23850       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23851                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23852     else
23853       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23854                            DAG.getConstant(MulAmt1, DL, VT));
23855
23856     if (isPowerOf2_64(MulAmt2))
23857       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23858                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23859     else
23860       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23861                            DAG.getConstant(MulAmt2, DL, VT));
23862
23863     // Do not add new nodes to DAG combiner worklist.
23864     DCI.CombineTo(N, NewMul, false);
23865   }
23866   return SDValue();
23867 }
23868
23869 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23870   SDValue N0 = N->getOperand(0);
23871   SDValue N1 = N->getOperand(1);
23872   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23873   EVT VT = N0.getValueType();
23874
23875   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23876   // since the result of setcc_c is all zero's or all ones.
23877   if (VT.isInteger() && !VT.isVector() &&
23878       N1C && N0.getOpcode() == ISD::AND &&
23879       N0.getOperand(1).getOpcode() == ISD::Constant) {
23880     SDValue N00 = N0.getOperand(0);
23881     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23882     APInt ShAmt = N1C->getAPIntValue();
23883     Mask = Mask.shl(ShAmt);
23884     bool MaskOK = false;
23885     // We can handle cases concerning bit-widening nodes containing setcc_c if
23886     // we carefully interrogate the mask to make sure we are semantics
23887     // preserving.
23888     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
23889     // of the underlying setcc_c operation if the setcc_c was zero extended.
23890     // Consider the following example:
23891     //   zext(setcc_c)                 -> i32 0x0000FFFF
23892     //   c1                            -> i32 0x0000FFFF
23893     //   c2                            -> i32 0x00000001
23894     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
23895     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
23896     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23897       MaskOK = true;
23898     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
23899                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23900       MaskOK = true;
23901     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
23902                 N00.getOpcode() == ISD::ANY_EXTEND) &&
23903                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23904       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
23905     }
23906     if (MaskOK && Mask != 0) {
23907       SDLoc DL(N);
23908       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
23909     }
23910   }
23911
23912   // Hardware support for vector shifts is sparse which makes us scalarize the
23913   // vector operations in many cases. Also, on sandybridge ADD is faster than
23914   // shl.
23915   // (shl V, 1) -> add V,V
23916   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23917     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23918       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23919       // We shift all of the values by one. In many cases we do not have
23920       // hardware support for this operation. This is better expressed as an ADD
23921       // of two values.
23922       if (N1SplatC->getAPIntValue() == 1)
23923         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23924     }
23925
23926   return SDValue();
23927 }
23928
23929 /// \brief Returns a vector of 0s if the node in input is a vector logical
23930 /// shift by a constant amount which is known to be bigger than or equal
23931 /// to the vector element size in bits.
23932 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23933                                       const X86Subtarget *Subtarget) {
23934   EVT VT = N->getValueType(0);
23935
23936   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23937       (!Subtarget->hasInt256() ||
23938        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23939     return SDValue();
23940
23941   SDValue Amt = N->getOperand(1);
23942   SDLoc DL(N);
23943   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23944     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23945       APInt ShiftAmt = AmtSplat->getAPIntValue();
23946       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23947
23948       // SSE2/AVX2 logical shifts always return a vector of 0s
23949       // if the shift amount is bigger than or equal to
23950       // the element size. The constant shift amount will be
23951       // encoded as a 8-bit immediate.
23952       if (ShiftAmt.trunc(8).uge(MaxAmount))
23953         return getZeroVector(VT, Subtarget, DAG, DL);
23954     }
23955
23956   return SDValue();
23957 }
23958
23959 /// PerformShiftCombine - Combine shifts.
23960 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23961                                    TargetLowering::DAGCombinerInfo &DCI,
23962                                    const X86Subtarget *Subtarget) {
23963   if (N->getOpcode() == ISD::SHL)
23964     if (SDValue V = PerformSHLCombine(N, DAG))
23965       return V;
23966
23967   // Try to fold this logical shift into a zero vector.
23968   if (N->getOpcode() != ISD::SRA)
23969     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23970       return V;
23971
23972   return SDValue();
23973 }
23974
23975 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23976 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23977 // and friends.  Likewise for OR -> CMPNEQSS.
23978 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23979                             TargetLowering::DAGCombinerInfo &DCI,
23980                             const X86Subtarget *Subtarget) {
23981   unsigned opcode;
23982
23983   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23984   // we're requiring SSE2 for both.
23985   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23986     SDValue N0 = N->getOperand(0);
23987     SDValue N1 = N->getOperand(1);
23988     SDValue CMP0 = N0->getOperand(1);
23989     SDValue CMP1 = N1->getOperand(1);
23990     SDLoc DL(N);
23991
23992     // The SETCCs should both refer to the same CMP.
23993     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23994       return SDValue();
23995
23996     SDValue CMP00 = CMP0->getOperand(0);
23997     SDValue CMP01 = CMP0->getOperand(1);
23998     EVT     VT    = CMP00.getValueType();
23999
24000     if (VT == MVT::f32 || VT == MVT::f64) {
24001       bool ExpectingFlags = false;
24002       // Check for any users that want flags:
24003       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
24004            !ExpectingFlags && UI != UE; ++UI)
24005         switch (UI->getOpcode()) {
24006         default:
24007         case ISD::BR_CC:
24008         case ISD::BRCOND:
24009         case ISD::SELECT:
24010           ExpectingFlags = true;
24011           break;
24012         case ISD::CopyToReg:
24013         case ISD::SIGN_EXTEND:
24014         case ISD::ZERO_EXTEND:
24015         case ISD::ANY_EXTEND:
24016           break;
24017         }
24018
24019       if (!ExpectingFlags) {
24020         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24021         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24022
24023         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24024           X86::CondCode tmp = cc0;
24025           cc0 = cc1;
24026           cc1 = tmp;
24027         }
24028
24029         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
24030             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24031           // FIXME: need symbolic constants for these magic numbers.
24032           // See X86ATTInstPrinter.cpp:printSSECC().
24033           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24034           if (Subtarget->hasAVX512()) {
24035             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24036                                          CMP01,
24037                                          DAG.getConstant(x86cc, DL, MVT::i8));
24038             if (N->getValueType(0) != MVT::i1)
24039               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24040                                  FSetCC);
24041             return FSetCC;
24042           }
24043           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24044                                               CMP00.getValueType(), CMP00, CMP01,
24045                                               DAG.getConstant(x86cc, DL,
24046                                                               MVT::i8));
24047
24048           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24049           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24050
24051           if (is64BitFP && !Subtarget->is64Bit()) {
24052             // On a 32-bit target, we cannot bitcast the 64-bit float to a
24053             // 64-bit integer, since that's not a legal type. Since
24054             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24055             // bits, but can do this little dance to extract the lowest 32 bits
24056             // and work with those going forward.
24057             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24058                                            OnesOrZeroesF);
24059             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
24060             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24061                                         Vector32, DAG.getIntPtrConstant(0, DL));
24062             IntVT = MVT::i32;
24063           }
24064
24065           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
24066           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24067                                       DAG.getConstant(1, DL, IntVT));
24068           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
24069                                               ANDed);
24070           return OneBitOfTruth;
24071         }
24072       }
24073     }
24074   }
24075   return SDValue();
24076 }
24077
24078 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24079 /// so it can be folded inside ANDNP.
24080 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24081   EVT VT = N->getValueType(0);
24082
24083   // Match direct AllOnes for 128 and 256-bit vectors
24084   if (ISD::isBuildVectorAllOnes(N))
24085     return true;
24086
24087   // Look through a bit convert.
24088   if (N->getOpcode() == ISD::BITCAST)
24089     N = N->getOperand(0).getNode();
24090
24091   // Sometimes the operand may come from a insert_subvector building a 256-bit
24092   // allones vector
24093   if (VT.is256BitVector() &&
24094       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24095     SDValue V1 = N->getOperand(0);
24096     SDValue V2 = N->getOperand(1);
24097
24098     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24099         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24100         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24101         ISD::isBuildVectorAllOnes(V2.getNode()))
24102       return true;
24103   }
24104
24105   return false;
24106 }
24107
24108 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24109 // register. In most cases we actually compare or select YMM-sized registers
24110 // and mixing the two types creates horrible code. This method optimizes
24111 // some of the transition sequences.
24112 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24113                                  TargetLowering::DAGCombinerInfo &DCI,
24114                                  const X86Subtarget *Subtarget) {
24115   EVT VT = N->getValueType(0);
24116   if (!VT.is256BitVector())
24117     return SDValue();
24118
24119   assert((N->getOpcode() == ISD::ANY_EXTEND ||
24120           N->getOpcode() == ISD::ZERO_EXTEND ||
24121           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24122
24123   SDValue Narrow = N->getOperand(0);
24124   EVT NarrowVT = Narrow->getValueType(0);
24125   if (!NarrowVT.is128BitVector())
24126     return SDValue();
24127
24128   if (Narrow->getOpcode() != ISD::XOR &&
24129       Narrow->getOpcode() != ISD::AND &&
24130       Narrow->getOpcode() != ISD::OR)
24131     return SDValue();
24132
24133   SDValue N0  = Narrow->getOperand(0);
24134   SDValue N1  = Narrow->getOperand(1);
24135   SDLoc DL(Narrow);
24136
24137   // The Left side has to be a trunc.
24138   if (N0.getOpcode() != ISD::TRUNCATE)
24139     return SDValue();
24140
24141   // The type of the truncated inputs.
24142   EVT WideVT = N0->getOperand(0)->getValueType(0);
24143   if (WideVT != VT)
24144     return SDValue();
24145
24146   // The right side has to be a 'trunc' or a constant vector.
24147   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24148   ConstantSDNode *RHSConstSplat = nullptr;
24149   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24150     RHSConstSplat = RHSBV->getConstantSplatNode();
24151   if (!RHSTrunc && !RHSConstSplat)
24152     return SDValue();
24153
24154   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24155
24156   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24157     return SDValue();
24158
24159   // Set N0 and N1 to hold the inputs to the new wide operation.
24160   N0 = N0->getOperand(0);
24161   if (RHSConstSplat) {
24162     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24163                      SDValue(RHSConstSplat, 0));
24164     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24165     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24166   } else if (RHSTrunc) {
24167     N1 = N1->getOperand(0);
24168   }
24169
24170   // Generate the wide operation.
24171   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24172   unsigned Opcode = N->getOpcode();
24173   switch (Opcode) {
24174   case ISD::ANY_EXTEND:
24175     return Op;
24176   case ISD::ZERO_EXTEND: {
24177     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24178     APInt Mask = APInt::getAllOnesValue(InBits);
24179     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24180     return DAG.getNode(ISD::AND, DL, VT,
24181                        Op, DAG.getConstant(Mask, DL, VT));
24182   }
24183   case ISD::SIGN_EXTEND:
24184     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24185                        Op, DAG.getValueType(NarrowVT));
24186   default:
24187     llvm_unreachable("Unexpected opcode");
24188   }
24189 }
24190
24191 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
24192                                  TargetLowering::DAGCombinerInfo &DCI,
24193                                  const X86Subtarget *Subtarget) {
24194   SDValue N0 = N->getOperand(0);
24195   SDValue N1 = N->getOperand(1);
24196   SDLoc DL(N);
24197
24198   // A vector zext_in_reg may be represented as a shuffle,
24199   // feeding into a bitcast (this represents anyext) feeding into
24200   // an and with a mask.
24201   // We'd like to try to combine that into a shuffle with zero
24202   // plus a bitcast, removing the and.
24203   if (N0.getOpcode() != ISD::BITCAST ||
24204       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
24205     return SDValue();
24206
24207   // The other side of the AND should be a splat of 2^C, where C
24208   // is the number of bits in the source type.
24209   if (N1.getOpcode() == ISD::BITCAST)
24210     N1 = N1.getOperand(0);
24211   if (N1.getOpcode() != ISD::BUILD_VECTOR)
24212     return SDValue();
24213   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
24214
24215   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
24216   EVT SrcType = Shuffle->getValueType(0);
24217
24218   // We expect a single-source shuffle
24219   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
24220     return SDValue();
24221
24222   unsigned SrcSize = SrcType.getScalarSizeInBits();
24223
24224   APInt SplatValue, SplatUndef;
24225   unsigned SplatBitSize;
24226   bool HasAnyUndefs;
24227   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
24228                                 SplatBitSize, HasAnyUndefs))
24229     return SDValue();
24230
24231   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
24232   // Make sure the splat matches the mask we expect
24233   if (SplatBitSize > ResSize ||
24234       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
24235     return SDValue();
24236
24237   // Make sure the input and output size make sense
24238   if (SrcSize >= ResSize || ResSize % SrcSize)
24239     return SDValue();
24240
24241   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
24242   // The number of u's between each two values depends on the ratio between
24243   // the source and dest type.
24244   unsigned ZextRatio = ResSize / SrcSize;
24245   bool IsZext = true;
24246   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
24247     if (i % ZextRatio) {
24248       if (Shuffle->getMaskElt(i) > 0) {
24249         // Expected undef
24250         IsZext = false;
24251         break;
24252       }
24253     } else {
24254       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
24255         // Expected element number
24256         IsZext = false;
24257         break;
24258       }
24259     }
24260   }
24261
24262   if (!IsZext)
24263     return SDValue();
24264
24265   // Ok, perform the transformation - replace the shuffle with
24266   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24267   // (instead of undef) where the k elements come from the zero vector.
24268   SmallVector<int, 8> Mask;
24269   unsigned NumElems = SrcType.getVectorNumElements();
24270   for (unsigned i = 0; i < NumElems; ++i)
24271     if (i % ZextRatio)
24272       Mask.push_back(NumElems);
24273     else
24274       Mask.push_back(i / ZextRatio);
24275
24276   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24277     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24278   return DAG.getBitcast(N0.getValueType(), NewShuffle);
24279 }
24280
24281 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24282                                  TargetLowering::DAGCombinerInfo &DCI,
24283                                  const X86Subtarget *Subtarget) {
24284   if (DCI.isBeforeLegalizeOps())
24285     return SDValue();
24286
24287   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24288     return Zext;
24289
24290   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24291     return R;
24292
24293   EVT VT = N->getValueType(0);
24294   SDValue N0 = N->getOperand(0);
24295   SDValue N1 = N->getOperand(1);
24296   SDLoc DL(N);
24297
24298   // Create BEXTR instructions
24299   // BEXTR is ((X >> imm) & (2**size-1))
24300   if (VT == MVT::i32 || VT == MVT::i64) {
24301     // Check for BEXTR.
24302     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24303         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24304       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24305       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24306       if (MaskNode && ShiftNode) {
24307         uint64_t Mask = MaskNode->getZExtValue();
24308         uint64_t Shift = ShiftNode->getZExtValue();
24309         if (isMask_64(Mask)) {
24310           uint64_t MaskSize = countPopulation(Mask);
24311           if (Shift + MaskSize <= VT.getSizeInBits())
24312             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24313                                DAG.getConstant(Shift | (MaskSize << 8), DL,
24314                                                VT));
24315         }
24316       }
24317     } // BEXTR
24318
24319     return SDValue();
24320   }
24321
24322   // Want to form ANDNP nodes:
24323   // 1) In the hopes of then easily combining them with OR and AND nodes
24324   //    to form PBLEND/PSIGN.
24325   // 2) To match ANDN packed intrinsics
24326   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24327     return SDValue();
24328
24329   // Check LHS for vnot
24330   if (N0.getOpcode() == ISD::XOR &&
24331       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24332       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24333     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24334
24335   // Check RHS for vnot
24336   if (N1.getOpcode() == ISD::XOR &&
24337       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24338       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24339     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24340
24341   return SDValue();
24342 }
24343
24344 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24345                                 TargetLowering::DAGCombinerInfo &DCI,
24346                                 const X86Subtarget *Subtarget) {
24347   if (DCI.isBeforeLegalizeOps())
24348     return SDValue();
24349
24350   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24351     return R;
24352
24353   SDValue N0 = N->getOperand(0);
24354   SDValue N1 = N->getOperand(1);
24355   EVT VT = N->getValueType(0);
24356
24357   // look for psign/blend
24358   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24359     if (!Subtarget->hasSSSE3() ||
24360         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24361       return SDValue();
24362
24363     // Canonicalize pandn to RHS
24364     if (N0.getOpcode() == X86ISD::ANDNP)
24365       std::swap(N0, N1);
24366     // or (and (m, y), (pandn m, x))
24367     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24368       SDValue Mask = N1.getOperand(0);
24369       SDValue X    = N1.getOperand(1);
24370       SDValue Y;
24371       if (N0.getOperand(0) == Mask)
24372         Y = N0.getOperand(1);
24373       if (N0.getOperand(1) == Mask)
24374         Y = N0.getOperand(0);
24375
24376       // Check to see if the mask appeared in both the AND and ANDNP and
24377       if (!Y.getNode())
24378         return SDValue();
24379
24380       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24381       // Look through mask bitcast.
24382       if (Mask.getOpcode() == ISD::BITCAST)
24383         Mask = Mask.getOperand(0);
24384       if (X.getOpcode() == ISD::BITCAST)
24385         X = X.getOperand(0);
24386       if (Y.getOpcode() == ISD::BITCAST)
24387         Y = Y.getOperand(0);
24388
24389       EVT MaskVT = Mask.getValueType();
24390
24391       // Validate that the Mask operand is a vector sra node.
24392       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24393       // there is no psrai.b
24394       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24395       unsigned SraAmt = ~0;
24396       if (Mask.getOpcode() == ISD::SRA) {
24397         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24398           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24399             SraAmt = AmtConst->getZExtValue();
24400       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24401         SDValue SraC = Mask.getOperand(1);
24402         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24403       }
24404       if ((SraAmt + 1) != EltBits)
24405         return SDValue();
24406
24407       SDLoc DL(N);
24408
24409       // Now we know we at least have a plendvb with the mask val.  See if
24410       // we can form a psignb/w/d.
24411       // psign = x.type == y.type == mask.type && y = sub(0, x);
24412       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24413           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24414           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24415         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24416                "Unsupported VT for PSIGN");
24417         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24418         return DAG.getBitcast(VT, Mask);
24419       }
24420       // PBLENDVB only available on SSE 4.1
24421       if (!Subtarget->hasSSE41())
24422         return SDValue();
24423
24424       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24425
24426       X = DAG.getBitcast(BlendVT, X);
24427       Y = DAG.getBitcast(BlendVT, Y);
24428       Mask = DAG.getBitcast(BlendVT, Mask);
24429       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24430       return DAG.getBitcast(VT, Mask);
24431     }
24432   }
24433
24434   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24435     return SDValue();
24436
24437   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24438   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24439
24440   // SHLD/SHRD instructions have lower register pressure, but on some
24441   // platforms they have higher latency than the equivalent
24442   // series of shifts/or that would otherwise be generated.
24443   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24444   // have higher latencies and we are not optimizing for size.
24445   if (!OptForSize && Subtarget->isSHLDSlow())
24446     return SDValue();
24447
24448   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24449     std::swap(N0, N1);
24450   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24451     return SDValue();
24452   if (!N0.hasOneUse() || !N1.hasOneUse())
24453     return SDValue();
24454
24455   SDValue ShAmt0 = N0.getOperand(1);
24456   if (ShAmt0.getValueType() != MVT::i8)
24457     return SDValue();
24458   SDValue ShAmt1 = N1.getOperand(1);
24459   if (ShAmt1.getValueType() != MVT::i8)
24460     return SDValue();
24461   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24462     ShAmt0 = ShAmt0.getOperand(0);
24463   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24464     ShAmt1 = ShAmt1.getOperand(0);
24465
24466   SDLoc DL(N);
24467   unsigned Opc = X86ISD::SHLD;
24468   SDValue Op0 = N0.getOperand(0);
24469   SDValue Op1 = N1.getOperand(0);
24470   if (ShAmt0.getOpcode() == ISD::SUB) {
24471     Opc = X86ISD::SHRD;
24472     std::swap(Op0, Op1);
24473     std::swap(ShAmt0, ShAmt1);
24474   }
24475
24476   unsigned Bits = VT.getSizeInBits();
24477   if (ShAmt1.getOpcode() == ISD::SUB) {
24478     SDValue Sum = ShAmt1.getOperand(0);
24479     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24480       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24481       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24482         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24483       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24484         return DAG.getNode(Opc, DL, VT,
24485                            Op0, Op1,
24486                            DAG.getNode(ISD::TRUNCATE, DL,
24487                                        MVT::i8, ShAmt0));
24488     }
24489   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24490     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24491     if (ShAmt0C &&
24492         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24493       return DAG.getNode(Opc, DL, VT,
24494                          N0.getOperand(0), N1.getOperand(0),
24495                          DAG.getNode(ISD::TRUNCATE, DL,
24496                                        MVT::i8, ShAmt0));
24497   }
24498
24499   return SDValue();
24500 }
24501
24502 // Generate NEG and CMOV for integer abs.
24503 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24504   EVT VT = N->getValueType(0);
24505
24506   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24507   // 8-bit integer abs to NEG and CMOV.
24508   if (VT.isInteger() && VT.getSizeInBits() == 8)
24509     return SDValue();
24510
24511   SDValue N0 = N->getOperand(0);
24512   SDValue N1 = N->getOperand(1);
24513   SDLoc DL(N);
24514
24515   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24516   // and change it to SUB and CMOV.
24517   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24518       N0.getOpcode() == ISD::ADD &&
24519       N0.getOperand(1) == N1 &&
24520       N1.getOpcode() == ISD::SRA &&
24521       N1.getOperand(0) == N0.getOperand(0))
24522     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24523       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24524         // Generate SUB & CMOV.
24525         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24526                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24527
24528         SDValue Ops[] = { N0.getOperand(0), Neg,
24529                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24530                           SDValue(Neg.getNode(), 1) };
24531         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24532       }
24533   return SDValue();
24534 }
24535
24536 // Try to turn tests against the signbit in the form of:
24537 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24538 // into:
24539 //   SETGT(X, -1)
24540 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24541   // This is only worth doing if the output type is i8.
24542   if (N->getValueType(0) != MVT::i8)
24543     return SDValue();
24544
24545   SDValue N0 = N->getOperand(0);
24546   SDValue N1 = N->getOperand(1);
24547
24548   // We should be performing an xor against a truncated shift.
24549   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24550     return SDValue();
24551
24552   // Make sure we are performing an xor against one.
24553   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24554     return SDValue();
24555
24556   // SetCC on x86 zero extends so only act on this if it's a logical shift.
24557   SDValue Shift = N0.getOperand(0);
24558   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24559     return SDValue();
24560
24561   // Make sure we are truncating from one of i16, i32 or i64.
24562   EVT ShiftTy = Shift.getValueType();
24563   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24564     return SDValue();
24565
24566   // Make sure the shift amount extracts the sign bit.
24567   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24568       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24569     return SDValue();
24570
24571   // Create a greater-than comparison against -1.
24572   // N.B. Using SETGE against 0 works but we want a canonical looking
24573   // comparison, using SETGT matches up with what TranslateX86CC.
24574   SDLoc DL(N);
24575   SDValue ShiftOp = Shift.getOperand(0);
24576   EVT ShiftOpTy = ShiftOp.getValueType();
24577   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24578                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24579   return Cond;
24580 }
24581
24582 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24583                                  TargetLowering::DAGCombinerInfo &DCI,
24584                                  const X86Subtarget *Subtarget) {
24585   if (DCI.isBeforeLegalizeOps())
24586     return SDValue();
24587
24588   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24589     return RV;
24590
24591   if (Subtarget->hasCMov())
24592     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24593       return RV;
24594
24595   return SDValue();
24596 }
24597
24598 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24599 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24600                                   TargetLowering::DAGCombinerInfo &DCI,
24601                                   const X86Subtarget *Subtarget) {
24602   LoadSDNode *Ld = cast<LoadSDNode>(N);
24603   EVT RegVT = Ld->getValueType(0);
24604   EVT MemVT = Ld->getMemoryVT();
24605   SDLoc dl(Ld);
24606   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24607
24608   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24609   // into two 16-byte operations.
24610   ISD::LoadExtType Ext = Ld->getExtensionType();
24611   bool Fast;
24612   unsigned AddressSpace = Ld->getAddressSpace();
24613   unsigned Alignment = Ld->getAlignment();
24614   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
24615       Ext == ISD::NON_EXTLOAD &&
24616       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
24617                              AddressSpace, Alignment, &Fast) && !Fast) {
24618     unsigned NumElems = RegVT.getVectorNumElements();
24619     if (NumElems < 2)
24620       return SDValue();
24621
24622     SDValue Ptr = Ld->getBasePtr();
24623     SDValue Increment =
24624         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24625
24626     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24627                                   NumElems/2);
24628     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24629                                 Ld->getPointerInfo(), Ld->isVolatile(),
24630                                 Ld->isNonTemporal(), Ld->isInvariant(),
24631                                 Alignment);
24632     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24633     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24634                                 Ld->getPointerInfo(), Ld->isVolatile(),
24635                                 Ld->isNonTemporal(), Ld->isInvariant(),
24636                                 std::min(16U, Alignment));
24637     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24638                              Load1.getValue(1),
24639                              Load2.getValue(1));
24640
24641     SDValue NewVec = DAG.getUNDEF(RegVT);
24642     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24643     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24644     return DCI.CombineTo(N, NewVec, TF, true);
24645   }
24646
24647   return SDValue();
24648 }
24649
24650 /// PerformMLOADCombine - Resolve extending loads
24651 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24652                                    TargetLowering::DAGCombinerInfo &DCI,
24653                                    const X86Subtarget *Subtarget) {
24654   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24655   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24656     return SDValue();
24657
24658   EVT VT = Mld->getValueType(0);
24659   unsigned NumElems = VT.getVectorNumElements();
24660   EVT LdVT = Mld->getMemoryVT();
24661   SDLoc dl(Mld);
24662
24663   assert(LdVT != VT && "Cannot extend to the same type");
24664   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24665   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24666   // From, To sizes and ElemCount must be pow of two
24667   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24668     "Unexpected size for extending masked load");
24669
24670   unsigned SizeRatio  = ToSz / FromSz;
24671   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24672
24673   // Create a type on which we perform the shuffle
24674   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24675           LdVT.getScalarType(), NumElems*SizeRatio);
24676   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24677
24678   // Convert Src0 value
24679   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24680   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24681     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24682     for (unsigned i = 0; i != NumElems; ++i)
24683       ShuffleVec[i] = i * SizeRatio;
24684
24685     // Can't shuffle using an illegal type.
24686     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24687             && "WideVecVT should be legal");
24688     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24689                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24690   }
24691   // Prepare the new mask
24692   SDValue NewMask;
24693   SDValue Mask = Mld->getMask();
24694   if (Mask.getValueType() == VT) {
24695     // Mask and original value have the same type
24696     NewMask = DAG.getBitcast(WideVecVT, Mask);
24697     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24698     for (unsigned i = 0; i != NumElems; ++i)
24699       ShuffleVec[i] = i * SizeRatio;
24700     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24701       ShuffleVec[i] = NumElems*SizeRatio;
24702     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24703                                    DAG.getConstant(0, dl, WideVecVT),
24704                                    &ShuffleVec[0]);
24705   }
24706   else {
24707     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24708     unsigned WidenNumElts = NumElems*SizeRatio;
24709     unsigned MaskNumElts = VT.getVectorNumElements();
24710     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24711                                      WidenNumElts);
24712
24713     unsigned NumConcat = WidenNumElts / MaskNumElts;
24714     SmallVector<SDValue, 16> Ops(NumConcat);
24715     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24716     Ops[0] = Mask;
24717     for (unsigned i = 1; i != NumConcat; ++i)
24718       Ops[i] = ZeroVal;
24719
24720     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24721   }
24722
24723   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24724                                      Mld->getBasePtr(), NewMask, WideSrc0,
24725                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24726                                      ISD::NON_EXTLOAD);
24727   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24728   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24729
24730 }
24731 /// PerformMSTORECombine - Resolve truncating stores
24732 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24733                                     const X86Subtarget *Subtarget) {
24734   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24735   if (!Mst->isTruncatingStore())
24736     return SDValue();
24737
24738   EVT VT = Mst->getValue().getValueType();
24739   unsigned NumElems = VT.getVectorNumElements();
24740   EVT StVT = Mst->getMemoryVT();
24741   SDLoc dl(Mst);
24742
24743   assert(StVT != VT && "Cannot truncate to the same type");
24744   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24745   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24746
24747   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24748
24749   // The truncating store is legal in some cases. For example
24750   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24751   // are designated for truncate store.
24752   // In this case we don't need any further transformations.
24753   if (TLI.isTruncStoreLegal(VT, StVT))
24754     return SDValue();
24755
24756   // From, To sizes and ElemCount must be pow of two
24757   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24758     "Unexpected size for truncating masked store");
24759   // We are going to use the original vector elt for storing.
24760   // Accumulated smaller vector elements must be a multiple of the store size.
24761   assert (((NumElems * FromSz) % ToSz) == 0 &&
24762           "Unexpected ratio for truncating masked store");
24763
24764   unsigned SizeRatio  = FromSz / ToSz;
24765   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24766
24767   // Create a type on which we perform the shuffle
24768   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24769           StVT.getScalarType(), NumElems*SizeRatio);
24770
24771   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24772
24773   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24774   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24775   for (unsigned i = 0; i != NumElems; ++i)
24776     ShuffleVec[i] = i * SizeRatio;
24777
24778   // Can't shuffle using an illegal type.
24779   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24780           && "WideVecVT should be legal");
24781
24782   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24783                                         DAG.getUNDEF(WideVecVT),
24784                                         &ShuffleVec[0]);
24785
24786   SDValue NewMask;
24787   SDValue Mask = Mst->getMask();
24788   if (Mask.getValueType() == VT) {
24789     // Mask and original value have the same type
24790     NewMask = DAG.getBitcast(WideVecVT, Mask);
24791     for (unsigned i = 0; i != NumElems; ++i)
24792       ShuffleVec[i] = i * SizeRatio;
24793     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24794       ShuffleVec[i] = NumElems*SizeRatio;
24795     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24796                                    DAG.getConstant(0, dl, WideVecVT),
24797                                    &ShuffleVec[0]);
24798   }
24799   else {
24800     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24801     unsigned WidenNumElts = NumElems*SizeRatio;
24802     unsigned MaskNumElts = VT.getVectorNumElements();
24803     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24804                                      WidenNumElts);
24805
24806     unsigned NumConcat = WidenNumElts / MaskNumElts;
24807     SmallVector<SDValue, 16> Ops(NumConcat);
24808     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24809     Ops[0] = Mask;
24810     for (unsigned i = 1; i != NumConcat; ++i)
24811       Ops[i] = ZeroVal;
24812
24813     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24814   }
24815
24816   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24817                             NewMask, StVT, Mst->getMemOperand(), false);
24818 }
24819 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24820 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24821                                    const X86Subtarget *Subtarget) {
24822   StoreSDNode *St = cast<StoreSDNode>(N);
24823   EVT VT = St->getValue().getValueType();
24824   EVT StVT = St->getMemoryVT();
24825   SDLoc dl(St);
24826   SDValue StoredVal = St->getOperand(1);
24827   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24828
24829   // If we are saving a concatenation of two XMM registers and 32-byte stores
24830   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24831   bool Fast;
24832   unsigned AddressSpace = St->getAddressSpace();
24833   unsigned Alignment = St->getAlignment();
24834   if (VT.is256BitVector() && StVT == VT &&
24835       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
24836                              AddressSpace, Alignment, &Fast) && !Fast) {
24837     unsigned NumElems = VT.getVectorNumElements();
24838     if (NumElems < 2)
24839       return SDValue();
24840
24841     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24842     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24843
24844     SDValue Stride =
24845         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24846     SDValue Ptr0 = St->getBasePtr();
24847     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24848
24849     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24850                                 St->getPointerInfo(), St->isVolatile(),
24851                                 St->isNonTemporal(), Alignment);
24852     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24853                                 St->getPointerInfo(), St->isVolatile(),
24854                                 St->isNonTemporal(),
24855                                 std::min(16U, Alignment));
24856     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24857   }
24858
24859   // Optimize trunc store (of multiple scalars) to shuffle and store.
24860   // First, pack all of the elements in one place. Next, store to memory
24861   // in fewer chunks.
24862   if (St->isTruncatingStore() && VT.isVector()) {
24863     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24864     unsigned NumElems = VT.getVectorNumElements();
24865     assert(StVT != VT && "Cannot truncate to the same type");
24866     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24867     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24868
24869     // The truncating store is legal in some cases. For example
24870     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24871     // are designated for truncate store.
24872     // In this case we don't need any further transformations.
24873     if (TLI.isTruncStoreLegal(VT, StVT))
24874       return SDValue();
24875
24876     // From, To sizes and ElemCount must be pow of two
24877     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24878     // We are going to use the original vector elt for storing.
24879     // Accumulated smaller vector elements must be a multiple of the store size.
24880     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24881
24882     unsigned SizeRatio  = FromSz / ToSz;
24883
24884     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24885
24886     // Create a type on which we perform the shuffle
24887     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24888             StVT.getScalarType(), NumElems*SizeRatio);
24889
24890     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24891
24892     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24893     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24894     for (unsigned i = 0; i != NumElems; ++i)
24895       ShuffleVec[i] = i * SizeRatio;
24896
24897     // Can't shuffle using an illegal type.
24898     if (!TLI.isTypeLegal(WideVecVT))
24899       return SDValue();
24900
24901     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24902                                          DAG.getUNDEF(WideVecVT),
24903                                          &ShuffleVec[0]);
24904     // At this point all of the data is stored at the bottom of the
24905     // register. We now need to save it to mem.
24906
24907     // Find the largest store unit
24908     MVT StoreType = MVT::i8;
24909     for (MVT Tp : MVT::integer_valuetypes()) {
24910       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24911         StoreType = Tp;
24912     }
24913
24914     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24915     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24916         (64 <= NumElems * ToSz))
24917       StoreType = MVT::f64;
24918
24919     // Bitcast the original vector into a vector of store-size units
24920     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24921             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24922     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24923     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24924     SmallVector<SDValue, 8> Chains;
24925     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24926                                         TLI.getPointerTy(DAG.getDataLayout()));
24927     SDValue Ptr = St->getBasePtr();
24928
24929     // Perform one or more big stores into memory.
24930     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24931       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24932                                    StoreType, ShuffWide,
24933                                    DAG.getIntPtrConstant(i, dl));
24934       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24935                                 St->getPointerInfo(), St->isVolatile(),
24936                                 St->isNonTemporal(), St->getAlignment());
24937       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24938       Chains.push_back(Ch);
24939     }
24940
24941     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24942   }
24943
24944   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24945   // the FP state in cases where an emms may be missing.
24946   // A preferable solution to the general problem is to figure out the right
24947   // places to insert EMMS.  This qualifies as a quick hack.
24948
24949   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24950   if (VT.getSizeInBits() != 64)
24951     return SDValue();
24952
24953   const Function *F = DAG.getMachineFunction().getFunction();
24954   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24955   bool F64IsLegal =
24956       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24957   if ((VT.isVector() ||
24958        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24959       isa<LoadSDNode>(St->getValue()) &&
24960       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24961       St->getChain().hasOneUse() && !St->isVolatile()) {
24962     SDNode* LdVal = St->getValue().getNode();
24963     LoadSDNode *Ld = nullptr;
24964     int TokenFactorIndex = -1;
24965     SmallVector<SDValue, 8> Ops;
24966     SDNode* ChainVal = St->getChain().getNode();
24967     // Must be a store of a load.  We currently handle two cases:  the load
24968     // is a direct child, and it's under an intervening TokenFactor.  It is
24969     // possible to dig deeper under nested TokenFactors.
24970     if (ChainVal == LdVal)
24971       Ld = cast<LoadSDNode>(St->getChain());
24972     else if (St->getValue().hasOneUse() &&
24973              ChainVal->getOpcode() == ISD::TokenFactor) {
24974       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24975         if (ChainVal->getOperand(i).getNode() == LdVal) {
24976           TokenFactorIndex = i;
24977           Ld = cast<LoadSDNode>(St->getValue());
24978         } else
24979           Ops.push_back(ChainVal->getOperand(i));
24980       }
24981     }
24982
24983     if (!Ld || !ISD::isNormalLoad(Ld))
24984       return SDValue();
24985
24986     // If this is not the MMX case, i.e. we are just turning i64 load/store
24987     // into f64 load/store, avoid the transformation if there are multiple
24988     // uses of the loaded value.
24989     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24990       return SDValue();
24991
24992     SDLoc LdDL(Ld);
24993     SDLoc StDL(N);
24994     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24995     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24996     // pair instead.
24997     if (Subtarget->is64Bit() || F64IsLegal) {
24998       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24999       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
25000                                   Ld->getPointerInfo(), Ld->isVolatile(),
25001                                   Ld->isNonTemporal(), Ld->isInvariant(),
25002                                   Ld->getAlignment());
25003       SDValue NewChain = NewLd.getValue(1);
25004       if (TokenFactorIndex != -1) {
25005         Ops.push_back(NewChain);
25006         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25007       }
25008       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
25009                           St->getPointerInfo(),
25010                           St->isVolatile(), St->isNonTemporal(),
25011                           St->getAlignment());
25012     }
25013
25014     // Otherwise, lower to two pairs of 32-bit loads / stores.
25015     SDValue LoAddr = Ld->getBasePtr();
25016     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
25017                                  DAG.getConstant(4, LdDL, MVT::i32));
25018
25019     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
25020                                Ld->getPointerInfo(),
25021                                Ld->isVolatile(), Ld->isNonTemporal(),
25022                                Ld->isInvariant(), Ld->getAlignment());
25023     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
25024                                Ld->getPointerInfo().getWithOffset(4),
25025                                Ld->isVolatile(), Ld->isNonTemporal(),
25026                                Ld->isInvariant(),
25027                                MinAlign(Ld->getAlignment(), 4));
25028
25029     SDValue NewChain = LoLd.getValue(1);
25030     if (TokenFactorIndex != -1) {
25031       Ops.push_back(LoLd);
25032       Ops.push_back(HiLd);
25033       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25034     }
25035
25036     LoAddr = St->getBasePtr();
25037     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
25038                          DAG.getConstant(4, StDL, MVT::i32));
25039
25040     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
25041                                 St->getPointerInfo(),
25042                                 St->isVolatile(), St->isNonTemporal(),
25043                                 St->getAlignment());
25044     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
25045                                 St->getPointerInfo().getWithOffset(4),
25046                                 St->isVolatile(),
25047                                 St->isNonTemporal(),
25048                                 MinAlign(St->getAlignment(), 4));
25049     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
25050   }
25051
25052   // This is similar to the above case, but here we handle a scalar 64-bit
25053   // integer store that is extracted from a vector on a 32-bit target.
25054   // If we have SSE2, then we can treat it like a floating-point double
25055   // to get past legalization. The execution dependencies fixup pass will
25056   // choose the optimal machine instruction for the store if this really is
25057   // an integer or v2f32 rather than an f64.
25058   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
25059       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
25060     SDValue OldExtract = St->getOperand(1);
25061     SDValue ExtOp0 = OldExtract.getOperand(0);
25062     unsigned VecSize = ExtOp0.getValueSizeInBits();
25063     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
25064     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
25065     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
25066                                      BitCast, OldExtract.getOperand(1));
25067     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
25068                         St->getPointerInfo(), St->isVolatile(),
25069                         St->isNonTemporal(), St->getAlignment());
25070   }
25071
25072   return SDValue();
25073 }
25074
25075 /// Return 'true' if this vector operation is "horizontal"
25076 /// and return the operands for the horizontal operation in LHS and RHS.  A
25077 /// horizontal operation performs the binary operation on successive elements
25078 /// of its first operand, then on successive elements of its second operand,
25079 /// returning the resulting values in a vector.  For example, if
25080 ///   A = < float a0, float a1, float a2, float a3 >
25081 /// and
25082 ///   B = < float b0, float b1, float b2, float b3 >
25083 /// then the result of doing a horizontal operation on A and B is
25084 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
25085 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
25086 /// A horizontal-op B, for some already available A and B, and if so then LHS is
25087 /// set to A, RHS to B, and the routine returns 'true'.
25088 /// Note that the binary operation should have the property that if one of the
25089 /// operands is UNDEF then the result is UNDEF.
25090 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
25091   // Look for the following pattern: if
25092   //   A = < float a0, float a1, float a2, float a3 >
25093   //   B = < float b0, float b1, float b2, float b3 >
25094   // and
25095   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
25096   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
25097   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
25098   // which is A horizontal-op B.
25099
25100   // At least one of the operands should be a vector shuffle.
25101   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
25102       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
25103     return false;
25104
25105   MVT VT = LHS.getSimpleValueType();
25106
25107   assert((VT.is128BitVector() || VT.is256BitVector()) &&
25108          "Unsupported vector type for horizontal add/sub");
25109
25110   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
25111   // operate independently on 128-bit lanes.
25112   unsigned NumElts = VT.getVectorNumElements();
25113   unsigned NumLanes = VT.getSizeInBits()/128;
25114   unsigned NumLaneElts = NumElts / NumLanes;
25115   assert((NumLaneElts % 2 == 0) &&
25116          "Vector type should have an even number of elements in each lane");
25117   unsigned HalfLaneElts = NumLaneElts/2;
25118
25119   // View LHS in the form
25120   //   LHS = VECTOR_SHUFFLE A, B, LMask
25121   // If LHS is not a shuffle then pretend it is the shuffle
25122   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
25123   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
25124   // type VT.
25125   SDValue A, B;
25126   SmallVector<int, 16> LMask(NumElts);
25127   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25128     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
25129       A = LHS.getOperand(0);
25130     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
25131       B = LHS.getOperand(1);
25132     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
25133     std::copy(Mask.begin(), Mask.end(), LMask.begin());
25134   } else {
25135     if (LHS.getOpcode() != ISD::UNDEF)
25136       A = LHS;
25137     for (unsigned i = 0; i != NumElts; ++i)
25138       LMask[i] = i;
25139   }
25140
25141   // Likewise, view RHS in the form
25142   //   RHS = VECTOR_SHUFFLE C, D, RMask
25143   SDValue C, D;
25144   SmallVector<int, 16> RMask(NumElts);
25145   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25146     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
25147       C = RHS.getOperand(0);
25148     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
25149       D = RHS.getOperand(1);
25150     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
25151     std::copy(Mask.begin(), Mask.end(), RMask.begin());
25152   } else {
25153     if (RHS.getOpcode() != ISD::UNDEF)
25154       C = RHS;
25155     for (unsigned i = 0; i != NumElts; ++i)
25156       RMask[i] = i;
25157   }
25158
25159   // Check that the shuffles are both shuffling the same vectors.
25160   if (!(A == C && B == D) && !(A == D && B == C))
25161     return false;
25162
25163   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
25164   if (!A.getNode() && !B.getNode())
25165     return false;
25166
25167   // If A and B occur in reverse order in RHS, then "swap" them (which means
25168   // rewriting the mask).
25169   if (A != C)
25170     ShuffleVectorSDNode::commuteMask(RMask);
25171
25172   // At this point LHS and RHS are equivalent to
25173   //   LHS = VECTOR_SHUFFLE A, B, LMask
25174   //   RHS = VECTOR_SHUFFLE A, B, RMask
25175   // Check that the masks correspond to performing a horizontal operation.
25176   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
25177     for (unsigned i = 0; i != NumLaneElts; ++i) {
25178       int LIdx = LMask[i+l], RIdx = RMask[i+l];
25179
25180       // Ignore any UNDEF components.
25181       if (LIdx < 0 || RIdx < 0 ||
25182           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
25183           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
25184         continue;
25185
25186       // Check that successive elements are being operated on.  If not, this is
25187       // not a horizontal operation.
25188       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
25189       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
25190       if (!(LIdx == Index && RIdx == Index + 1) &&
25191           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
25192         return false;
25193     }
25194   }
25195
25196   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
25197   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
25198   return true;
25199 }
25200
25201 /// Do target-specific dag combines on floating point adds.
25202 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
25203                                   const X86Subtarget *Subtarget) {
25204   EVT VT = N->getValueType(0);
25205   SDValue LHS = N->getOperand(0);
25206   SDValue RHS = N->getOperand(1);
25207
25208   // Try to synthesize horizontal adds from adds of shuffles.
25209   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25210        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25211       isHorizontalBinOp(LHS, RHS, true))
25212     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
25213   return SDValue();
25214 }
25215
25216 /// Do target-specific dag combines on floating point subs.
25217 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
25218                                   const X86Subtarget *Subtarget) {
25219   EVT VT = N->getValueType(0);
25220   SDValue LHS = N->getOperand(0);
25221   SDValue RHS = N->getOperand(1);
25222
25223   // Try to synthesize horizontal subs from subs of shuffles.
25224   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25225        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25226       isHorizontalBinOp(LHS, RHS, false))
25227     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
25228   return SDValue();
25229 }
25230
25231 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
25232 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
25233                                  const X86Subtarget *Subtarget) {
25234   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
25235
25236   // F[X]OR(0.0, x) -> x
25237   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25238     if (C->getValueAPF().isPosZero())
25239       return N->getOperand(1);
25240
25241   // F[X]OR(x, 0.0) -> x
25242   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25243     if (C->getValueAPF().isPosZero())
25244       return N->getOperand(0);
25245
25246   EVT VT = N->getValueType(0);
25247   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
25248     SDLoc dl(N);
25249     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
25250     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
25251
25252     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
25253     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
25254     unsigned IntOpcode = (N->getOpcode() == X86ISD::FOR) ? ISD::OR : ISD::XOR;
25255     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
25256     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
25257   }
25258   return SDValue();
25259 }
25260
25261 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
25262 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
25263   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
25264
25265   // Only perform optimizations if UnsafeMath is used.
25266   if (!DAG.getTarget().Options.UnsafeFPMath)
25267     return SDValue();
25268
25269   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25270   // into FMINC and FMAXC, which are Commutative operations.
25271   unsigned NewOp = 0;
25272   switch (N->getOpcode()) {
25273     default: llvm_unreachable("unknown opcode");
25274     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
25275     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
25276   }
25277
25278   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25279                      N->getOperand(0), N->getOperand(1));
25280 }
25281
25282 /// Do target-specific dag combines on X86ISD::FAND nodes.
25283 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25284   // FAND(0.0, x) -> 0.0
25285   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25286     if (C->getValueAPF().isPosZero())
25287       return N->getOperand(0);
25288
25289   // FAND(x, 0.0) -> 0.0
25290   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25291     if (C->getValueAPF().isPosZero())
25292       return N->getOperand(1);
25293
25294   return SDValue();
25295 }
25296
25297 /// Do target-specific dag combines on X86ISD::FANDN nodes
25298 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25299   // FANDN(0.0, x) -> x
25300   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25301     if (C->getValueAPF().isPosZero())
25302       return N->getOperand(1);
25303
25304   // FANDN(x, 0.0) -> 0.0
25305   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25306     if (C->getValueAPF().isPosZero())
25307       return N->getOperand(1);
25308
25309   return SDValue();
25310 }
25311
25312 static SDValue PerformBTCombine(SDNode *N,
25313                                 SelectionDAG &DAG,
25314                                 TargetLowering::DAGCombinerInfo &DCI) {
25315   // BT ignores high bits in the bit index operand.
25316   SDValue Op1 = N->getOperand(1);
25317   if (Op1.hasOneUse()) {
25318     unsigned BitWidth = Op1.getValueSizeInBits();
25319     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25320     APInt KnownZero, KnownOne;
25321     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25322                                           !DCI.isBeforeLegalizeOps());
25323     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25324     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25325         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25326       DCI.CommitTargetLoweringOpt(TLO);
25327   }
25328   return SDValue();
25329 }
25330
25331 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25332   SDValue Op = N->getOperand(0);
25333   if (Op.getOpcode() == ISD::BITCAST)
25334     Op = Op.getOperand(0);
25335   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25336   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25337       VT.getVectorElementType().getSizeInBits() ==
25338       OpVT.getVectorElementType().getSizeInBits()) {
25339     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25340   }
25341   return SDValue();
25342 }
25343
25344 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25345                                                const X86Subtarget *Subtarget) {
25346   EVT VT = N->getValueType(0);
25347   if (!VT.isVector())
25348     return SDValue();
25349
25350   SDValue N0 = N->getOperand(0);
25351   SDValue N1 = N->getOperand(1);
25352   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25353   SDLoc dl(N);
25354
25355   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25356   // both SSE and AVX2 since there is no sign-extended shift right
25357   // operation on a vector with 64-bit elements.
25358   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25359   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25360   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25361       N0.getOpcode() == ISD::SIGN_EXTEND)) {
25362     SDValue N00 = N0.getOperand(0);
25363
25364     // EXTLOAD has a better solution on AVX2,
25365     // it may be replaced with X86ISD::VSEXT node.
25366     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25367       if (!ISD::isNormalLoad(N00.getNode()))
25368         return SDValue();
25369
25370     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25371         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25372                                   N00, N1);
25373       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25374     }
25375   }
25376   return SDValue();
25377 }
25378
25379 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25380                                   TargetLowering::DAGCombinerInfo &DCI,
25381                                   const X86Subtarget *Subtarget) {
25382   SDValue N0 = N->getOperand(0);
25383   EVT VT = N->getValueType(0);
25384   EVT SVT = VT.getScalarType();
25385   EVT InVT = N0.getValueType();
25386   EVT InSVT = InVT.getScalarType();
25387   SDLoc DL(N);
25388
25389   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25390   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25391   // This exposes the sext to the sdivrem lowering, so that it directly extends
25392   // from AH (which we otherwise need to do contortions to access).
25393   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25394       InVT == MVT::i8 && VT == MVT::i32) {
25395     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25396     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25397                             N0.getOperand(0), N0.getOperand(1));
25398     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25399     return R.getValue(1);
25400   }
25401
25402   if (!DCI.isBeforeLegalizeOps()) {
25403     if (InVT == MVT::i1) {
25404       SDValue Zero = DAG.getConstant(0, DL, VT);
25405       SDValue AllOnes =
25406         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25407       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25408     }
25409     return SDValue();
25410   }
25411
25412   if (VT.isVector() && Subtarget->hasSSE2()) {
25413     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25414       EVT InVT = N.getValueType();
25415       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25416                                    Size / InVT.getScalarSizeInBits());
25417       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25418                                     DAG.getUNDEF(InVT));
25419       Opnds[0] = N;
25420       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25421     };
25422
25423     // If target-size is less than 128-bits, extend to a type that would extend
25424     // to 128 bits, extend that and extract the original target vector.
25425     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25426         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25427         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25428       unsigned Scale = 128 / VT.getSizeInBits();
25429       EVT ExVT =
25430           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25431       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25432       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25433       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25434                          DAG.getIntPtrConstant(0, DL));
25435     }
25436
25437     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25438     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25439     if (VT.getSizeInBits() == 128 &&
25440         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25441         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25442       SDValue ExOp = ExtendVecSize(DL, N0, 128);
25443       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25444     }
25445
25446     // On pre-AVX2 targets, split into 128-bit nodes of
25447     // ISD::SIGN_EXTEND_VECTOR_INREG.
25448     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25449         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25450         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25451       unsigned NumVecs = VT.getSizeInBits() / 128;
25452       unsigned NumSubElts = 128 / SVT.getSizeInBits();
25453       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25454       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25455
25456       SmallVector<SDValue, 8> Opnds;
25457       for (unsigned i = 0, Offset = 0; i != NumVecs;
25458            ++i, Offset += NumSubElts) {
25459         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25460                                      DAG.getIntPtrConstant(Offset, DL));
25461         SrcVec = ExtendVecSize(DL, SrcVec, 128);
25462         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25463         Opnds.push_back(SrcVec);
25464       }
25465       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25466     }
25467   }
25468
25469   if (!Subtarget->hasFp256())
25470     return SDValue();
25471
25472   if (VT.isVector() && VT.getSizeInBits() == 256)
25473     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25474       return R;
25475
25476   return SDValue();
25477 }
25478
25479 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25480                                  const X86Subtarget* Subtarget) {
25481   SDLoc dl(N);
25482   EVT VT = N->getValueType(0);
25483
25484   // Let legalize expand this if it isn't a legal type yet.
25485   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25486     return SDValue();
25487
25488   EVT ScalarVT = VT.getScalarType();
25489   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25490       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25491        !Subtarget->hasAVX512()))
25492     return SDValue();
25493
25494   SDValue A = N->getOperand(0);
25495   SDValue B = N->getOperand(1);
25496   SDValue C = N->getOperand(2);
25497
25498   bool NegA = (A.getOpcode() == ISD::FNEG);
25499   bool NegB = (B.getOpcode() == ISD::FNEG);
25500   bool NegC = (C.getOpcode() == ISD::FNEG);
25501
25502   // Negative multiplication when NegA xor NegB
25503   bool NegMul = (NegA != NegB);
25504   if (NegA)
25505     A = A.getOperand(0);
25506   if (NegB)
25507     B = B.getOperand(0);
25508   if (NegC)
25509     C = C.getOperand(0);
25510
25511   unsigned Opcode;
25512   if (!NegMul)
25513     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25514   else
25515     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25516
25517   return DAG.getNode(Opcode, dl, VT, A, B, C);
25518 }
25519
25520 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25521                                   TargetLowering::DAGCombinerInfo &DCI,
25522                                   const X86Subtarget *Subtarget) {
25523   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
25524   //           (and (i32 x86isd::setcc_carry), 1)
25525   // This eliminates the zext. This transformation is necessary because
25526   // ISD::SETCC is always legalized to i8.
25527   SDLoc dl(N);
25528   SDValue N0 = N->getOperand(0);
25529   EVT VT = N->getValueType(0);
25530
25531   if (N0.getOpcode() == ISD::AND &&
25532       N0.hasOneUse() &&
25533       N0.getOperand(0).hasOneUse()) {
25534     SDValue N00 = N0.getOperand(0);
25535     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25536       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25537       if (!C || C->getZExtValue() != 1)
25538         return SDValue();
25539       return DAG.getNode(ISD::AND, dl, VT,
25540                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25541                                      N00.getOperand(0), N00.getOperand(1)),
25542                          DAG.getConstant(1, dl, VT));
25543     }
25544   }
25545
25546   if (N0.getOpcode() == ISD::TRUNCATE &&
25547       N0.hasOneUse() &&
25548       N0.getOperand(0).hasOneUse()) {
25549     SDValue N00 = N0.getOperand(0);
25550     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25551       return DAG.getNode(ISD::AND, dl, VT,
25552                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25553                                      N00.getOperand(0), N00.getOperand(1)),
25554                          DAG.getConstant(1, dl, VT));
25555     }
25556   }
25557
25558   if (VT.is256BitVector())
25559     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25560       return R;
25561
25562   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25563   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25564   // This exposes the zext to the udivrem lowering, so that it directly extends
25565   // from AH (which we otherwise need to do contortions to access).
25566   if (N0.getOpcode() == ISD::UDIVREM &&
25567       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25568       (VT == MVT::i32 || VT == MVT::i64)) {
25569     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25570     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25571                             N0.getOperand(0), N0.getOperand(1));
25572     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25573     return R.getValue(1);
25574   }
25575
25576   return SDValue();
25577 }
25578
25579 // Optimize x == -y --> x+y == 0
25580 //          x != -y --> x+y != 0
25581 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25582                                       const X86Subtarget* Subtarget) {
25583   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25584   SDValue LHS = N->getOperand(0);
25585   SDValue RHS = N->getOperand(1);
25586   EVT VT = N->getValueType(0);
25587   SDLoc DL(N);
25588
25589   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25590     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25591       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25592         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25593                                    LHS.getOperand(1));
25594         return DAG.getSetCC(DL, N->getValueType(0), addV,
25595                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25596       }
25597   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25598     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25599       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25600         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25601                                    RHS.getOperand(1));
25602         return DAG.getSetCC(DL, N->getValueType(0), addV,
25603                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25604       }
25605
25606   if (VT.getScalarType() == MVT::i1 &&
25607       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25608     bool IsSEXT0 =
25609         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25610         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25611     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25612
25613     if (!IsSEXT0 || !IsVZero1) {
25614       // Swap the operands and update the condition code.
25615       std::swap(LHS, RHS);
25616       CC = ISD::getSetCCSwappedOperands(CC);
25617
25618       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25619                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25620       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25621     }
25622
25623     if (IsSEXT0 && IsVZero1) {
25624       assert(VT == LHS.getOperand(0).getValueType() &&
25625              "Uexpected operand type");
25626       if (CC == ISD::SETGT)
25627         return DAG.getConstant(0, DL, VT);
25628       if (CC == ISD::SETLE)
25629         return DAG.getConstant(1, DL, VT);
25630       if (CC == ISD::SETEQ || CC == ISD::SETGE)
25631         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25632
25633       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25634              "Unexpected condition code!");
25635       return LHS.getOperand(0);
25636     }
25637   }
25638
25639   return SDValue();
25640 }
25641
25642 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25643                                          SelectionDAG &DAG) {
25644   SDLoc dl(Load);
25645   MVT VT = Load->getSimpleValueType(0);
25646   MVT EVT = VT.getVectorElementType();
25647   SDValue Addr = Load->getOperand(1);
25648   SDValue NewAddr = DAG.getNode(
25649       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25650       DAG.getConstant(Index * EVT.getStoreSize(), dl,
25651                       Addr.getSimpleValueType()));
25652
25653   SDValue NewLoad =
25654       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25655                   DAG.getMachineFunction().getMachineMemOperand(
25656                       Load->getMemOperand(), 0, EVT.getStoreSize()));
25657   return NewLoad;
25658 }
25659
25660 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25661                                       const X86Subtarget *Subtarget) {
25662   SDLoc dl(N);
25663   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25664   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25665          "X86insertps is only defined for v4x32");
25666
25667   SDValue Ld = N->getOperand(1);
25668   if (MayFoldLoad(Ld)) {
25669     // Extract the countS bits from the immediate so we can get the proper
25670     // address when narrowing the vector load to a specific element.
25671     // When the second source op is a memory address, insertps doesn't use
25672     // countS and just gets an f32 from that address.
25673     unsigned DestIndex =
25674         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25675
25676     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25677
25678     // Create this as a scalar to vector to match the instruction pattern.
25679     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25680     // countS bits are ignored when loading from memory on insertps, which
25681     // means we don't need to explicitly set them to 0.
25682     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25683                        LoadScalarToVector, N->getOperand(2));
25684   }
25685   return SDValue();
25686 }
25687
25688 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25689   SDValue V0 = N->getOperand(0);
25690   SDValue V1 = N->getOperand(1);
25691   SDLoc DL(N);
25692   EVT VT = N->getValueType(0);
25693
25694   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25695   // operands and changing the mask to 1. This saves us a bunch of
25696   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25697   // x86InstrInfo knows how to commute this back after instruction selection
25698   // if it would help register allocation.
25699
25700   // TODO: If optimizing for size or a processor that doesn't suffer from
25701   // partial register update stalls, this should be transformed into a MOVSD
25702   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25703
25704   if (VT == MVT::v2f64)
25705     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25706       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25707         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25708         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25709       }
25710
25711   return SDValue();
25712 }
25713
25714 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25715 // as "sbb reg,reg", since it can be extended without zext and produces
25716 // an all-ones bit which is more useful than 0/1 in some cases.
25717 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25718                                MVT VT) {
25719   if (VT == MVT::i8)
25720     return DAG.getNode(ISD::AND, DL, VT,
25721                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25722                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25723                                    EFLAGS),
25724                        DAG.getConstant(1, DL, VT));
25725   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25726   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25727                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25728                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25729                                  EFLAGS));
25730 }
25731
25732 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25733 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25734                                    TargetLowering::DAGCombinerInfo &DCI,
25735                                    const X86Subtarget *Subtarget) {
25736   SDLoc DL(N);
25737   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25738   SDValue EFLAGS = N->getOperand(1);
25739
25740   if (CC == X86::COND_A) {
25741     // Try to convert COND_A into COND_B in an attempt to facilitate
25742     // materializing "setb reg".
25743     //
25744     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25745     // cannot take an immediate as its first operand.
25746     //
25747     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25748         EFLAGS.getValueType().isInteger() &&
25749         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25750       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25751                                    EFLAGS.getNode()->getVTList(),
25752                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25753       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25754       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25755     }
25756   }
25757
25758   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25759   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25760   // cases.
25761   if (CC == X86::COND_B)
25762     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25763
25764   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25765     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25766     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25767   }
25768
25769   return SDValue();
25770 }
25771
25772 // Optimize branch condition evaluation.
25773 //
25774 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25775                                     TargetLowering::DAGCombinerInfo &DCI,
25776                                     const X86Subtarget *Subtarget) {
25777   SDLoc DL(N);
25778   SDValue Chain = N->getOperand(0);
25779   SDValue Dest = N->getOperand(1);
25780   SDValue EFLAGS = N->getOperand(3);
25781   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25782
25783   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25784     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25785     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25786                        Flags);
25787   }
25788
25789   return SDValue();
25790 }
25791
25792 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25793                                                          SelectionDAG &DAG) {
25794   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25795   // optimize away operation when it's from a constant.
25796   //
25797   // The general transformation is:
25798   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25799   //       AND(VECTOR_CMP(x,y), constant2)
25800   //    constant2 = UNARYOP(constant)
25801
25802   // Early exit if this isn't a vector operation, the operand of the
25803   // unary operation isn't a bitwise AND, or if the sizes of the operations
25804   // aren't the same.
25805   EVT VT = N->getValueType(0);
25806   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25807       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25808       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25809     return SDValue();
25810
25811   // Now check that the other operand of the AND is a constant. We could
25812   // make the transformation for non-constant splats as well, but it's unclear
25813   // that would be a benefit as it would not eliminate any operations, just
25814   // perform one more step in scalar code before moving to the vector unit.
25815   if (BuildVectorSDNode *BV =
25816           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25817     // Bail out if the vector isn't a constant.
25818     if (!BV->isConstant())
25819       return SDValue();
25820
25821     // Everything checks out. Build up the new and improved node.
25822     SDLoc DL(N);
25823     EVT IntVT = BV->getValueType(0);
25824     // Create a new constant of the appropriate type for the transformed
25825     // DAG.
25826     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25827     // The AND node needs bitcasts to/from an integer vector type around it.
25828     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25829     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25830                                  N->getOperand(0)->getOperand(0), MaskConst);
25831     SDValue Res = DAG.getBitcast(VT, NewAnd);
25832     return Res;
25833   }
25834
25835   return SDValue();
25836 }
25837
25838 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25839                                         const X86Subtarget *Subtarget) {
25840   SDValue Op0 = N->getOperand(0);
25841   EVT VT = N->getValueType(0);
25842   EVT InVT = Op0.getValueType();
25843   EVT InSVT = InVT.getScalarType();
25844   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25845
25846   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25847   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25848   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25849     SDLoc dl(N);
25850     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25851                                  InVT.getVectorNumElements());
25852     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25853
25854     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25855       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25856
25857     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25858   }
25859
25860   return SDValue();
25861 }
25862
25863 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25864                                         const X86Subtarget *Subtarget) {
25865   // First try to optimize away the conversion entirely when it's
25866   // conditionally from a constant. Vectors only.
25867   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25868     return Res;
25869
25870   // Now move on to more general possibilities.
25871   SDValue Op0 = N->getOperand(0);
25872   EVT VT = N->getValueType(0);
25873   EVT InVT = Op0.getValueType();
25874   EVT InSVT = InVT.getScalarType();
25875
25876   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25877   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25878   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25879     SDLoc dl(N);
25880     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25881                                  InVT.getVectorNumElements());
25882     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25883     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25884   }
25885
25886   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25887   // a 32-bit target where SSE doesn't support i64->FP operations.
25888   if (Op0.getOpcode() == ISD::LOAD) {
25889     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25890     EVT LdVT = Ld->getValueType(0);
25891
25892     // This transformation is not supported if the result type is f16
25893     if (VT == MVT::f16)
25894       return SDValue();
25895
25896     if (!Ld->isVolatile() && !VT.isVector() &&
25897         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25898         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25899       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25900           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25901       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25902       return FILDChain;
25903     }
25904   }
25905   return SDValue();
25906 }
25907
25908 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25909 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25910                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25911   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25912   // the result is either zero or one (depending on the input carry bit).
25913   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25914   if (X86::isZeroNode(N->getOperand(0)) &&
25915       X86::isZeroNode(N->getOperand(1)) &&
25916       // We don't have a good way to replace an EFLAGS use, so only do this when
25917       // dead right now.
25918       SDValue(N, 1).use_empty()) {
25919     SDLoc DL(N);
25920     EVT VT = N->getValueType(0);
25921     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25922     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25923                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25924                                            DAG.getConstant(X86::COND_B, DL,
25925                                                            MVT::i8),
25926                                            N->getOperand(2)),
25927                                DAG.getConstant(1, DL, VT));
25928     return DCI.CombineTo(N, Res1, CarryOut);
25929   }
25930
25931   return SDValue();
25932 }
25933
25934 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25935 //      (add Y, (setne X, 0)) -> sbb -1, Y
25936 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25937 //      (sub (setne X, 0), Y) -> adc -1, Y
25938 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25939   SDLoc DL(N);
25940
25941   // Look through ZExts.
25942   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25943   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25944     return SDValue();
25945
25946   SDValue SetCC = Ext.getOperand(0);
25947   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25948     return SDValue();
25949
25950   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25951   if (CC != X86::COND_E && CC != X86::COND_NE)
25952     return SDValue();
25953
25954   SDValue Cmp = SetCC.getOperand(1);
25955   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25956       !X86::isZeroNode(Cmp.getOperand(1)) ||
25957       !Cmp.getOperand(0).getValueType().isInteger())
25958     return SDValue();
25959
25960   SDValue CmpOp0 = Cmp.getOperand(0);
25961   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25962                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25963
25964   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25965   if (CC == X86::COND_NE)
25966     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25967                        DL, OtherVal.getValueType(), OtherVal,
25968                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25969                        NewCmp);
25970   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25971                      DL, OtherVal.getValueType(), OtherVal,
25972                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25973 }
25974
25975 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25976 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25977                                  const X86Subtarget *Subtarget) {
25978   EVT VT = N->getValueType(0);
25979   SDValue Op0 = N->getOperand(0);
25980   SDValue Op1 = N->getOperand(1);
25981
25982   // Try to synthesize horizontal adds from adds of shuffles.
25983   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25984        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25985       isHorizontalBinOp(Op0, Op1, true))
25986     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25987
25988   return OptimizeConditionalInDecrement(N, DAG);
25989 }
25990
25991 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25992                                  const X86Subtarget *Subtarget) {
25993   SDValue Op0 = N->getOperand(0);
25994   SDValue Op1 = N->getOperand(1);
25995
25996   // X86 can't encode an immediate LHS of a sub. See if we can push the
25997   // negation into a preceding instruction.
25998   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25999     // If the RHS of the sub is a XOR with one use and a constant, invert the
26000     // immediate. Then add one to the LHS of the sub so we can turn
26001     // X-Y -> X+~Y+1, saving one register.
26002     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
26003         isa<ConstantSDNode>(Op1.getOperand(1))) {
26004       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
26005       EVT VT = Op0.getValueType();
26006       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
26007                                    Op1.getOperand(0),
26008                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
26009       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
26010                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
26011     }
26012   }
26013
26014   // Try to synthesize horizontal adds from adds of shuffles.
26015   EVT VT = N->getValueType(0);
26016   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26017        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26018       isHorizontalBinOp(Op0, Op1, true))
26019     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
26020
26021   return OptimizeConditionalInDecrement(N, DAG);
26022 }
26023
26024 /// performVZEXTCombine - Performs build vector combines
26025 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
26026                                    TargetLowering::DAGCombinerInfo &DCI,
26027                                    const X86Subtarget *Subtarget) {
26028   SDLoc DL(N);
26029   MVT VT = N->getSimpleValueType(0);
26030   SDValue Op = N->getOperand(0);
26031   MVT OpVT = Op.getSimpleValueType();
26032   MVT OpEltVT = OpVT.getVectorElementType();
26033   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
26034
26035   // (vzext (bitcast (vzext (x)) -> (vzext x)
26036   SDValue V = Op;
26037   while (V.getOpcode() == ISD::BITCAST)
26038     V = V.getOperand(0);
26039
26040   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
26041     MVT InnerVT = V.getSimpleValueType();
26042     MVT InnerEltVT = InnerVT.getVectorElementType();
26043
26044     // If the element sizes match exactly, we can just do one larger vzext. This
26045     // is always an exact type match as vzext operates on integer types.
26046     if (OpEltVT == InnerEltVT) {
26047       assert(OpVT == InnerVT && "Types must match for vzext!");
26048       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
26049     }
26050
26051     // The only other way we can combine them is if only a single element of the
26052     // inner vzext is used in the input to the outer vzext.
26053     if (InnerEltVT.getSizeInBits() < InputBits)
26054       return SDValue();
26055
26056     // In this case, the inner vzext is completely dead because we're going to
26057     // only look at bits inside of the low element. Just do the outer vzext on
26058     // a bitcast of the input to the inner.
26059     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
26060   }
26061
26062   // Check if we can bypass extracting and re-inserting an element of an input
26063   // vector. Essentially:
26064   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
26065   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
26066       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
26067       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
26068     SDValue ExtractedV = V.getOperand(0);
26069     SDValue OrigV = ExtractedV.getOperand(0);
26070     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
26071       if (ExtractIdx->getZExtValue() == 0) {
26072         MVT OrigVT = OrigV.getSimpleValueType();
26073         // Extract a subvector if necessary...
26074         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
26075           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
26076           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
26077                                     OrigVT.getVectorNumElements() / Ratio);
26078           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
26079                               DAG.getIntPtrConstant(0, DL));
26080         }
26081         Op = DAG.getBitcast(OpVT, OrigV);
26082         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
26083       }
26084   }
26085
26086   return SDValue();
26087 }
26088
26089 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
26090                                              DAGCombinerInfo &DCI) const {
26091   SelectionDAG &DAG = DCI.DAG;
26092   switch (N->getOpcode()) {
26093   default: break;
26094   case ISD::EXTRACT_VECTOR_ELT:
26095     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
26096   case ISD::VSELECT:
26097   case ISD::SELECT:
26098   case X86ISD::SHRUNKBLEND:
26099     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
26100   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
26101   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
26102   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
26103   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
26104   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
26105   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
26106   case ISD::SHL:
26107   case ISD::SRA:
26108   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
26109   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
26110   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
26111   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
26112   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
26113   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
26114   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
26115   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
26116   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
26117   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
26118   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
26119   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
26120   case X86ISD::FXOR:
26121   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
26122   case X86ISD::FMIN:
26123   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
26124   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
26125   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
26126   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
26127   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
26128   case ISD::ANY_EXTEND:
26129   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
26130   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
26131   case ISD::SIGN_EXTEND_INREG:
26132     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
26133   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
26134   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
26135   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
26136   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
26137   case X86ISD::SHUFP:       // Handle all target specific shuffles
26138   case X86ISD::PALIGNR:
26139   case X86ISD::UNPCKH:
26140   case X86ISD::UNPCKL:
26141   case X86ISD::MOVHLPS:
26142   case X86ISD::MOVLHPS:
26143   case X86ISD::PSHUFB:
26144   case X86ISD::PSHUFD:
26145   case X86ISD::PSHUFHW:
26146   case X86ISD::PSHUFLW:
26147   case X86ISD::MOVSS:
26148   case X86ISD::MOVSD:
26149   case X86ISD::VPERMILPI:
26150   case X86ISD::VPERM2X128:
26151   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
26152   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
26153   case X86ISD::INSERTPS: {
26154     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
26155       return PerformINSERTPSCombine(N, DAG, Subtarget);
26156     break;
26157   }
26158   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
26159   }
26160
26161   return SDValue();
26162 }
26163
26164 /// isTypeDesirableForOp - Return true if the target has native support for
26165 /// the specified value type and it is 'desirable' to use the type for the
26166 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
26167 /// instruction encodings are longer and some i16 instructions are slow.
26168 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
26169   if (!isTypeLegal(VT))
26170     return false;
26171   if (VT != MVT::i16)
26172     return true;
26173
26174   switch (Opc) {
26175   default:
26176     return true;
26177   case ISD::LOAD:
26178   case ISD::SIGN_EXTEND:
26179   case ISD::ZERO_EXTEND:
26180   case ISD::ANY_EXTEND:
26181   case ISD::SHL:
26182   case ISD::SRL:
26183   case ISD::SUB:
26184   case ISD::ADD:
26185   case ISD::MUL:
26186   case ISD::AND:
26187   case ISD::OR:
26188   case ISD::XOR:
26189     return false;
26190   }
26191 }
26192
26193 /// IsDesirableToPromoteOp - This method query the target whether it is
26194 /// beneficial for dag combiner to promote the specified node. If true, it
26195 /// should return the desired promotion type by reference.
26196 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
26197   EVT VT = Op.getValueType();
26198   if (VT != MVT::i16)
26199     return false;
26200
26201   bool Promote = false;
26202   bool Commute = false;
26203   switch (Op.getOpcode()) {
26204   default: break;
26205   case ISD::LOAD: {
26206     LoadSDNode *LD = cast<LoadSDNode>(Op);
26207     // If the non-extending load has a single use and it's not live out, then it
26208     // might be folded.
26209     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
26210                                                      Op.hasOneUse()*/) {
26211       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
26212              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
26213         // The only case where we'd want to promote LOAD (rather then it being
26214         // promoted as an operand is when it's only use is liveout.
26215         if (UI->getOpcode() != ISD::CopyToReg)
26216           return false;
26217       }
26218     }
26219     Promote = true;
26220     break;
26221   }
26222   case ISD::SIGN_EXTEND:
26223   case ISD::ZERO_EXTEND:
26224   case ISD::ANY_EXTEND:
26225     Promote = true;
26226     break;
26227   case ISD::SHL:
26228   case ISD::SRL: {
26229     SDValue N0 = Op.getOperand(0);
26230     // Look out for (store (shl (load), x)).
26231     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
26232       return false;
26233     Promote = true;
26234     break;
26235   }
26236   case ISD::ADD:
26237   case ISD::MUL:
26238   case ISD::AND:
26239   case ISD::OR:
26240   case ISD::XOR:
26241     Commute = true;
26242     // fallthrough
26243   case ISD::SUB: {
26244     SDValue N0 = Op.getOperand(0);
26245     SDValue N1 = Op.getOperand(1);
26246     if (!Commute && MayFoldLoad(N1))
26247       return false;
26248     // Avoid disabling potential load folding opportunities.
26249     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
26250       return false;
26251     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
26252       return false;
26253     Promote = true;
26254   }
26255   }
26256
26257   PVT = MVT::i32;
26258   return Promote;
26259 }
26260
26261 //===----------------------------------------------------------------------===//
26262 //                           X86 Inline Assembly Support
26263 //===----------------------------------------------------------------------===//
26264
26265 // Helper to match a string separated by whitespace.
26266 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
26267   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
26268
26269   for (StringRef Piece : Pieces) {
26270     if (!S.startswith(Piece)) // Check if the piece matches.
26271       return false;
26272
26273     S = S.substr(Piece.size());
26274     StringRef::size_type Pos = S.find_first_not_of(" \t");
26275     if (Pos == 0) // We matched a prefix.
26276       return false;
26277
26278     S = S.substr(Pos);
26279   }
26280
26281   return S.empty();
26282 }
26283
26284 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26285
26286   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26287     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26288         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26289         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26290
26291       if (AsmPieces.size() == 3)
26292         return true;
26293       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26294         return true;
26295     }
26296   }
26297   return false;
26298 }
26299
26300 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26301   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26302
26303   std::string AsmStr = IA->getAsmString();
26304
26305   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26306   if (!Ty || Ty->getBitWidth() % 16 != 0)
26307     return false;
26308
26309   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26310   SmallVector<StringRef, 4> AsmPieces;
26311   SplitString(AsmStr, AsmPieces, ";\n");
26312
26313   switch (AsmPieces.size()) {
26314   default: return false;
26315   case 1:
26316     // FIXME: this should verify that we are targeting a 486 or better.  If not,
26317     // we will turn this bswap into something that will be lowered to logical
26318     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
26319     // lower so don't worry about this.
26320     // bswap $0
26321     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26322         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26323         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26324         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26325         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26326         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26327       // No need to check constraints, nothing other than the equivalent of
26328       // "=r,0" would be valid here.
26329       return IntrinsicLowering::LowerToByteSwap(CI);
26330     }
26331
26332     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
26333     if (CI->getType()->isIntegerTy(16) &&
26334         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26335         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26336          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26337       AsmPieces.clear();
26338       StringRef ConstraintsStr = IA->getConstraintString();
26339       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26340       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26341       if (clobbersFlagRegisters(AsmPieces))
26342         return IntrinsicLowering::LowerToByteSwap(CI);
26343     }
26344     break;
26345   case 3:
26346     if (CI->getType()->isIntegerTy(32) &&
26347         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26348         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26349         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26350         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26351       AsmPieces.clear();
26352       StringRef ConstraintsStr = IA->getConstraintString();
26353       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26354       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26355       if (clobbersFlagRegisters(AsmPieces))
26356         return IntrinsicLowering::LowerToByteSwap(CI);
26357     }
26358
26359     if (CI->getType()->isIntegerTy(64)) {
26360       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26361       if (Constraints.size() >= 2 &&
26362           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26363           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26364         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
26365         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26366             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26367             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26368           return IntrinsicLowering::LowerToByteSwap(CI);
26369       }
26370     }
26371     break;
26372   }
26373   return false;
26374 }
26375
26376 /// getConstraintType - Given a constraint letter, return the type of
26377 /// constraint it is for this target.
26378 X86TargetLowering::ConstraintType
26379 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26380   if (Constraint.size() == 1) {
26381     switch (Constraint[0]) {
26382     case 'R':
26383     case 'q':
26384     case 'Q':
26385     case 'f':
26386     case 't':
26387     case 'u':
26388     case 'y':
26389     case 'x':
26390     case 'Y':
26391     case 'l':
26392       return C_RegisterClass;
26393     case 'a':
26394     case 'b':
26395     case 'c':
26396     case 'd':
26397     case 'S':
26398     case 'D':
26399     case 'A':
26400       return C_Register;
26401     case 'I':
26402     case 'J':
26403     case 'K':
26404     case 'L':
26405     case 'M':
26406     case 'N':
26407     case 'G':
26408     case 'C':
26409     case 'e':
26410     case 'Z':
26411       return C_Other;
26412     default:
26413       break;
26414     }
26415   }
26416   return TargetLowering::getConstraintType(Constraint);
26417 }
26418
26419 /// Examine constraint type and operand type and determine a weight value.
26420 /// This object must already have been set up with the operand type
26421 /// and the current alternative constraint selected.
26422 TargetLowering::ConstraintWeight
26423   X86TargetLowering::getSingleConstraintMatchWeight(
26424     AsmOperandInfo &info, const char *constraint) const {
26425   ConstraintWeight weight = CW_Invalid;
26426   Value *CallOperandVal = info.CallOperandVal;
26427     // If we don't have a value, we can't do a match,
26428     // but allow it at the lowest weight.
26429   if (!CallOperandVal)
26430     return CW_Default;
26431   Type *type = CallOperandVal->getType();
26432   // Look at the constraint type.
26433   switch (*constraint) {
26434   default:
26435     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26436   case 'R':
26437   case 'q':
26438   case 'Q':
26439   case 'a':
26440   case 'b':
26441   case 'c':
26442   case 'd':
26443   case 'S':
26444   case 'D':
26445   case 'A':
26446     if (CallOperandVal->getType()->isIntegerTy())
26447       weight = CW_SpecificReg;
26448     break;
26449   case 'f':
26450   case 't':
26451   case 'u':
26452     if (type->isFloatingPointTy())
26453       weight = CW_SpecificReg;
26454     break;
26455   case 'y':
26456     if (type->isX86_MMXTy() && Subtarget->hasMMX())
26457       weight = CW_SpecificReg;
26458     break;
26459   case 'x':
26460   case 'Y':
26461     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26462         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26463       weight = CW_Register;
26464     break;
26465   case 'I':
26466     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26467       if (C->getZExtValue() <= 31)
26468         weight = CW_Constant;
26469     }
26470     break;
26471   case 'J':
26472     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26473       if (C->getZExtValue() <= 63)
26474         weight = CW_Constant;
26475     }
26476     break;
26477   case 'K':
26478     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26479       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26480         weight = CW_Constant;
26481     }
26482     break;
26483   case 'L':
26484     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26485       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26486         weight = CW_Constant;
26487     }
26488     break;
26489   case 'M':
26490     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26491       if (C->getZExtValue() <= 3)
26492         weight = CW_Constant;
26493     }
26494     break;
26495   case 'N':
26496     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26497       if (C->getZExtValue() <= 0xff)
26498         weight = CW_Constant;
26499     }
26500     break;
26501   case 'G':
26502   case 'C':
26503     if (isa<ConstantFP>(CallOperandVal)) {
26504       weight = CW_Constant;
26505     }
26506     break;
26507   case 'e':
26508     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26509       if ((C->getSExtValue() >= -0x80000000LL) &&
26510           (C->getSExtValue() <= 0x7fffffffLL))
26511         weight = CW_Constant;
26512     }
26513     break;
26514   case 'Z':
26515     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26516       if (C->getZExtValue() <= 0xffffffff)
26517         weight = CW_Constant;
26518     }
26519     break;
26520   }
26521   return weight;
26522 }
26523
26524 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26525 /// with another that has more specific requirements based on the type of the
26526 /// corresponding operand.
26527 const char *X86TargetLowering::
26528 LowerXConstraint(EVT ConstraintVT) const {
26529   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26530   // 'f' like normal targets.
26531   if (ConstraintVT.isFloatingPoint()) {
26532     if (Subtarget->hasSSE2())
26533       return "Y";
26534     if (Subtarget->hasSSE1())
26535       return "x";
26536   }
26537
26538   return TargetLowering::LowerXConstraint(ConstraintVT);
26539 }
26540
26541 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26542 /// vector.  If it is invalid, don't add anything to Ops.
26543 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26544                                                      std::string &Constraint,
26545                                                      std::vector<SDValue>&Ops,
26546                                                      SelectionDAG &DAG) const {
26547   SDValue Result;
26548
26549   // Only support length 1 constraints for now.
26550   if (Constraint.length() > 1) return;
26551
26552   char ConstraintLetter = Constraint[0];
26553   switch (ConstraintLetter) {
26554   default: break;
26555   case 'I':
26556     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26557       if (C->getZExtValue() <= 31) {
26558         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26559                                        Op.getValueType());
26560         break;
26561       }
26562     }
26563     return;
26564   case 'J':
26565     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26566       if (C->getZExtValue() <= 63) {
26567         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26568                                        Op.getValueType());
26569         break;
26570       }
26571     }
26572     return;
26573   case 'K':
26574     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26575       if (isInt<8>(C->getSExtValue())) {
26576         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26577                                        Op.getValueType());
26578         break;
26579       }
26580     }
26581     return;
26582   case 'L':
26583     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26584       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26585           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26586         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26587                                        Op.getValueType());
26588         break;
26589       }
26590     }
26591     return;
26592   case 'M':
26593     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26594       if (C->getZExtValue() <= 3) {
26595         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26596                                        Op.getValueType());
26597         break;
26598       }
26599     }
26600     return;
26601   case 'N':
26602     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26603       if (C->getZExtValue() <= 255) {
26604         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26605                                        Op.getValueType());
26606         break;
26607       }
26608     }
26609     return;
26610   case 'O':
26611     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26612       if (C->getZExtValue() <= 127) {
26613         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26614                                        Op.getValueType());
26615         break;
26616       }
26617     }
26618     return;
26619   case 'e': {
26620     // 32-bit signed value
26621     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26622       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26623                                            C->getSExtValue())) {
26624         // Widen to 64 bits here to get it sign extended.
26625         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26626         break;
26627       }
26628     // FIXME gcc accepts some relocatable values here too, but only in certain
26629     // memory models; it's complicated.
26630     }
26631     return;
26632   }
26633   case 'Z': {
26634     // 32-bit unsigned value
26635     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26636       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26637                                            C->getZExtValue())) {
26638         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26639                                        Op.getValueType());
26640         break;
26641       }
26642     }
26643     // FIXME gcc accepts some relocatable values here too, but only in certain
26644     // memory models; it's complicated.
26645     return;
26646   }
26647   case 'i': {
26648     // Literal immediates are always ok.
26649     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26650       // Widen to 64 bits here to get it sign extended.
26651       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26652       break;
26653     }
26654
26655     // In any sort of PIC mode addresses need to be computed at runtime by
26656     // adding in a register or some sort of table lookup.  These can't
26657     // be used as immediates.
26658     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26659       return;
26660
26661     // If we are in non-pic codegen mode, we allow the address of a global (with
26662     // an optional displacement) to be used with 'i'.
26663     GlobalAddressSDNode *GA = nullptr;
26664     int64_t Offset = 0;
26665
26666     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26667     while (1) {
26668       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26669         Offset += GA->getOffset();
26670         break;
26671       } else if (Op.getOpcode() == ISD::ADD) {
26672         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26673           Offset += C->getZExtValue();
26674           Op = Op.getOperand(0);
26675           continue;
26676         }
26677       } else if (Op.getOpcode() == ISD::SUB) {
26678         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26679           Offset += -C->getZExtValue();
26680           Op = Op.getOperand(0);
26681           continue;
26682         }
26683       }
26684
26685       // Otherwise, this isn't something we can handle, reject it.
26686       return;
26687     }
26688
26689     const GlobalValue *GV = GA->getGlobal();
26690     // If we require an extra load to get this address, as in PIC mode, we
26691     // can't accept it.
26692     if (isGlobalStubReference(
26693             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26694       return;
26695
26696     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26697                                         GA->getValueType(0), Offset);
26698     break;
26699   }
26700   }
26701
26702   if (Result.getNode()) {
26703     Ops.push_back(Result);
26704     return;
26705   }
26706   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26707 }
26708
26709 std::pair<unsigned, const TargetRegisterClass *>
26710 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26711                                                 StringRef Constraint,
26712                                                 MVT VT) const {
26713   // First, see if this is a constraint that directly corresponds to an LLVM
26714   // register class.
26715   if (Constraint.size() == 1) {
26716     // GCC Constraint Letters
26717     switch (Constraint[0]) {
26718     default: break;
26719       // TODO: Slight differences here in allocation order and leaving
26720       // RIP in the class. Do they matter any more here than they do
26721       // in the normal allocation?
26722     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26723       if (Subtarget->is64Bit()) {
26724         if (VT == MVT::i32 || VT == MVT::f32)
26725           return std::make_pair(0U, &X86::GR32RegClass);
26726         if (VT == MVT::i16)
26727           return std::make_pair(0U, &X86::GR16RegClass);
26728         if (VT == MVT::i8 || VT == MVT::i1)
26729           return std::make_pair(0U, &X86::GR8RegClass);
26730         if (VT == MVT::i64 || VT == MVT::f64)
26731           return std::make_pair(0U, &X86::GR64RegClass);
26732         break;
26733       }
26734       // 32-bit fallthrough
26735     case 'Q':   // Q_REGS
26736       if (VT == MVT::i32 || VT == MVT::f32)
26737         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26738       if (VT == MVT::i16)
26739         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26740       if (VT == MVT::i8 || VT == MVT::i1)
26741         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26742       if (VT == MVT::i64)
26743         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26744       break;
26745     case 'r':   // GENERAL_REGS
26746     case 'l':   // INDEX_REGS
26747       if (VT == MVT::i8 || VT == MVT::i1)
26748         return std::make_pair(0U, &X86::GR8RegClass);
26749       if (VT == MVT::i16)
26750         return std::make_pair(0U, &X86::GR16RegClass);
26751       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26752         return std::make_pair(0U, &X86::GR32RegClass);
26753       return std::make_pair(0U, &X86::GR64RegClass);
26754     case 'R':   // LEGACY_REGS
26755       if (VT == MVT::i8 || VT == MVT::i1)
26756         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26757       if (VT == MVT::i16)
26758         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26759       if (VT == MVT::i32 || !Subtarget->is64Bit())
26760         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26761       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26762     case 'f':  // FP Stack registers.
26763       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26764       // value to the correct fpstack register class.
26765       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26766         return std::make_pair(0U, &X86::RFP32RegClass);
26767       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26768         return std::make_pair(0U, &X86::RFP64RegClass);
26769       return std::make_pair(0U, &X86::RFP80RegClass);
26770     case 'y':   // MMX_REGS if MMX allowed.
26771       if (!Subtarget->hasMMX()) break;
26772       return std::make_pair(0U, &X86::VR64RegClass);
26773     case 'Y':   // SSE_REGS if SSE2 allowed
26774       if (!Subtarget->hasSSE2()) break;
26775       // FALL THROUGH.
26776     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26777       if (!Subtarget->hasSSE1()) break;
26778
26779       switch (VT.SimpleTy) {
26780       default: break;
26781       // Scalar SSE types.
26782       case MVT::f32:
26783       case MVT::i32:
26784         return std::make_pair(0U, &X86::FR32RegClass);
26785       case MVT::f64:
26786       case MVT::i64:
26787         return std::make_pair(0U, &X86::FR64RegClass);
26788       // Vector types.
26789       case MVT::v16i8:
26790       case MVT::v8i16:
26791       case MVT::v4i32:
26792       case MVT::v2i64:
26793       case MVT::v4f32:
26794       case MVT::v2f64:
26795         return std::make_pair(0U, &X86::VR128RegClass);
26796       // AVX types.
26797       case MVT::v32i8:
26798       case MVT::v16i16:
26799       case MVT::v8i32:
26800       case MVT::v4i64:
26801       case MVT::v8f32:
26802       case MVT::v4f64:
26803         return std::make_pair(0U, &X86::VR256RegClass);
26804       case MVT::v8f64:
26805       case MVT::v16f32:
26806       case MVT::v16i32:
26807       case MVT::v8i64:
26808         return std::make_pair(0U, &X86::VR512RegClass);
26809       }
26810       break;
26811     }
26812   }
26813
26814   // Use the default implementation in TargetLowering to convert the register
26815   // constraint into a member of a register class.
26816   std::pair<unsigned, const TargetRegisterClass*> Res;
26817   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26818
26819   // Not found as a standard register?
26820   if (!Res.second) {
26821     // Map st(0) -> st(7) -> ST0
26822     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26823         tolower(Constraint[1]) == 's' &&
26824         tolower(Constraint[2]) == 't' &&
26825         Constraint[3] == '(' &&
26826         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26827         Constraint[5] == ')' &&
26828         Constraint[6] == '}') {
26829
26830       Res.first = X86::FP0+Constraint[4]-'0';
26831       Res.second = &X86::RFP80RegClass;
26832       return Res;
26833     }
26834
26835     // GCC allows "st(0)" to be called just plain "st".
26836     if (StringRef("{st}").equals_lower(Constraint)) {
26837       Res.first = X86::FP0;
26838       Res.second = &X86::RFP80RegClass;
26839       return Res;
26840     }
26841
26842     // flags -> EFLAGS
26843     if (StringRef("{flags}").equals_lower(Constraint)) {
26844       Res.first = X86::EFLAGS;
26845       Res.second = &X86::CCRRegClass;
26846       return Res;
26847     }
26848
26849     // 'A' means EAX + EDX.
26850     if (Constraint == "A") {
26851       Res.first = X86::EAX;
26852       Res.second = &X86::GR32_ADRegClass;
26853       return Res;
26854     }
26855     return Res;
26856   }
26857
26858   // Otherwise, check to see if this is a register class of the wrong value
26859   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26860   // turn into {ax},{dx}.
26861   // MVT::Other is used to specify clobber names.
26862   if (Res.second->hasType(VT) || VT == MVT::Other)
26863     return Res;   // Correct type already, nothing to do.
26864
26865   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26866   // return "eax". This should even work for things like getting 64bit integer
26867   // registers when given an f64 type.
26868   const TargetRegisterClass *Class = Res.second;
26869   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26870       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26871     unsigned Size = VT.getSizeInBits();
26872     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26873                                   : Size == 16 ? MVT::i16
26874                                   : Size == 32 ? MVT::i32
26875                                   : Size == 64 ? MVT::i64
26876                                   : MVT::Other;
26877     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26878     if (DestReg > 0) {
26879       Res.first = DestReg;
26880       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26881                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26882                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26883                  : &X86::GR64RegClass;
26884       assert(Res.second->contains(Res.first) && "Register in register class");
26885     } else {
26886       // No register found/type mismatch.
26887       Res.first = 0;
26888       Res.second = nullptr;
26889     }
26890   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26891              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26892              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26893              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26894              Class == &X86::VR512RegClass) {
26895     // Handle references to XMM physical registers that got mapped into the
26896     // wrong class.  This can happen with constraints like {xmm0} where the
26897     // target independent register mapper will just pick the first match it can
26898     // find, ignoring the required type.
26899
26900     if (VT == MVT::f32 || VT == MVT::i32)
26901       Res.second = &X86::FR32RegClass;
26902     else if (VT == MVT::f64 || VT == MVT::i64)
26903       Res.second = &X86::FR64RegClass;
26904     else if (X86::VR128RegClass.hasType(VT))
26905       Res.second = &X86::VR128RegClass;
26906     else if (X86::VR256RegClass.hasType(VT))
26907       Res.second = &X86::VR256RegClass;
26908     else if (X86::VR512RegClass.hasType(VT))
26909       Res.second = &X86::VR512RegClass;
26910     else {
26911       // Type mismatch and not a clobber: Return an error;
26912       Res.first = 0;
26913       Res.second = nullptr;
26914     }
26915   }
26916
26917   return Res;
26918 }
26919
26920 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26921                                             const AddrMode &AM, Type *Ty,
26922                                             unsigned AS) const {
26923   // Scaling factors are not free at all.
26924   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26925   // will take 2 allocations in the out of order engine instead of 1
26926   // for plain addressing mode, i.e. inst (reg1).
26927   // E.g.,
26928   // vaddps (%rsi,%drx), %ymm0, %ymm1
26929   // Requires two allocations (one for the load, one for the computation)
26930   // whereas:
26931   // vaddps (%rsi), %ymm0, %ymm1
26932   // Requires just 1 allocation, i.e., freeing allocations for other operations
26933   // and having less micro operations to execute.
26934   //
26935   // For some X86 architectures, this is even worse because for instance for
26936   // stores, the complex addressing mode forces the instruction to use the
26937   // "load" ports instead of the dedicated "store" port.
26938   // E.g., on Haswell:
26939   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26940   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26941   if (isLegalAddressingMode(DL, AM, Ty, AS))
26942     // Scale represents reg2 * scale, thus account for 1
26943     // as soon as we use a second register.
26944     return AM.Scale != 0;
26945   return -1;
26946 }
26947
26948 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
26949   // Integer division on x86 is expensive. However, when aggressively optimizing
26950   // for code size, we prefer to use a div instruction, as it is usually smaller
26951   // than the alternative sequence.
26952   // The exception to this is vector division. Since x86 doesn't have vector
26953   // integer division, leaving the division as-is is a loss even in terms of
26954   // size, because it will have to be scalarized, while the alternative code
26955   // sequence can be performed in vector form.
26956   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
26957                                    Attribute::MinSize);
26958   return OptSize && !VT.isVector();
26959 }