55f24cafcc8e3f36cd4c68d3cbfca1962f97731b
[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. The extended elements are consecutive and
7361 /// begin and can start from an offseted element index in the input; to
7362 /// avoid excess shuffling the offset must either being in the bottom lane
7363 /// or at the start of a higher lane. All extended elements must be from
7364 /// the same lane.
7365 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7366     SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7367     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7368   assert(Scale > 1 && "Need a scale to extend.");
7369   int EltBits = VT.getScalarSizeInBits();
7370   int NumElements = VT.getVectorNumElements();
7371   int NumEltsPerLane = 128 / EltBits;
7372   int OffsetLane = Offset / NumEltsPerLane;
7373   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7374          "Only 8, 16, and 32 bit elements can be extended.");
7375   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7376   assert(0 <= Offset && "Extension offset must be positive.");
7377   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7378          "Extension offset must be in the first lane or start an upper lane.");
7379
7380   // Check that an index is in same lane as the base offset.
7381   auto SafeOffset = [&](int Idx) {
7382     return OffsetLane == (Idx / NumEltsPerLane);
7383   };
7384
7385   // Shift along an input so that the offset base moves to the first element.
7386   auto ShuffleOffset = [&](SDValue V) {
7387     if (!Offset)
7388       return V;
7389
7390     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7391     for (int i = 0; i * Scale < NumElements; ++i) {
7392       int SrcIdx = i + Offset;
7393       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7394     }
7395     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7396   };
7397
7398   // Found a valid zext mask! Try various lowering strategies based on the
7399   // input type and available ISA extensions.
7400   if (Subtarget->hasSSE41()) {
7401     // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7402     // PUNPCK will catch this in a later shuffle match.
7403     if (Offset && Scale == 2 && VT.getSizeInBits() == 128)
7404       return SDValue();
7405     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7406                                  NumElements / Scale);
7407     InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7408     return DAG.getBitcast(VT, InputV);
7409   }
7410
7411   assert(VT.getSizeInBits() == 128 && "Only 128-bit vectors can be extended.");
7412
7413   // For any extends we can cheat for larger element sizes and use shuffle
7414   // instructions that can fold with a load and/or copy.
7415   if (AnyExt && EltBits == 32) {
7416     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7417                          -1};
7418     return DAG.getBitcast(
7419         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7420                         DAG.getBitcast(MVT::v4i32, InputV),
7421                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7422   }
7423   if (AnyExt && EltBits == 16 && Scale > 2) {
7424     int PSHUFDMask[4] = {Offset / 2, -1,
7425                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7426     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7427                          DAG.getBitcast(MVT::v4i32, InputV),
7428                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7429     int PSHUFWMask[4] = {1, -1, -1, -1};
7430     unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7431     return DAG.getBitcast(
7432         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7433                         DAG.getBitcast(MVT::v8i16, InputV),
7434                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7435   }
7436
7437   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7438   // to 64-bits.
7439   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7440     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7441     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7442
7443     int LoIdx = Offset * EltBits;
7444     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7445                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7446                                          DAG.getConstant(EltBits, DL, MVT::i8),
7447                                          DAG.getConstant(LoIdx, DL, MVT::i8)));
7448
7449     if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7450         !SafeOffset(Offset + 1))
7451       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7452
7453     int HiIdx = (Offset + 1) * EltBits;
7454     SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7455                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7456                                          DAG.getConstant(EltBits, DL, MVT::i8),
7457                                          DAG.getConstant(HiIdx, DL, MVT::i8)));
7458     return DAG.getNode(ISD::BITCAST, DL, VT,
7459                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7460   }
7461
7462   // If this would require more than 2 unpack instructions to expand, use
7463   // pshufb when available. We can only use more than 2 unpack instructions
7464   // when zero extending i8 elements which also makes it easier to use pshufb.
7465   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7466     assert(NumElements == 16 && "Unexpected byte vector width!");
7467     SDValue PSHUFBMask[16];
7468     for (int i = 0; i < 16; ++i) {
7469       int Idx = Offset + (i / Scale);
7470       PSHUFBMask[i] = DAG.getConstant(
7471           (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7472     }
7473     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7474     return DAG.getBitcast(VT,
7475                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7476                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7477                                                   MVT::v16i8, PSHUFBMask)));
7478   }
7479
7480   // If we are extending from an (odd)offset, shuffle them by 1 element.
7481   if (Offset & 1) {
7482     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7483     for (int i = 1; i < NumElements; ++i)
7484       ShMask[i - 1] = i;
7485     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7486     Offset--;
7487   }
7488
7489   // Otherwise emit a sequence of unpacks.
7490   do {
7491     unsigned UnpackLoHi = X86ISD::UNPCKL;
7492     if (Offset >= (NumElements / 2)) {
7493       UnpackLoHi = X86ISD::UNPCKH;
7494       Offset -= (NumElements / 2);
7495     }
7496
7497     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7498     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7499                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7500     InputV = DAG.getBitcast(InputVT, InputV);
7501     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7502     Scale /= 2;
7503     EltBits *= 2;
7504     NumElements /= 2;
7505   } while (Scale > 1);
7506   return DAG.getBitcast(VT, InputV);
7507 }
7508
7509 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7510 ///
7511 /// This routine will try to do everything in its power to cleverly lower
7512 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7513 /// check for the profitability of this lowering,  it tries to aggressively
7514 /// match this pattern. It will use all of the micro-architectural details it
7515 /// can to emit an efficient lowering. It handles both blends with all-zero
7516 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7517 /// masking out later).
7518 ///
7519 /// The reason we have dedicated lowering for zext-style shuffles is that they
7520 /// are both incredibly common and often quite performance sensitive.
7521 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7522     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7523     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7524   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7525
7526   int Bits = VT.getSizeInBits();
7527   int NumLanes = Bits / 128;
7528   int NumElements = VT.getVectorNumElements();
7529   int NumEltsPerLane = NumElements / NumLanes;
7530   assert(VT.getScalarSizeInBits() <= 32 &&
7531          "Exceeds 32-bit integer zero extension limit");
7532   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7533
7534   // Define a helper function to check a particular ext-scale and lower to it if
7535   // valid.
7536   auto Lower = [&](int Scale) -> SDValue {
7537     SDValue InputV;
7538     bool AnyExt = true;
7539     int Offset = 0;
7540     int Matches = 0;
7541     for (int i = 0; i < NumElements; ++i) {
7542       int M = Mask[i];
7543       if (M == -1)
7544         continue; // Valid anywhere but doesn't tell us anything.
7545       if (i % Scale != 0) {
7546         // Each of the extended elements need to be zeroable.
7547         if (!Zeroable[i])
7548           return SDValue();
7549
7550         // We no longer are in the anyext case.
7551         AnyExt = false;
7552         continue;
7553       }
7554
7555       // Each of the base elements needs to be consecutive indices into the
7556       // same input vector.
7557       SDValue V = M < NumElements ? V1 : V2;
7558       M = M % NumElements;
7559       if (!InputV) {
7560         InputV = V;
7561         Offset = M - (i / Scale);
7562       } else if (InputV != V)
7563         return SDValue(); // Flip-flopping inputs.
7564
7565       // Offset must start in the lowest 128-bit lane or at the start of an
7566       // upper lane.
7567       // FIXME: Is it ever worth allowing a negative base offset?
7568       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7569             (Offset % NumEltsPerLane) == 0))
7570         return SDValue();
7571
7572       // If we are offsetting, all referenced entries must come from the same
7573       // lane.
7574       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7575         return SDValue();
7576
7577       if ((M % NumElements) != (Offset + (i / Scale)))
7578         return SDValue(); // Non-consecutive strided elements.
7579       Matches++;
7580     }
7581
7582     // If we fail to find an input, we have a zero-shuffle which should always
7583     // have already been handled.
7584     // FIXME: Maybe handle this here in case during blending we end up with one?
7585     if (!InputV)
7586       return SDValue();
7587
7588     // If we are offsetting, don't extend if we only match a single input, we
7589     // can always do better by using a basic PSHUF or PUNPCK.
7590     if (Offset != 0 && Matches < 2)
7591       return SDValue();
7592
7593     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7594         DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7595   };
7596
7597   // The widest scale possible for extending is to a 64-bit integer.
7598   assert(Bits % 64 == 0 &&
7599          "The number of bits in a vector must be divisible by 64 on x86!");
7600   int NumExtElements = Bits / 64;
7601
7602   // Each iteration, try extending the elements half as much, but into twice as
7603   // many elements.
7604   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7605     assert(NumElements % NumExtElements == 0 &&
7606            "The input vector size must be divisible by the extended size.");
7607     if (SDValue V = Lower(NumElements / NumExtElements))
7608       return V;
7609   }
7610
7611   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7612   if (Bits != 128)
7613     return SDValue();
7614
7615   // Returns one of the source operands if the shuffle can be reduced to a
7616   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7617   auto CanZExtLowHalf = [&]() {
7618     for (int i = NumElements / 2; i != NumElements; ++i)
7619       if (!Zeroable[i])
7620         return SDValue();
7621     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7622       return V1;
7623     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7624       return V2;
7625     return SDValue();
7626   };
7627
7628   if (SDValue V = CanZExtLowHalf()) {
7629     V = DAG.getBitcast(MVT::v2i64, V);
7630     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7631     return DAG.getBitcast(VT, V);
7632   }
7633
7634   // No viable ext lowering found.
7635   return SDValue();
7636 }
7637
7638 /// \brief Try to get a scalar value for a specific element of a vector.
7639 ///
7640 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7641 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7642                                               SelectionDAG &DAG) {
7643   MVT VT = V.getSimpleValueType();
7644   MVT EltVT = VT.getVectorElementType();
7645   while (V.getOpcode() == ISD::BITCAST)
7646     V = V.getOperand(0);
7647   // If the bitcasts shift the element size, we can't extract an equivalent
7648   // element from it.
7649   MVT NewVT = V.getSimpleValueType();
7650   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7651     return SDValue();
7652
7653   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7654       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7655     // Ensure the scalar operand is the same size as the destination.
7656     // FIXME: Add support for scalar truncation where possible.
7657     SDValue S = V.getOperand(Idx);
7658     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7659       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7660   }
7661
7662   return SDValue();
7663 }
7664
7665 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7666 ///
7667 /// This is particularly important because the set of instructions varies
7668 /// significantly based on whether the operand is a load or not.
7669 static bool isShuffleFoldableLoad(SDValue V) {
7670   while (V.getOpcode() == ISD::BITCAST)
7671     V = V.getOperand(0);
7672
7673   return ISD::isNON_EXTLoad(V.getNode());
7674 }
7675
7676 /// \brief Try to lower insertion of a single element into a zero vector.
7677 ///
7678 /// This is a common pattern that we have especially efficient patterns to lower
7679 /// across all subtarget feature sets.
7680 static SDValue lowerVectorShuffleAsElementInsertion(
7681     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7682     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7683   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7684   MVT ExtVT = VT;
7685   MVT EltVT = VT.getVectorElementType();
7686
7687   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7688                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7689                 Mask.begin();
7690   bool IsV1Zeroable = true;
7691   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7692     if (i != V2Index && !Zeroable[i]) {
7693       IsV1Zeroable = false;
7694       break;
7695     }
7696
7697   // Check for a single input from a SCALAR_TO_VECTOR node.
7698   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7699   // all the smarts here sunk into that routine. However, the current
7700   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7701   // vector shuffle lowering is dead.
7702   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7703                                                DAG);
7704   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7705     // We need to zext the scalar if it is smaller than an i32.
7706     V2S = DAG.getBitcast(EltVT, V2S);
7707     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7708       // Using zext to expand a narrow element won't work for non-zero
7709       // insertions.
7710       if (!IsV1Zeroable)
7711         return SDValue();
7712
7713       // Zero-extend directly to i32.
7714       ExtVT = MVT::v4i32;
7715       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7716     }
7717     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7718   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7719              EltVT == MVT::i16) {
7720     // Either not inserting from the low element of the input or the input
7721     // element size is too small to use VZEXT_MOVL to clear the high bits.
7722     return SDValue();
7723   }
7724
7725   if (!IsV1Zeroable) {
7726     // If V1 can't be treated as a zero vector we have fewer options to lower
7727     // this. We can't support integer vectors or non-zero targets cheaply, and
7728     // the V1 elements can't be permuted in any way.
7729     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7730     if (!VT.isFloatingPoint() || V2Index != 0)
7731       return SDValue();
7732     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7733     V1Mask[V2Index] = -1;
7734     if (!isNoopShuffleMask(V1Mask))
7735       return SDValue();
7736     // This is essentially a special case blend operation, but if we have
7737     // general purpose blend operations, they are always faster. Bail and let
7738     // the rest of the lowering handle these as blends.
7739     if (Subtarget->hasSSE41())
7740       return SDValue();
7741
7742     // Otherwise, use MOVSD or MOVSS.
7743     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7744            "Only two types of floating point element types to handle!");
7745     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7746                        ExtVT, V1, V2);
7747   }
7748
7749   // This lowering only works for the low element with floating point vectors.
7750   if (VT.isFloatingPoint() && V2Index != 0)
7751     return SDValue();
7752
7753   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7754   if (ExtVT != VT)
7755     V2 = DAG.getBitcast(VT, V2);
7756
7757   if (V2Index != 0) {
7758     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7759     // the desired position. Otherwise it is more efficient to do a vector
7760     // shift left. We know that we can do a vector shift left because all
7761     // the inputs are zero.
7762     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7763       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7764       V2Shuffle[V2Index] = 0;
7765       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7766     } else {
7767       V2 = DAG.getBitcast(MVT::v2i64, V2);
7768       V2 = DAG.getNode(
7769           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7770           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7771                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7772                               DAG.getDataLayout(), VT)));
7773       V2 = DAG.getBitcast(VT, V2);
7774     }
7775   }
7776   return V2;
7777 }
7778
7779 /// \brief Try to lower broadcast of a single element.
7780 ///
7781 /// For convenience, this code also bundles all of the subtarget feature set
7782 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7783 /// a convenient way to factor it out.
7784 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7785                                              ArrayRef<int> Mask,
7786                                              const X86Subtarget *Subtarget,
7787                                              SelectionDAG &DAG) {
7788   if (!Subtarget->hasAVX())
7789     return SDValue();
7790   if (VT.isInteger() && !Subtarget->hasAVX2())
7791     return SDValue();
7792
7793   // Check that the mask is a broadcast.
7794   int BroadcastIdx = -1;
7795   for (int M : Mask)
7796     if (M >= 0 && BroadcastIdx == -1)
7797       BroadcastIdx = M;
7798     else if (M >= 0 && M != BroadcastIdx)
7799       return SDValue();
7800
7801   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7802                                             "a sorted mask where the broadcast "
7803                                             "comes from V1.");
7804
7805   // Go up the chain of (vector) values to find a scalar load that we can
7806   // combine with the broadcast.
7807   for (;;) {
7808     switch (V.getOpcode()) {
7809     case ISD::CONCAT_VECTORS: {
7810       int OperandSize = Mask.size() / V.getNumOperands();
7811       V = V.getOperand(BroadcastIdx / OperandSize);
7812       BroadcastIdx %= OperandSize;
7813       continue;
7814     }
7815
7816     case ISD::INSERT_SUBVECTOR: {
7817       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7818       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7819       if (!ConstantIdx)
7820         break;
7821
7822       int BeginIdx = (int)ConstantIdx->getZExtValue();
7823       int EndIdx =
7824           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7825       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7826         BroadcastIdx -= BeginIdx;
7827         V = VInner;
7828       } else {
7829         V = VOuter;
7830       }
7831       continue;
7832     }
7833     }
7834     break;
7835   }
7836
7837   // Check if this is a broadcast of a scalar. We special case lowering
7838   // for scalars so that we can more effectively fold with loads.
7839   // First, look through bitcast: if the original value has a larger element
7840   // type than the shuffle, the broadcast element is in essence truncated.
7841   // Make that explicit to ease folding.
7842   if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7843     EVT EltVT = VT.getVectorElementType();
7844     SDValue V0 = V.getOperand(0);
7845     EVT V0VT = V0.getValueType();
7846
7847     if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7848         ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7849          (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7850       V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7851       BroadcastIdx = 0;
7852     }
7853   }
7854
7855   // Also check the simpler case, where we can directly reuse the scalar.
7856   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7857       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7858     V = V.getOperand(BroadcastIdx);
7859
7860     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7861     // Only AVX2 has register broadcasts.
7862     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7863       return SDValue();
7864   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7865     // We can't broadcast from a vector register without AVX2, and we can only
7866     // broadcast from the zero-element of a vector register.
7867     return SDValue();
7868   }
7869
7870   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7871 }
7872
7873 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7874 // INSERTPS when the V1 elements are already in the correct locations
7875 // because otherwise we can just always use two SHUFPS instructions which
7876 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7877 // perform INSERTPS if a single V1 element is out of place and all V2
7878 // elements are zeroable.
7879 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7880                                             ArrayRef<int> Mask,
7881                                             SelectionDAG &DAG) {
7882   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7883   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7884   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7885   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7886
7887   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7888
7889   unsigned ZMask = 0;
7890   int V1DstIndex = -1;
7891   int V2DstIndex = -1;
7892   bool V1UsedInPlace = false;
7893
7894   for (int i = 0; i < 4; ++i) {
7895     // Synthesize a zero mask from the zeroable elements (includes undefs).
7896     if (Zeroable[i]) {
7897       ZMask |= 1 << i;
7898       continue;
7899     }
7900
7901     // Flag if we use any V1 inputs in place.
7902     if (i == Mask[i]) {
7903       V1UsedInPlace = true;
7904       continue;
7905     }
7906
7907     // We can only insert a single non-zeroable element.
7908     if (V1DstIndex != -1 || V2DstIndex != -1)
7909       return SDValue();
7910
7911     if (Mask[i] < 4) {
7912       // V1 input out of place for insertion.
7913       V1DstIndex = i;
7914     } else {
7915       // V2 input for insertion.
7916       V2DstIndex = i;
7917     }
7918   }
7919
7920   // Don't bother if we have no (non-zeroable) element for insertion.
7921   if (V1DstIndex == -1 && V2DstIndex == -1)
7922     return SDValue();
7923
7924   // Determine element insertion src/dst indices. The src index is from the
7925   // start of the inserted vector, not the start of the concatenated vector.
7926   unsigned V2SrcIndex = 0;
7927   if (V1DstIndex != -1) {
7928     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7929     // and don't use the original V2 at all.
7930     V2SrcIndex = Mask[V1DstIndex];
7931     V2DstIndex = V1DstIndex;
7932     V2 = V1;
7933   } else {
7934     V2SrcIndex = Mask[V2DstIndex] - 4;
7935   }
7936
7937   // If no V1 inputs are used in place, then the result is created only from
7938   // the zero mask and the V2 insertion - so remove V1 dependency.
7939   if (!V1UsedInPlace)
7940     V1 = DAG.getUNDEF(MVT::v4f32);
7941
7942   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7943   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7944
7945   // Insert the V2 element into the desired position.
7946   SDLoc DL(Op);
7947   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7948                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7949 }
7950
7951 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7952 /// UNPCK instruction.
7953 ///
7954 /// This specifically targets cases where we end up with alternating between
7955 /// the two inputs, and so can permute them into something that feeds a single
7956 /// UNPCK instruction. Note that this routine only targets integer vectors
7957 /// because for floating point vectors we have a generalized SHUFPS lowering
7958 /// strategy that handles everything that doesn't *exactly* match an unpack,
7959 /// making this clever lowering unnecessary.
7960 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
7961                                                     SDValue V1, SDValue V2,
7962                                                     ArrayRef<int> Mask,
7963                                                     SelectionDAG &DAG) {
7964   assert(!VT.isFloatingPoint() &&
7965          "This routine only supports integer vectors.");
7966   assert(!isSingleInputShuffleMask(Mask) &&
7967          "This routine should only be used when blending two inputs.");
7968   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7969
7970   int Size = Mask.size();
7971
7972   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7973     return M >= 0 && M % Size < Size / 2;
7974   });
7975   int NumHiInputs = std::count_if(
7976       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7977
7978   bool UnpackLo = NumLoInputs >= NumHiInputs;
7979
7980   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7981     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7982     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7983
7984     for (int i = 0; i < Size; ++i) {
7985       if (Mask[i] < 0)
7986         continue;
7987
7988       // Each element of the unpack contains Scale elements from this mask.
7989       int UnpackIdx = i / Scale;
7990
7991       // We only handle the case where V1 feeds the first slots of the unpack.
7992       // We rely on canonicalization to ensure this is the case.
7993       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7994         return SDValue();
7995
7996       // Setup the mask for this input. The indexing is tricky as we have to
7997       // handle the unpack stride.
7998       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7999       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8000           Mask[i] % Size;
8001     }
8002
8003     // If we will have to shuffle both inputs to use the unpack, check whether
8004     // we can just unpack first and shuffle the result. If so, skip this unpack.
8005     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8006         !isNoopShuffleMask(V2Mask))
8007       return SDValue();
8008
8009     // Shuffle the inputs into place.
8010     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8011     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8012
8013     // Cast the inputs to the type we will use to unpack them.
8014     V1 = DAG.getBitcast(UnpackVT, V1);
8015     V2 = DAG.getBitcast(UnpackVT, V2);
8016
8017     // Unpack the inputs and cast the result back to the desired type.
8018     return DAG.getBitcast(
8019         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8020                         UnpackVT, V1, V2));
8021   };
8022
8023   // We try each unpack from the largest to the smallest to try and find one
8024   // that fits this mask.
8025   int OrigNumElements = VT.getVectorNumElements();
8026   int OrigScalarSize = VT.getScalarSizeInBits();
8027   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8028     int Scale = ScalarSize / OrigScalarSize;
8029     int NumElements = OrigNumElements / Scale;
8030     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8031     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8032       return Unpack;
8033   }
8034
8035   // If none of the unpack-rooted lowerings worked (or were profitable) try an
8036   // initial unpack.
8037   if (NumLoInputs == 0 || NumHiInputs == 0) {
8038     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8039            "We have to have *some* inputs!");
8040     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8041
8042     // FIXME: We could consider the total complexity of the permute of each
8043     // possible unpacking. Or at the least we should consider how many
8044     // half-crossings are created.
8045     // FIXME: We could consider commuting the unpacks.
8046
8047     SmallVector<int, 32> PermMask;
8048     PermMask.assign(Size, -1);
8049     for (int i = 0; i < Size; ++i) {
8050       if (Mask[i] < 0)
8051         continue;
8052
8053       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8054
8055       PermMask[i] =
8056           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8057     }
8058     return DAG.getVectorShuffle(
8059         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8060                             DL, VT, V1, V2),
8061         DAG.getUNDEF(VT), PermMask);
8062   }
8063
8064   return SDValue();
8065 }
8066
8067 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8068 ///
8069 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8070 /// support for floating point shuffles but not integer shuffles. These
8071 /// instructions will incur a domain crossing penalty on some chips though so
8072 /// it is better to avoid lowering through this for integer vectors where
8073 /// possible.
8074 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8075                                        const X86Subtarget *Subtarget,
8076                                        SelectionDAG &DAG) {
8077   SDLoc DL(Op);
8078   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8079   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8080   assert(V2.getSimpleValueType() == MVT::v2f64 && "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     // Use low duplicate instructions for masks that match their pattern.
8087     if (Subtarget->hasSSE3())
8088       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8089         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8090
8091     // Straight shuffle of a single input vector. Simulate this by using the
8092     // single input as both of the "inputs" to this instruction..
8093     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8094
8095     if (Subtarget->hasAVX()) {
8096       // If we have AVX, we can use VPERMILPS which will allow folding a load
8097       // into the shuffle.
8098       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8099                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8100     }
8101
8102     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8103                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8104   }
8105   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8106   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8107
8108   // If we have a single input, insert that into V1 if we can do so cheaply.
8109   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8110     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8111             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8112       return Insertion;
8113     // Try inverting the insertion since for v2 masks it is easy to do and we
8114     // can't reliably sort the mask one way or the other.
8115     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8116                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8117     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8118             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8119       return Insertion;
8120   }
8121
8122   // Try to use one of the special instruction patterns to handle two common
8123   // blend patterns if a zero-blend above didn't work.
8124   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8125       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8126     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8127       // We can either use a special instruction to load over the low double or
8128       // to move just the low double.
8129       return DAG.getNode(
8130           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8131           DL, MVT::v2f64, V2,
8132           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8133
8134   if (Subtarget->hasSSE41())
8135     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8136                                                   Subtarget, DAG))
8137       return Blend;
8138
8139   // Use dedicated unpack instructions for masks that match their pattern.
8140   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8141     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
8142   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8143     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
8144
8145   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8146   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8147                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8148 }
8149
8150 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8151 ///
8152 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8153 /// the integer unit to minimize domain crossing penalties. However, for blends
8154 /// it falls back to the floating point shuffle operation with appropriate bit
8155 /// casting.
8156 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8157                                        const X86Subtarget *Subtarget,
8158                                        SelectionDAG &DAG) {
8159   SDLoc DL(Op);
8160   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8161   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8162   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8163   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8164   ArrayRef<int> Mask = SVOp->getMask();
8165   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8166
8167   if (isSingleInputShuffleMask(Mask)) {
8168     // Check for being able to broadcast a single element.
8169     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8170                                                           Mask, Subtarget, DAG))
8171       return Broadcast;
8172
8173     // Straight shuffle of a single input vector. For everything from SSE2
8174     // onward this has a single fast instruction with no scary immediates.
8175     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8176     V1 = DAG.getBitcast(MVT::v4i32, V1);
8177     int WidenedMask[4] = {
8178         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8179         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8180     return DAG.getBitcast(
8181         MVT::v2i64,
8182         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8183                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8184   }
8185   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8186   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8187   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8188   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8189
8190   // If we have a blend of two PACKUS operations an the blend aligns with the
8191   // low and half halves, we can just merge the PACKUS operations. This is
8192   // particularly important as it lets us merge shuffles that this routine itself
8193   // creates.
8194   auto GetPackNode = [](SDValue V) {
8195     while (V.getOpcode() == ISD::BITCAST)
8196       V = V.getOperand(0);
8197
8198     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8199   };
8200   if (SDValue V1Pack = GetPackNode(V1))
8201     if (SDValue V2Pack = GetPackNode(V2))
8202       return DAG.getBitcast(MVT::v2i64,
8203                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8204                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8205                                                      : V1Pack.getOperand(1),
8206                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8207                                                      : V2Pack.getOperand(1)));
8208
8209   // Try to use shift instructions.
8210   if (SDValue Shift =
8211           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8212     return Shift;
8213
8214   // When loading a scalar and then shuffling it into a vector we can often do
8215   // the insertion cheaply.
8216   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8217           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8218     return Insertion;
8219   // Try inverting the insertion since for v2 masks it is easy to do and we
8220   // can't reliably sort the mask one way or the other.
8221   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8222   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8223           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8224     return Insertion;
8225
8226   // We have different paths for blend lowering, but they all must use the
8227   // *exact* same predicate.
8228   bool IsBlendSupported = Subtarget->hasSSE41();
8229   if (IsBlendSupported)
8230     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8231                                                   Subtarget, DAG))
8232       return Blend;
8233
8234   // Use dedicated unpack instructions for masks that match their pattern.
8235   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8236     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8237   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8238     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8239
8240   // Try to use byte rotation instructions.
8241   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8242   if (Subtarget->hasSSSE3())
8243     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8244             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8245       return Rotate;
8246
8247   // If we have direct support for blends, we should lower by decomposing into
8248   // a permute. That will be faster than the domain cross.
8249   if (IsBlendSupported)
8250     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8251                                                       Mask, DAG);
8252
8253   // We implement this with SHUFPD which is pretty lame because it will likely
8254   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8255   // However, all the alternatives are still more cycles and newer chips don't
8256   // have this problem. It would be really nice if x86 had better shuffles here.
8257   V1 = DAG.getBitcast(MVT::v2f64, V1);
8258   V2 = DAG.getBitcast(MVT::v2f64, V2);
8259   return DAG.getBitcast(MVT::v2i64,
8260                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8261 }
8262
8263 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8264 ///
8265 /// This is used to disable more specialized lowerings when the shufps lowering
8266 /// will happen to be efficient.
8267 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8268   // This routine only handles 128-bit shufps.
8269   assert(Mask.size() == 4 && "Unsupported mask size!");
8270
8271   // To lower with a single SHUFPS we need to have the low half and high half
8272   // each requiring a single input.
8273   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8274     return false;
8275   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8276     return false;
8277
8278   return true;
8279 }
8280
8281 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8282 ///
8283 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8284 /// It makes no assumptions about whether this is the *best* lowering, it simply
8285 /// uses it.
8286 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8287                                             ArrayRef<int> Mask, SDValue V1,
8288                                             SDValue V2, SelectionDAG &DAG) {
8289   SDValue LowV = V1, HighV = V2;
8290   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8291
8292   int NumV2Elements =
8293       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8294
8295   if (NumV2Elements == 1) {
8296     int V2Index =
8297         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8298         Mask.begin();
8299
8300     // Compute the index adjacent to V2Index and in the same half by toggling
8301     // the low bit.
8302     int V2AdjIndex = V2Index ^ 1;
8303
8304     if (Mask[V2AdjIndex] == -1) {
8305       // Handles all the cases where we have a single V2 element and an undef.
8306       // This will only ever happen in the high lanes because we commute the
8307       // vector otherwise.
8308       if (V2Index < 2)
8309         std::swap(LowV, HighV);
8310       NewMask[V2Index] -= 4;
8311     } else {
8312       // Handle the case where the V2 element ends up adjacent to a V1 element.
8313       // To make this work, blend them together as the first step.
8314       int V1Index = V2AdjIndex;
8315       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8316       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8317                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8318
8319       // Now proceed to reconstruct the final blend as we have the necessary
8320       // high or low half formed.
8321       if (V2Index < 2) {
8322         LowV = V2;
8323         HighV = V1;
8324       } else {
8325         HighV = V2;
8326       }
8327       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8328       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8329     }
8330   } else if (NumV2Elements == 2) {
8331     if (Mask[0] < 4 && Mask[1] < 4) {
8332       // Handle the easy case where we have V1 in the low lanes and V2 in the
8333       // high lanes.
8334       NewMask[2] -= 4;
8335       NewMask[3] -= 4;
8336     } else if (Mask[2] < 4 && Mask[3] < 4) {
8337       // We also handle the reversed case because this utility may get called
8338       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8339       // arrange things in the right direction.
8340       NewMask[0] -= 4;
8341       NewMask[1] -= 4;
8342       HighV = V1;
8343       LowV = V2;
8344     } else {
8345       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8346       // trying to place elements directly, just blend them and set up the final
8347       // shuffle to place them.
8348
8349       // The first two blend mask elements are for V1, the second two are for
8350       // V2.
8351       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8352                           Mask[2] < 4 ? Mask[2] : Mask[3],
8353                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8354                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8355       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8356                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8357
8358       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8359       // a blend.
8360       LowV = HighV = V1;
8361       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8362       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8363       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8364       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8365     }
8366   }
8367   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8368                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8369 }
8370
8371 /// \brief Lower 4-lane 32-bit floating point shuffles.
8372 ///
8373 /// Uses instructions exclusively from the floating point unit to minimize
8374 /// domain crossing penalties, as these are sufficient to implement all v4f32
8375 /// shuffles.
8376 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8377                                        const X86Subtarget *Subtarget,
8378                                        SelectionDAG &DAG) {
8379   SDLoc DL(Op);
8380   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8381   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8382   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8383   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8384   ArrayRef<int> Mask = SVOp->getMask();
8385   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8386
8387   int NumV2Elements =
8388       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8389
8390   if (NumV2Elements == 0) {
8391     // Check for being able to broadcast a single element.
8392     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8393                                                           Mask, Subtarget, DAG))
8394       return Broadcast;
8395
8396     // Use even/odd duplicate instructions for masks that match their pattern.
8397     if (Subtarget->hasSSE3()) {
8398       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8399         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8400       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8401         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8402     }
8403
8404     if (Subtarget->hasAVX()) {
8405       // If we have AVX, we can use VPERMILPS which will allow folding a load
8406       // into the shuffle.
8407       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8408                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8409     }
8410
8411     // Otherwise, use a straight shuffle of a single input vector. We pass the
8412     // input vector to both operands to simulate this with a SHUFPS.
8413     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8414                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8415   }
8416
8417   // There are special ways we can lower some single-element blends. However, we
8418   // have custom ways we can lower more complex single-element blends below that
8419   // we defer to if both this and BLENDPS fail to match, so restrict this to
8420   // when the V2 input is targeting element 0 of the mask -- that is the fast
8421   // case here.
8422   if (NumV2Elements == 1 && Mask[0] >= 4)
8423     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8424                                                          Mask, Subtarget, DAG))
8425       return V;
8426
8427   if (Subtarget->hasSSE41()) {
8428     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8429                                                   Subtarget, DAG))
8430       return Blend;
8431
8432     // Use INSERTPS if we can complete the shuffle efficiently.
8433     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8434       return V;
8435
8436     if (!isSingleSHUFPSMask(Mask))
8437       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8438               DL, MVT::v4f32, V1, V2, Mask, DAG))
8439         return BlendPerm;
8440   }
8441
8442   // Use dedicated unpack instructions for masks that match their pattern.
8443   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8444     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8445   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8446     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8447   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8448     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8449   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8450     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8451
8452   // Otherwise fall back to a SHUFPS lowering strategy.
8453   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8454 }
8455
8456 /// \brief Lower 4-lane i32 vector shuffles.
8457 ///
8458 /// We try to handle these with integer-domain shuffles where we can, but for
8459 /// blends we use the floating point domain blend instructions.
8460 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8461                                        const X86Subtarget *Subtarget,
8462                                        SelectionDAG &DAG) {
8463   SDLoc DL(Op);
8464   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8465   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8466   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8467   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8468   ArrayRef<int> Mask = SVOp->getMask();
8469   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8470
8471   // Whenever we can lower this as a zext, that instruction is strictly faster
8472   // than any alternative. It also allows us to fold memory operands into the
8473   // shuffle in many cases.
8474   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8475                                                          Mask, Subtarget, DAG))
8476     return ZExt;
8477
8478   int NumV2Elements =
8479       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8480
8481   if (NumV2Elements == 0) {
8482     // Check for being able to broadcast a single element.
8483     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8484                                                           Mask, Subtarget, DAG))
8485       return Broadcast;
8486
8487     // Straight shuffle of a single input vector. For everything from SSE2
8488     // onward this has a single fast instruction with no scary immediates.
8489     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8490     // but we aren't actually going to use the UNPCK instruction because doing
8491     // so prevents folding a load into this instruction or making a copy.
8492     const int UnpackLoMask[] = {0, 0, 1, 1};
8493     const int UnpackHiMask[] = {2, 2, 3, 3};
8494     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8495       Mask = UnpackLoMask;
8496     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8497       Mask = UnpackHiMask;
8498
8499     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8500                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8501   }
8502
8503   // Try to use shift instructions.
8504   if (SDValue Shift =
8505           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8506     return Shift;
8507
8508   // There are special ways we can lower some single-element blends.
8509   if (NumV2Elements == 1)
8510     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8511                                                          Mask, Subtarget, DAG))
8512       return V;
8513
8514   // We have different paths for blend lowering, but they all must use the
8515   // *exact* same predicate.
8516   bool IsBlendSupported = Subtarget->hasSSE41();
8517   if (IsBlendSupported)
8518     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8519                                                   Subtarget, DAG))
8520       return Blend;
8521
8522   if (SDValue Masked =
8523           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8524     return Masked;
8525
8526   // Use dedicated unpack instructions for masks that match their pattern.
8527   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8528     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8529   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8530     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8531   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8532     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8533   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8534     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8535
8536   // Try to use byte rotation instructions.
8537   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8538   if (Subtarget->hasSSSE3())
8539     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8540             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8541       return Rotate;
8542
8543   // If we have direct support for blends, we should lower by decomposing into
8544   // a permute. That will be faster than the domain cross.
8545   if (IsBlendSupported)
8546     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8547                                                       Mask, DAG);
8548
8549   // Try to lower by permuting the inputs into an unpack instruction.
8550   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8551                                                             V2, Mask, DAG))
8552     return Unpack;
8553
8554   // We implement this with SHUFPS because it can blend from two vectors.
8555   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8556   // up the inputs, bypassing domain shift penalties that we would encur if we
8557   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8558   // relevant.
8559   return DAG.getBitcast(
8560       MVT::v4i32,
8561       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8562                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8563 }
8564
8565 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8566 /// shuffle lowering, and the most complex part.
8567 ///
8568 /// The lowering strategy is to try to form pairs of input lanes which are
8569 /// targeted at the same half of the final vector, and then use a dword shuffle
8570 /// to place them onto the right half, and finally unpack the paired lanes into
8571 /// their final position.
8572 ///
8573 /// The exact breakdown of how to form these dword pairs and align them on the
8574 /// correct sides is really tricky. See the comments within the function for
8575 /// more of the details.
8576 ///
8577 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8578 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8579 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8580 /// vector, form the analogous 128-bit 8-element Mask.
8581 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8582     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8583     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8584   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8585   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8586
8587   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8588   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8589   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8590
8591   SmallVector<int, 4> LoInputs;
8592   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8593                [](int M) { return M >= 0; });
8594   std::sort(LoInputs.begin(), LoInputs.end());
8595   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8596   SmallVector<int, 4> HiInputs;
8597   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8598                [](int M) { return M >= 0; });
8599   std::sort(HiInputs.begin(), HiInputs.end());
8600   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8601   int NumLToL =
8602       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8603   int NumHToL = LoInputs.size() - NumLToL;
8604   int NumLToH =
8605       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8606   int NumHToH = HiInputs.size() - NumLToH;
8607   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8608   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8609   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8610   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8611
8612   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8613   // such inputs we can swap two of the dwords across the half mark and end up
8614   // with <=2 inputs to each half in each half. Once there, we can fall through
8615   // to the generic code below. For example:
8616   //
8617   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8618   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8619   //
8620   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8621   // and an existing 2-into-2 on the other half. In this case we may have to
8622   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8623   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8624   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8625   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8626   // half than the one we target for fixing) will be fixed when we re-enter this
8627   // path. We will also combine away any sequence of PSHUFD instructions that
8628   // result into a single instruction. Here is an example of the tricky case:
8629   //
8630   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8631   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8632   //
8633   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8634   //
8635   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8636   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8637   //
8638   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8639   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8640   //
8641   // The result is fine to be handled by the generic logic.
8642   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8643                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8644                           int AOffset, int BOffset) {
8645     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8646            "Must call this with A having 3 or 1 inputs from the A half.");
8647     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8648            "Must call this with B having 1 or 3 inputs from the B half.");
8649     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8650            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8651
8652     bool ThreeAInputs = AToAInputs.size() == 3;
8653
8654     // Compute the index of dword with only one word among the three inputs in
8655     // a half by taking the sum of the half with three inputs and subtracting
8656     // the sum of the actual three inputs. The difference is the remaining
8657     // slot.
8658     int ADWord, BDWord;
8659     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8660     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8661     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8662     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8663     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8664     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8665     int TripleNonInputIdx =
8666         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8667     TripleDWord = TripleNonInputIdx / 2;
8668
8669     // We use xor with one to compute the adjacent DWord to whichever one the
8670     // OneInput is in.
8671     OneInputDWord = (OneInput / 2) ^ 1;
8672
8673     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8674     // and BToA inputs. If there is also such a problem with the BToB and AToB
8675     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8676     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8677     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8678     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8679       // Compute how many inputs will be flipped by swapping these DWords. We
8680       // need
8681       // to balance this to ensure we don't form a 3-1 shuffle in the other
8682       // half.
8683       int NumFlippedAToBInputs =
8684           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8685           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8686       int NumFlippedBToBInputs =
8687           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8688           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8689       if ((NumFlippedAToBInputs == 1 &&
8690            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8691           (NumFlippedBToBInputs == 1 &&
8692            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8693         // We choose whether to fix the A half or B half based on whether that
8694         // half has zero flipped inputs. At zero, we may not be able to fix it
8695         // with that half. We also bias towards fixing the B half because that
8696         // will more commonly be the high half, and we have to bias one way.
8697         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8698                                                        ArrayRef<int> Inputs) {
8699           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8700           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8701                                          PinnedIdx ^ 1) != Inputs.end();
8702           // Determine whether the free index is in the flipped dword or the
8703           // unflipped dword based on where the pinned index is. We use this bit
8704           // in an xor to conditionally select the adjacent dword.
8705           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8706           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8707                                              FixFreeIdx) != Inputs.end();
8708           if (IsFixIdxInput == IsFixFreeIdxInput)
8709             FixFreeIdx += 1;
8710           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8711                                         FixFreeIdx) != Inputs.end();
8712           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8713                  "We need to be changing the number of flipped inputs!");
8714           int PSHUFHalfMask[] = {0, 1, 2, 3};
8715           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8716           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8717                           MVT::v8i16, V,
8718                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8719
8720           for (int &M : Mask)
8721             if (M != -1 && M == FixIdx)
8722               M = FixFreeIdx;
8723             else if (M != -1 && M == FixFreeIdx)
8724               M = FixIdx;
8725         };
8726         if (NumFlippedBToBInputs != 0) {
8727           int BPinnedIdx =
8728               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8729           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8730         } else {
8731           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8732           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8733           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8734         }
8735       }
8736     }
8737
8738     int PSHUFDMask[] = {0, 1, 2, 3};
8739     PSHUFDMask[ADWord] = BDWord;
8740     PSHUFDMask[BDWord] = ADWord;
8741     V = DAG.getBitcast(
8742         VT,
8743         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8744                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8745
8746     // Adjust the mask to match the new locations of A and B.
8747     for (int &M : Mask)
8748       if (M != -1 && M/2 == ADWord)
8749         M = 2 * BDWord + M % 2;
8750       else if (M != -1 && M/2 == BDWord)
8751         M = 2 * ADWord + M % 2;
8752
8753     // Recurse back into this routine to re-compute state now that this isn't
8754     // a 3 and 1 problem.
8755     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8756                                                      DAG);
8757   };
8758   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8759     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8760   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8761     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8762
8763   // At this point there are at most two inputs to the low and high halves from
8764   // each half. That means the inputs can always be grouped into dwords and
8765   // those dwords can then be moved to the correct half with a dword shuffle.
8766   // We use at most one low and one high word shuffle to collect these paired
8767   // inputs into dwords, and finally a dword shuffle to place them.
8768   int PSHUFLMask[4] = {-1, -1, -1, -1};
8769   int PSHUFHMask[4] = {-1, -1, -1, -1};
8770   int PSHUFDMask[4] = {-1, -1, -1, -1};
8771
8772   // First fix the masks for all the inputs that are staying in their
8773   // original halves. This will then dictate the targets of the cross-half
8774   // shuffles.
8775   auto fixInPlaceInputs =
8776       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8777                     MutableArrayRef<int> SourceHalfMask,
8778                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8779     if (InPlaceInputs.empty())
8780       return;
8781     if (InPlaceInputs.size() == 1) {
8782       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8783           InPlaceInputs[0] - HalfOffset;
8784       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8785       return;
8786     }
8787     if (IncomingInputs.empty()) {
8788       // Just fix all of the in place inputs.
8789       for (int Input : InPlaceInputs) {
8790         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8791         PSHUFDMask[Input / 2] = Input / 2;
8792       }
8793       return;
8794     }
8795
8796     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8797     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8798         InPlaceInputs[0] - HalfOffset;
8799     // Put the second input next to the first so that they are packed into
8800     // a dword. We find the adjacent index by toggling the low bit.
8801     int AdjIndex = InPlaceInputs[0] ^ 1;
8802     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8803     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8804     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8805   };
8806   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8807   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8808
8809   // Now gather the cross-half inputs and place them into a free dword of
8810   // their target half.
8811   // FIXME: This operation could almost certainly be simplified dramatically to
8812   // look more like the 3-1 fixing operation.
8813   auto moveInputsToRightHalf = [&PSHUFDMask](
8814       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8815       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8816       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8817       int DestOffset) {
8818     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8819       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8820     };
8821     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8822                                                int Word) {
8823       int LowWord = Word & ~1;
8824       int HighWord = Word | 1;
8825       return isWordClobbered(SourceHalfMask, LowWord) ||
8826              isWordClobbered(SourceHalfMask, HighWord);
8827     };
8828
8829     if (IncomingInputs.empty())
8830       return;
8831
8832     if (ExistingInputs.empty()) {
8833       // Map any dwords with inputs from them into the right half.
8834       for (int Input : IncomingInputs) {
8835         // If the source half mask maps over the inputs, turn those into
8836         // swaps and use the swapped lane.
8837         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8838           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8839             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8840                 Input - SourceOffset;
8841             // We have to swap the uses in our half mask in one sweep.
8842             for (int &M : HalfMask)
8843               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8844                 M = Input;
8845               else if (M == Input)
8846                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8847           } else {
8848             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8849                        Input - SourceOffset &&
8850                    "Previous placement doesn't match!");
8851           }
8852           // Note that this correctly re-maps both when we do a swap and when
8853           // we observe the other side of the swap above. We rely on that to
8854           // avoid swapping the members of the input list directly.
8855           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8856         }
8857
8858         // Map the input's dword into the correct half.
8859         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8860           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8861         else
8862           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8863                      Input / 2 &&
8864                  "Previous placement doesn't match!");
8865       }
8866
8867       // And just directly shift any other-half mask elements to be same-half
8868       // as we will have mirrored the dword containing the element into the
8869       // same position within that half.
8870       for (int &M : HalfMask)
8871         if (M >= SourceOffset && M < SourceOffset + 4) {
8872           M = M - SourceOffset + DestOffset;
8873           assert(M >= 0 && "This should never wrap below zero!");
8874         }
8875       return;
8876     }
8877
8878     // Ensure we have the input in a viable dword of its current half. This
8879     // is particularly tricky because the original position may be clobbered
8880     // by inputs being moved and *staying* in that half.
8881     if (IncomingInputs.size() == 1) {
8882       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8883         int InputFixed = std::find(std::begin(SourceHalfMask),
8884                                    std::end(SourceHalfMask), -1) -
8885                          std::begin(SourceHalfMask) + SourceOffset;
8886         SourceHalfMask[InputFixed - SourceOffset] =
8887             IncomingInputs[0] - SourceOffset;
8888         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8889                      InputFixed);
8890         IncomingInputs[0] = InputFixed;
8891       }
8892     } else if (IncomingInputs.size() == 2) {
8893       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8894           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8895         // We have two non-adjacent or clobbered inputs we need to extract from
8896         // the source half. To do this, we need to map them into some adjacent
8897         // dword slot in the source mask.
8898         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8899                               IncomingInputs[1] - SourceOffset};
8900
8901         // If there is a free slot in the source half mask adjacent to one of
8902         // the inputs, place the other input in it. We use (Index XOR 1) to
8903         // compute an adjacent index.
8904         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8905             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8906           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8907           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8908           InputsFixed[1] = InputsFixed[0] ^ 1;
8909         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8910                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8911           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8912           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8913           InputsFixed[0] = InputsFixed[1] ^ 1;
8914         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8915                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8916           // The two inputs are in the same DWord but it is clobbered and the
8917           // adjacent DWord isn't used at all. Move both inputs to the free
8918           // slot.
8919           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8920           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8921           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8922           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8923         } else {
8924           // The only way we hit this point is if there is no clobbering
8925           // (because there are no off-half inputs to this half) and there is no
8926           // free slot adjacent to one of the inputs. In this case, we have to
8927           // swap an input with a non-input.
8928           for (int i = 0; i < 4; ++i)
8929             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8930                    "We can't handle any clobbers here!");
8931           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8932                  "Cannot have adjacent inputs here!");
8933
8934           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8935           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8936
8937           // We also have to update the final source mask in this case because
8938           // it may need to undo the above swap.
8939           for (int &M : FinalSourceHalfMask)
8940             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8941               M = InputsFixed[1] + SourceOffset;
8942             else if (M == InputsFixed[1] + SourceOffset)
8943               M = (InputsFixed[0] ^ 1) + SourceOffset;
8944
8945           InputsFixed[1] = InputsFixed[0] ^ 1;
8946         }
8947
8948         // Point everything at the fixed inputs.
8949         for (int &M : HalfMask)
8950           if (M == IncomingInputs[0])
8951             M = InputsFixed[0] + SourceOffset;
8952           else if (M == IncomingInputs[1])
8953             M = InputsFixed[1] + SourceOffset;
8954
8955         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8956         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8957       }
8958     } else {
8959       llvm_unreachable("Unhandled input size!");
8960     }
8961
8962     // Now hoist the DWord down to the right half.
8963     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8964     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8965     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8966     for (int &M : HalfMask)
8967       for (int Input : IncomingInputs)
8968         if (M == Input)
8969           M = FreeDWord * 2 + Input % 2;
8970   };
8971   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8972                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8973   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8974                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8975
8976   // Now enact all the shuffles we've computed to move the inputs into their
8977   // target half.
8978   if (!isNoopShuffleMask(PSHUFLMask))
8979     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8980                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8981   if (!isNoopShuffleMask(PSHUFHMask))
8982     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8983                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8984   if (!isNoopShuffleMask(PSHUFDMask))
8985     V = DAG.getBitcast(
8986         VT,
8987         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8988                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8989
8990   // At this point, each half should contain all its inputs, and we can then
8991   // just shuffle them into their final position.
8992   assert(std::count_if(LoMask.begin(), LoMask.end(),
8993                        [](int M) { return M >= 4; }) == 0 &&
8994          "Failed to lift all the high half inputs to the low mask!");
8995   assert(std::count_if(HiMask.begin(), HiMask.end(),
8996                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8997          "Failed to lift all the low half inputs to the high mask!");
8998
8999   // Do a half shuffle for the low mask.
9000   if (!isNoopShuffleMask(LoMask))
9001     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9002                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9003
9004   // Do a half shuffle with the high mask after shifting its values down.
9005   for (int &M : HiMask)
9006     if (M >= 0)
9007       M -= 4;
9008   if (!isNoopShuffleMask(HiMask))
9009     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9010                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9011
9012   return V;
9013 }
9014
9015 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9016 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9017                                           SDValue V2, ArrayRef<int> Mask,
9018                                           SelectionDAG &DAG, bool &V1InUse,
9019                                           bool &V2InUse) {
9020   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9021   SDValue V1Mask[16];
9022   SDValue V2Mask[16];
9023   V1InUse = false;
9024   V2InUse = false;
9025
9026   int Size = Mask.size();
9027   int Scale = 16 / Size;
9028   for (int i = 0; i < 16; ++i) {
9029     if (Mask[i / Scale] == -1) {
9030       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9031     } else {
9032       const int ZeroMask = 0x80;
9033       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9034                                           : ZeroMask;
9035       int V2Idx = Mask[i / Scale] < Size
9036                       ? ZeroMask
9037                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
9038       if (Zeroable[i / Scale])
9039         V1Idx = V2Idx = ZeroMask;
9040       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9041       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9042       V1InUse |= (ZeroMask != V1Idx);
9043       V2InUse |= (ZeroMask != V2Idx);
9044     }
9045   }
9046
9047   if (V1InUse)
9048     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9049                      DAG.getBitcast(MVT::v16i8, V1),
9050                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9051   if (V2InUse)
9052     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9053                      DAG.getBitcast(MVT::v16i8, V2),
9054                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9055
9056   // If we need shuffled inputs from both, blend the two.
9057   SDValue V;
9058   if (V1InUse && V2InUse)
9059     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9060   else
9061     V = V1InUse ? V1 : V2;
9062
9063   // Cast the result back to the correct type.
9064   return DAG.getBitcast(VT, V);
9065 }
9066
9067 /// \brief Generic lowering of 8-lane i16 shuffles.
9068 ///
9069 /// This handles both single-input shuffles and combined shuffle/blends with
9070 /// two inputs. The single input shuffles are immediately delegated to
9071 /// a dedicated lowering routine.
9072 ///
9073 /// The blends are lowered in one of three fundamental ways. If there are few
9074 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9075 /// of the input is significantly cheaper when lowered as an interleaving of
9076 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9077 /// halves of the inputs separately (making them have relatively few inputs)
9078 /// and then concatenate them.
9079 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9080                                        const X86Subtarget *Subtarget,
9081                                        SelectionDAG &DAG) {
9082   SDLoc DL(Op);
9083   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9084   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9085   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9086   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9087   ArrayRef<int> OrigMask = SVOp->getMask();
9088   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9089                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9090   MutableArrayRef<int> Mask(MaskStorage);
9091
9092   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9093
9094   // Whenever we can lower this as a zext, that instruction is strictly faster
9095   // than any alternative.
9096   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9097           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9098     return ZExt;
9099
9100   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9101   (void)isV1;
9102   auto isV2 = [](int M) { return M >= 8; };
9103
9104   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9105
9106   if (NumV2Inputs == 0) {
9107     // Check for being able to broadcast a single element.
9108     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9109                                                           Mask, Subtarget, DAG))
9110       return Broadcast;
9111
9112     // Try to use shift instructions.
9113     if (SDValue Shift =
9114             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9115       return Shift;
9116
9117     // Use dedicated unpack instructions for masks that match their pattern.
9118     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
9119       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
9120     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
9121       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
9122
9123     // Try to use byte rotation instructions.
9124     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9125                                                         Mask, Subtarget, DAG))
9126       return Rotate;
9127
9128     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9129                                                      Subtarget, DAG);
9130   }
9131
9132   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9133          "All single-input shuffles should be canonicalized to be V1-input "
9134          "shuffles.");
9135
9136   // Try to use shift instructions.
9137   if (SDValue Shift =
9138           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9139     return Shift;
9140
9141   // See if we can use SSE4A Extraction / Insertion.
9142   if (Subtarget->hasSSE4A())
9143     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9144       return V;
9145
9146   // There are special ways we can lower some single-element blends.
9147   if (NumV2Inputs == 1)
9148     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9149                                                          Mask, Subtarget, DAG))
9150       return V;
9151
9152   // We have different paths for blend lowering, but they all must use the
9153   // *exact* same predicate.
9154   bool IsBlendSupported = Subtarget->hasSSE41();
9155   if (IsBlendSupported)
9156     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9157                                                   Subtarget, DAG))
9158       return Blend;
9159
9160   if (SDValue Masked =
9161           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9162     return Masked;
9163
9164   // Use dedicated unpack instructions for masks that match their pattern.
9165   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
9166     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9167   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
9168     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9169
9170   // Try to use byte rotation instructions.
9171   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9172           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9173     return Rotate;
9174
9175   if (SDValue BitBlend =
9176           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9177     return BitBlend;
9178
9179   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9180                                                             V2, Mask, DAG))
9181     return Unpack;
9182
9183   // If we can't directly blend but can use PSHUFB, that will be better as it
9184   // can both shuffle and set up the inefficient blend.
9185   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9186     bool V1InUse, V2InUse;
9187     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9188                                       V1InUse, V2InUse);
9189   }
9190
9191   // We can always bit-blend if we have to so the fallback strategy is to
9192   // decompose into single-input permutes and blends.
9193   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9194                                                       Mask, DAG);
9195 }
9196
9197 /// \brief Check whether a compaction lowering can be done by dropping even
9198 /// elements and compute how many times even elements must be dropped.
9199 ///
9200 /// This handles shuffles which take every Nth element where N is a power of
9201 /// two. Example shuffle masks:
9202 ///
9203 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9204 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9205 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9206 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9207 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9208 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9209 ///
9210 /// Any of these lanes can of course be undef.
9211 ///
9212 /// This routine only supports N <= 3.
9213 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9214 /// for larger N.
9215 ///
9216 /// \returns N above, or the number of times even elements must be dropped if
9217 /// there is such a number. Otherwise returns zero.
9218 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9219   // Figure out whether we're looping over two inputs or just one.
9220   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9221
9222   // The modulus for the shuffle vector entries is based on whether this is
9223   // a single input or not.
9224   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9225   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9226          "We should only be called with masks with a power-of-2 size!");
9227
9228   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9229
9230   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9231   // and 2^3 simultaneously. This is because we may have ambiguity with
9232   // partially undef inputs.
9233   bool ViableForN[3] = {true, true, true};
9234
9235   for (int i = 0, e = Mask.size(); i < e; ++i) {
9236     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9237     // want.
9238     if (Mask[i] == -1)
9239       continue;
9240
9241     bool IsAnyViable = false;
9242     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9243       if (ViableForN[j]) {
9244         uint64_t N = j + 1;
9245
9246         // The shuffle mask must be equal to (i * 2^N) % M.
9247         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9248           IsAnyViable = true;
9249         else
9250           ViableForN[j] = false;
9251       }
9252     // Early exit if we exhaust the possible powers of two.
9253     if (!IsAnyViable)
9254       break;
9255   }
9256
9257   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9258     if (ViableForN[j])
9259       return j + 1;
9260
9261   // Return 0 as there is no viable power of two.
9262   return 0;
9263 }
9264
9265 /// \brief Generic lowering of v16i8 shuffles.
9266 ///
9267 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9268 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9269 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9270 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9271 /// back together.
9272 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9273                                        const X86Subtarget *Subtarget,
9274                                        SelectionDAG &DAG) {
9275   SDLoc DL(Op);
9276   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9277   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9278   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9279   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9280   ArrayRef<int> Mask = SVOp->getMask();
9281   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9282
9283   // Try to use shift instructions.
9284   if (SDValue Shift =
9285           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9286     return Shift;
9287
9288   // Try to use byte rotation instructions.
9289   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9290           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9291     return Rotate;
9292
9293   // Try to use a zext lowering.
9294   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9295           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9296     return ZExt;
9297
9298   // See if we can use SSE4A Extraction / Insertion.
9299   if (Subtarget->hasSSE4A())
9300     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9301       return V;
9302
9303   int NumV2Elements =
9304       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9305
9306   // For single-input shuffles, there are some nicer lowering tricks we can use.
9307   if (NumV2Elements == 0) {
9308     // Check for being able to broadcast a single element.
9309     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9310                                                           Mask, Subtarget, DAG))
9311       return Broadcast;
9312
9313     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9314     // Notably, this handles splat and partial-splat shuffles more efficiently.
9315     // However, it only makes sense if the pre-duplication shuffle simplifies
9316     // things significantly. Currently, this means we need to be able to
9317     // express the pre-duplication shuffle as an i16 shuffle.
9318     //
9319     // FIXME: We should check for other patterns which can be widened into an
9320     // i16 shuffle as well.
9321     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9322       for (int i = 0; i < 16; i += 2)
9323         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9324           return false;
9325
9326       return true;
9327     };
9328     auto tryToWidenViaDuplication = [&]() -> SDValue {
9329       if (!canWidenViaDuplication(Mask))
9330         return SDValue();
9331       SmallVector<int, 4> LoInputs;
9332       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9333                    [](int M) { return M >= 0 && M < 8; });
9334       std::sort(LoInputs.begin(), LoInputs.end());
9335       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9336                      LoInputs.end());
9337       SmallVector<int, 4> HiInputs;
9338       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9339                    [](int M) { return M >= 8; });
9340       std::sort(HiInputs.begin(), HiInputs.end());
9341       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9342                      HiInputs.end());
9343
9344       bool TargetLo = LoInputs.size() >= HiInputs.size();
9345       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9346       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9347
9348       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9349       SmallDenseMap<int, int, 8> LaneMap;
9350       for (int I : InPlaceInputs) {
9351         PreDupI16Shuffle[I/2] = I/2;
9352         LaneMap[I] = I;
9353       }
9354       int j = TargetLo ? 0 : 4, je = j + 4;
9355       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9356         // Check if j is already a shuffle of this input. This happens when
9357         // there are two adjacent bytes after we move the low one.
9358         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9359           // If we haven't yet mapped the input, search for a slot into which
9360           // we can map it.
9361           while (j < je && PreDupI16Shuffle[j] != -1)
9362             ++j;
9363
9364           if (j == je)
9365             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9366             return SDValue();
9367
9368           // Map this input with the i16 shuffle.
9369           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9370         }
9371
9372         // Update the lane map based on the mapping we ended up with.
9373         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9374       }
9375       V1 = DAG.getBitcast(
9376           MVT::v16i8,
9377           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9378                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9379
9380       // Unpack the bytes to form the i16s that will be shuffled into place.
9381       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9382                        MVT::v16i8, V1, V1);
9383
9384       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9385       for (int i = 0; i < 16; ++i)
9386         if (Mask[i] != -1) {
9387           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9388           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9389           if (PostDupI16Shuffle[i / 2] == -1)
9390             PostDupI16Shuffle[i / 2] = MappedMask;
9391           else
9392             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9393                    "Conflicting entrties in the original shuffle!");
9394         }
9395       return DAG.getBitcast(
9396           MVT::v16i8,
9397           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9398                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9399     };
9400     if (SDValue V = tryToWidenViaDuplication())
9401       return V;
9402   }
9403
9404   if (SDValue Masked =
9405           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9406     return Masked;
9407
9408   // Use dedicated unpack instructions for masks that match their pattern.
9409   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9410                                          0, 16, 1, 17, 2, 18, 3, 19,
9411                                          // High half.
9412                                          4, 20, 5, 21, 6, 22, 7, 23}))
9413     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9414   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9415                                          8, 24, 9, 25, 10, 26, 11, 27,
9416                                          // High half.
9417                                          12, 28, 13, 29, 14, 30, 15, 31}))
9418     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9419
9420   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9421   // with PSHUFB. It is important to do this before we attempt to generate any
9422   // blends but after all of the single-input lowerings. If the single input
9423   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9424   // want to preserve that and we can DAG combine any longer sequences into
9425   // a PSHUFB in the end. But once we start blending from multiple inputs,
9426   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9427   // and there are *very* few patterns that would actually be faster than the
9428   // PSHUFB approach because of its ability to zero lanes.
9429   //
9430   // FIXME: The only exceptions to the above are blends which are exact
9431   // interleavings with direct instructions supporting them. We currently don't
9432   // handle those well here.
9433   if (Subtarget->hasSSSE3()) {
9434     bool V1InUse = false;
9435     bool V2InUse = false;
9436
9437     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9438                                                 DAG, V1InUse, V2InUse);
9439
9440     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9441     // do so. This avoids using them to handle blends-with-zero which is
9442     // important as a single pshufb is significantly faster for that.
9443     if (V1InUse && V2InUse) {
9444       if (Subtarget->hasSSE41())
9445         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9446                                                       Mask, Subtarget, DAG))
9447           return Blend;
9448
9449       // We can use an unpack to do the blending rather than an or in some
9450       // cases. Even though the or may be (very minorly) more efficient, we
9451       // preference this lowering because there are common cases where part of
9452       // the complexity of the shuffles goes away when we do the final blend as
9453       // an unpack.
9454       // FIXME: It might be worth trying to detect if the unpack-feeding
9455       // shuffles will both be pshufb, in which case we shouldn't bother with
9456       // this.
9457       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9458               DL, MVT::v16i8, V1, V2, Mask, DAG))
9459         return Unpack;
9460     }
9461
9462     return PSHUFB;
9463   }
9464
9465   // There are special ways we can lower some single-element blends.
9466   if (NumV2Elements == 1)
9467     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9468                                                          Mask, Subtarget, DAG))
9469       return V;
9470
9471   if (SDValue BitBlend =
9472           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9473     return BitBlend;
9474
9475   // Check whether a compaction lowering can be done. This handles shuffles
9476   // which take every Nth element for some even N. See the helper function for
9477   // details.
9478   //
9479   // We special case these as they can be particularly efficiently handled with
9480   // the PACKUSB instruction on x86 and they show up in common patterns of
9481   // rearranging bytes to truncate wide elements.
9482   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9483     // NumEvenDrops is the power of two stride of the elements. Another way of
9484     // thinking about it is that we need to drop the even elements this many
9485     // times to get the original input.
9486     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9487
9488     // First we need to zero all the dropped bytes.
9489     assert(NumEvenDrops <= 3 &&
9490            "No support for dropping even elements more than 3 times.");
9491     // We use the mask type to pick which bytes are preserved based on how many
9492     // elements are dropped.
9493     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9494     SDValue ByteClearMask = DAG.getBitcast(
9495         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9496     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9497     if (!IsSingleInput)
9498       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9499
9500     // Now pack things back together.
9501     V1 = DAG.getBitcast(MVT::v8i16, V1);
9502     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9503     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9504     for (int i = 1; i < NumEvenDrops; ++i) {
9505       Result = DAG.getBitcast(MVT::v8i16, Result);
9506       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9507     }
9508
9509     return Result;
9510   }
9511
9512   // Handle multi-input cases by blending single-input shuffles.
9513   if (NumV2Elements > 0)
9514     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9515                                                       Mask, DAG);
9516
9517   // The fallback path for single-input shuffles widens this into two v8i16
9518   // vectors with unpacks, shuffles those, and then pulls them back together
9519   // with a pack.
9520   SDValue V = V1;
9521
9522   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9523   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9524   for (int i = 0; i < 16; ++i)
9525     if (Mask[i] >= 0)
9526       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9527
9528   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9529
9530   SDValue VLoHalf, VHiHalf;
9531   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9532   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9533   // i16s.
9534   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9535                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9536       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9537                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9538     // Use a mask to drop the high bytes.
9539     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9540     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9541                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9542
9543     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9544     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9545
9546     // Squash the masks to point directly into VLoHalf.
9547     for (int &M : LoBlendMask)
9548       if (M >= 0)
9549         M /= 2;
9550     for (int &M : HiBlendMask)
9551       if (M >= 0)
9552         M /= 2;
9553   } else {
9554     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9555     // VHiHalf so that we can blend them as i16s.
9556     VLoHalf = DAG.getBitcast(
9557         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9558     VHiHalf = DAG.getBitcast(
9559         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9560   }
9561
9562   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9563   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9564
9565   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9566 }
9567
9568 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9569 ///
9570 /// This routine breaks down the specific type of 128-bit shuffle and
9571 /// dispatches to the lowering routines accordingly.
9572 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9573                                         MVT VT, const X86Subtarget *Subtarget,
9574                                         SelectionDAG &DAG) {
9575   switch (VT.SimpleTy) {
9576   case MVT::v2i64:
9577     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9578   case MVT::v2f64:
9579     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9580   case MVT::v4i32:
9581     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9582   case MVT::v4f32:
9583     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9584   case MVT::v8i16:
9585     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9586   case MVT::v16i8:
9587     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9588
9589   default:
9590     llvm_unreachable("Unimplemented!");
9591   }
9592 }
9593
9594 /// \brief Helper function to test whether a shuffle mask could be
9595 /// simplified by widening the elements being shuffled.
9596 ///
9597 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9598 /// leaves it in an unspecified state.
9599 ///
9600 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9601 /// shuffle masks. The latter have the special property of a '-2' representing
9602 /// a zero-ed lane of a vector.
9603 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9604                                     SmallVectorImpl<int> &WidenedMask) {
9605   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9606     // If both elements are undef, its trivial.
9607     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9608       WidenedMask.push_back(SM_SentinelUndef);
9609       continue;
9610     }
9611
9612     // Check for an undef mask and a mask value properly aligned to fit with
9613     // a pair of values. If we find such a case, use the non-undef mask's value.
9614     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9615       WidenedMask.push_back(Mask[i + 1] / 2);
9616       continue;
9617     }
9618     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9619       WidenedMask.push_back(Mask[i] / 2);
9620       continue;
9621     }
9622
9623     // When zeroing, we need to spread the zeroing across both lanes to widen.
9624     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9625       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9626           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9627         WidenedMask.push_back(SM_SentinelZero);
9628         continue;
9629       }
9630       return false;
9631     }
9632
9633     // Finally check if the two mask values are adjacent and aligned with
9634     // a pair.
9635     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9636       WidenedMask.push_back(Mask[i] / 2);
9637       continue;
9638     }
9639
9640     // Otherwise we can't safely widen the elements used in this shuffle.
9641     return false;
9642   }
9643   assert(WidenedMask.size() == Mask.size() / 2 &&
9644          "Incorrect size of mask after widening the elements!");
9645
9646   return true;
9647 }
9648
9649 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9650 ///
9651 /// This routine just extracts two subvectors, shuffles them independently, and
9652 /// then concatenates them back together. This should work effectively with all
9653 /// AVX vector shuffle types.
9654 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9655                                           SDValue V2, ArrayRef<int> Mask,
9656                                           SelectionDAG &DAG) {
9657   assert(VT.getSizeInBits() >= 256 &&
9658          "Only for 256-bit or wider vector shuffles!");
9659   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9660   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9661
9662   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9663   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9664
9665   int NumElements = VT.getVectorNumElements();
9666   int SplitNumElements = NumElements / 2;
9667   MVT ScalarVT = VT.getScalarType();
9668   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9669
9670   // Rather than splitting build-vectors, just build two narrower build
9671   // vectors. This helps shuffling with splats and zeros.
9672   auto SplitVector = [&](SDValue V) {
9673     while (V.getOpcode() == ISD::BITCAST)
9674       V = V->getOperand(0);
9675
9676     MVT OrigVT = V.getSimpleValueType();
9677     int OrigNumElements = OrigVT.getVectorNumElements();
9678     int OrigSplitNumElements = OrigNumElements / 2;
9679     MVT OrigScalarVT = OrigVT.getScalarType();
9680     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9681
9682     SDValue LoV, HiV;
9683
9684     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9685     if (!BV) {
9686       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9687                         DAG.getIntPtrConstant(0, DL));
9688       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9689                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9690     } else {
9691
9692       SmallVector<SDValue, 16> LoOps, HiOps;
9693       for (int i = 0; i < OrigSplitNumElements; ++i) {
9694         LoOps.push_back(BV->getOperand(i));
9695         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9696       }
9697       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9698       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9699     }
9700     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9701                           DAG.getBitcast(SplitVT, HiV));
9702   };
9703
9704   SDValue LoV1, HiV1, LoV2, HiV2;
9705   std::tie(LoV1, HiV1) = SplitVector(V1);
9706   std::tie(LoV2, HiV2) = SplitVector(V2);
9707
9708   // Now create two 4-way blends of these half-width vectors.
9709   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9710     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9711     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9712     for (int i = 0; i < SplitNumElements; ++i) {
9713       int M = HalfMask[i];
9714       if (M >= NumElements) {
9715         if (M >= NumElements + SplitNumElements)
9716           UseHiV2 = true;
9717         else
9718           UseLoV2 = true;
9719         V2BlendMask.push_back(M - NumElements);
9720         V1BlendMask.push_back(-1);
9721         BlendMask.push_back(SplitNumElements + i);
9722       } else if (M >= 0) {
9723         if (M >= SplitNumElements)
9724           UseHiV1 = true;
9725         else
9726           UseLoV1 = true;
9727         V2BlendMask.push_back(-1);
9728         V1BlendMask.push_back(M);
9729         BlendMask.push_back(i);
9730       } else {
9731         V2BlendMask.push_back(-1);
9732         V1BlendMask.push_back(-1);
9733         BlendMask.push_back(-1);
9734       }
9735     }
9736
9737     // Because the lowering happens after all combining takes place, we need to
9738     // manually combine these blend masks as much as possible so that we create
9739     // a minimal number of high-level vector shuffle nodes.
9740
9741     // First try just blending the halves of V1 or V2.
9742     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9743       return DAG.getUNDEF(SplitVT);
9744     if (!UseLoV2 && !UseHiV2)
9745       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9746     if (!UseLoV1 && !UseHiV1)
9747       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9748
9749     SDValue V1Blend, V2Blend;
9750     if (UseLoV1 && UseHiV1) {
9751       V1Blend =
9752         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9753     } else {
9754       // We only use half of V1 so map the usage down into the final blend mask.
9755       V1Blend = UseLoV1 ? LoV1 : HiV1;
9756       for (int i = 0; i < SplitNumElements; ++i)
9757         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9758           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9759     }
9760     if (UseLoV2 && UseHiV2) {
9761       V2Blend =
9762         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9763     } else {
9764       // We only use half of V2 so map the usage down into the final blend mask.
9765       V2Blend = UseLoV2 ? LoV2 : HiV2;
9766       for (int i = 0; i < SplitNumElements; ++i)
9767         if (BlendMask[i] >= SplitNumElements)
9768           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9769     }
9770     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9771   };
9772   SDValue Lo = HalfBlend(LoMask);
9773   SDValue Hi = HalfBlend(HiMask);
9774   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9775 }
9776
9777 /// \brief Either split a vector in halves or decompose the shuffles and the
9778 /// blend.
9779 ///
9780 /// This is provided as a good fallback for many lowerings of non-single-input
9781 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9782 /// between splitting the shuffle into 128-bit components and stitching those
9783 /// back together vs. extracting the single-input shuffles and blending those
9784 /// results.
9785 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9786                                                 SDValue V2, ArrayRef<int> Mask,
9787                                                 SelectionDAG &DAG) {
9788   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9789                                             "lower single-input shuffles as it "
9790                                             "could then recurse on itself.");
9791   int Size = Mask.size();
9792
9793   // If this can be modeled as a broadcast of two elements followed by a blend,
9794   // prefer that lowering. This is especially important because broadcasts can
9795   // often fold with memory operands.
9796   auto DoBothBroadcast = [&] {
9797     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9798     for (int M : Mask)
9799       if (M >= Size) {
9800         if (V2BroadcastIdx == -1)
9801           V2BroadcastIdx = M - Size;
9802         else if (M - Size != V2BroadcastIdx)
9803           return false;
9804       } else if (M >= 0) {
9805         if (V1BroadcastIdx == -1)
9806           V1BroadcastIdx = M;
9807         else if (M != V1BroadcastIdx)
9808           return false;
9809       }
9810     return true;
9811   };
9812   if (DoBothBroadcast())
9813     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9814                                                       DAG);
9815
9816   // If the inputs all stem from a single 128-bit lane of each input, then we
9817   // split them rather than blending because the split will decompose to
9818   // unusually few instructions.
9819   int LaneCount = VT.getSizeInBits() / 128;
9820   int LaneSize = Size / LaneCount;
9821   SmallBitVector LaneInputs[2];
9822   LaneInputs[0].resize(LaneCount, false);
9823   LaneInputs[1].resize(LaneCount, false);
9824   for (int i = 0; i < Size; ++i)
9825     if (Mask[i] >= 0)
9826       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9827   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9828     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9829
9830   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9831   // that the decomposed single-input shuffles don't end up here.
9832   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9833 }
9834
9835 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9836 /// a permutation and blend of those lanes.
9837 ///
9838 /// This essentially blends the out-of-lane inputs to each lane into the lane
9839 /// from a permuted copy of the vector. This lowering strategy results in four
9840 /// instructions in the worst case for a single-input cross lane shuffle which
9841 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9842 /// of. Special cases for each particular shuffle pattern should be handled
9843 /// prior to trying this lowering.
9844 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9845                                                        SDValue V1, SDValue V2,
9846                                                        ArrayRef<int> Mask,
9847                                                        SelectionDAG &DAG) {
9848   // FIXME: This should probably be generalized for 512-bit vectors as well.
9849   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9850   int LaneSize = Mask.size() / 2;
9851
9852   // If there are only inputs from one 128-bit lane, splitting will in fact be
9853   // less expensive. The flags track whether the given lane contains an element
9854   // that crosses to another lane.
9855   bool LaneCrossing[2] = {false, false};
9856   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9857     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9858       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9859   if (!LaneCrossing[0] || !LaneCrossing[1])
9860     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9861
9862   if (isSingleInputShuffleMask(Mask)) {
9863     SmallVector<int, 32> FlippedBlendMask;
9864     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9865       FlippedBlendMask.push_back(
9866           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9867                                   ? Mask[i]
9868                                   : Mask[i] % LaneSize +
9869                                         (i / LaneSize) * LaneSize + Size));
9870
9871     // Flip the vector, and blend the results which should now be in-lane. The
9872     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9873     // 5 for the high source. The value 3 selects the high half of source 2 and
9874     // the value 2 selects the low half of source 2. We only use source 2 to
9875     // allow folding it into a memory operand.
9876     unsigned PERMMask = 3 | 2 << 4;
9877     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9878                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9879     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9880   }
9881
9882   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9883   // will be handled by the above logic and a blend of the results, much like
9884   // other patterns in AVX.
9885   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9886 }
9887
9888 /// \brief Handle lowering 2-lane 128-bit shuffles.
9889 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9890                                         SDValue V2, ArrayRef<int> Mask,
9891                                         const X86Subtarget *Subtarget,
9892                                         SelectionDAG &DAG) {
9893   // TODO: If minimizing size and one of the inputs is a zero vector and the
9894   // the zero vector has only one use, we could use a VPERM2X128 to save the
9895   // instruction bytes needed to explicitly generate the zero vector.
9896
9897   // Blends are faster and handle all the non-lane-crossing cases.
9898   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9899                                                 Subtarget, DAG))
9900     return Blend;
9901
9902   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9903   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9904
9905   // If either input operand is a zero vector, use VPERM2X128 because its mask
9906   // allows us to replace the zero input with an implicit zero.
9907   if (!IsV1Zero && !IsV2Zero) {
9908     // Check for patterns which can be matched with a single insert of a 128-bit
9909     // subvector.
9910     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9911     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9912       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9913                                    VT.getVectorNumElements() / 2);
9914       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9915                                 DAG.getIntPtrConstant(0, DL));
9916       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9917                                 OnlyUsesV1 ? V1 : V2,
9918                                 DAG.getIntPtrConstant(0, DL));
9919       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9920     }
9921   }
9922
9923   // Otherwise form a 128-bit permutation. After accounting for undefs,
9924   // convert the 64-bit shuffle mask selection values into 128-bit
9925   // selection bits by dividing the indexes by 2 and shifting into positions
9926   // defined by a vperm2*128 instruction's immediate control byte.
9927
9928   // The immediate permute control byte looks like this:
9929   //    [1:0] - select 128 bits from sources for low half of destination
9930   //    [2]   - ignore
9931   //    [3]   - zero low half of destination
9932   //    [5:4] - select 128 bits from sources for high half of destination
9933   //    [6]   - ignore
9934   //    [7]   - zero high half of destination
9935
9936   int MaskLO = Mask[0];
9937   if (MaskLO == SM_SentinelUndef)
9938     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9939
9940   int MaskHI = Mask[2];
9941   if (MaskHI == SM_SentinelUndef)
9942     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9943
9944   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9945
9946   // If either input is a zero vector, replace it with an undef input.
9947   // Shuffle mask values <  4 are selecting elements of V1.
9948   // Shuffle mask values >= 4 are selecting elements of V2.
9949   // Adjust each half of the permute mask by clearing the half that was
9950   // selecting the zero vector and setting the zero mask bit.
9951   if (IsV1Zero) {
9952     V1 = DAG.getUNDEF(VT);
9953     if (MaskLO < 4)
9954       PermMask = (PermMask & 0xf0) | 0x08;
9955     if (MaskHI < 4)
9956       PermMask = (PermMask & 0x0f) | 0x80;
9957   }
9958   if (IsV2Zero) {
9959     V2 = DAG.getUNDEF(VT);
9960     if (MaskLO >= 4)
9961       PermMask = (PermMask & 0xf0) | 0x08;
9962     if (MaskHI >= 4)
9963       PermMask = (PermMask & 0x0f) | 0x80;
9964   }
9965
9966   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9967                      DAG.getConstant(PermMask, DL, MVT::i8));
9968 }
9969
9970 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9971 /// shuffling each lane.
9972 ///
9973 /// This will only succeed when the result of fixing the 128-bit lanes results
9974 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9975 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9976 /// the lane crosses early and then use simpler shuffles within each lane.
9977 ///
9978 /// FIXME: It might be worthwhile at some point to support this without
9979 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9980 /// in x86 only floating point has interesting non-repeating shuffles, and even
9981 /// those are still *marginally* more expensive.
9982 static SDValue lowerVectorShuffleByMerging128BitLanes(
9983     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9984     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9985   assert(!isSingleInputShuffleMask(Mask) &&
9986          "This is only useful with multiple inputs.");
9987
9988   int Size = Mask.size();
9989   int LaneSize = 128 / VT.getScalarSizeInBits();
9990   int NumLanes = Size / LaneSize;
9991   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9992
9993   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9994   // check whether the in-128-bit lane shuffles share a repeating pattern.
9995   SmallVector<int, 4> Lanes;
9996   Lanes.resize(NumLanes, -1);
9997   SmallVector<int, 4> InLaneMask;
9998   InLaneMask.resize(LaneSize, -1);
9999   for (int i = 0; i < Size; ++i) {
10000     if (Mask[i] < 0)
10001       continue;
10002
10003     int j = i / LaneSize;
10004
10005     if (Lanes[j] < 0) {
10006       // First entry we've seen for this lane.
10007       Lanes[j] = Mask[i] / LaneSize;
10008     } else if (Lanes[j] != Mask[i] / LaneSize) {
10009       // This doesn't match the lane selected previously!
10010       return SDValue();
10011     }
10012
10013     // Check that within each lane we have a consistent shuffle mask.
10014     int k = i % LaneSize;
10015     if (InLaneMask[k] < 0) {
10016       InLaneMask[k] = Mask[i] % LaneSize;
10017     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10018       // This doesn't fit a repeating in-lane mask.
10019       return SDValue();
10020     }
10021   }
10022
10023   // First shuffle the lanes into place.
10024   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10025                                 VT.getSizeInBits() / 64);
10026   SmallVector<int, 8> LaneMask;
10027   LaneMask.resize(NumLanes * 2, -1);
10028   for (int i = 0; i < NumLanes; ++i)
10029     if (Lanes[i] >= 0) {
10030       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10031       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10032     }
10033
10034   V1 = DAG.getBitcast(LaneVT, V1);
10035   V2 = DAG.getBitcast(LaneVT, V2);
10036   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10037
10038   // Cast it back to the type we actually want.
10039   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10040
10041   // Now do a simple shuffle that isn't lane crossing.
10042   SmallVector<int, 8> NewMask;
10043   NewMask.resize(Size, -1);
10044   for (int i = 0; i < Size; ++i)
10045     if (Mask[i] >= 0)
10046       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10047   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10048          "Must not introduce lane crosses at this point!");
10049
10050   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10051 }
10052
10053 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10054 /// given mask.
10055 ///
10056 /// This returns true if the elements from a particular input are already in the
10057 /// slot required by the given mask and require no permutation.
10058 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10059   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10060   int Size = Mask.size();
10061   for (int i = 0; i < Size; ++i)
10062     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10063       return false;
10064
10065   return true;
10066 }
10067
10068 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10069                                             ArrayRef<int> Mask, SDValue V1,
10070                                             SDValue V2, SelectionDAG &DAG) {
10071
10072   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
10073   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
10074   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10075   int NumElts = VT.getVectorNumElements();
10076   bool ShufpdMask = true;
10077   bool CommutableMask = true;
10078   unsigned Immediate = 0;
10079   for (int i = 0; i < NumElts; ++i) {
10080     if (Mask[i] < 0)
10081       continue;
10082     int Val = (i & 6) + NumElts * (i & 1);
10083     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10084     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10085       ShufpdMask = false;
10086     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10087       CommutableMask = false;
10088     Immediate |= (Mask[i] % 2) << i;
10089   }
10090   if (ShufpdMask)
10091     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10092                        DAG.getConstant(Immediate, DL, MVT::i8));
10093   if (CommutableMask)
10094     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10095                        DAG.getConstant(Immediate, DL, MVT::i8));
10096   return SDValue();
10097 }
10098
10099 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10100 ///
10101 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10102 /// isn't available.
10103 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10104                                        const X86Subtarget *Subtarget,
10105                                        SelectionDAG &DAG) {
10106   SDLoc DL(Op);
10107   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10108   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10109   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10110   ArrayRef<int> Mask = SVOp->getMask();
10111   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10112
10113   SmallVector<int, 4> WidenedMask;
10114   if (canWidenShuffleElements(Mask, WidenedMask))
10115     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10116                                     DAG);
10117
10118   if (isSingleInputShuffleMask(Mask)) {
10119     // Check for being able to broadcast a single element.
10120     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10121                                                           Mask, Subtarget, DAG))
10122       return Broadcast;
10123
10124     // Use low duplicate instructions for masks that match their pattern.
10125     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10126       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10127
10128     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10129       // Non-half-crossing single input shuffles can be lowerid with an
10130       // interleaved permutation.
10131       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10132                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10133       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10134                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10135     }
10136
10137     // With AVX2 we have direct support for this permutation.
10138     if (Subtarget->hasAVX2())
10139       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10140                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10141
10142     // Otherwise, fall back.
10143     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10144                                                    DAG);
10145   }
10146
10147   // X86 has dedicated unpack instructions that can handle specific blend
10148   // operations: UNPCKH and UNPCKL.
10149   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10150     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
10151   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10152     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
10153   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10154     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
10155   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10156     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
10157
10158   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10159                                                 Subtarget, DAG))
10160     return Blend;
10161
10162   // Check if the blend happens to exactly fit that of SHUFPD.
10163   if (SDValue Op =
10164       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10165     return Op;
10166
10167   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10168   // shuffle. However, if we have AVX2 and either inputs are already in place,
10169   // we will be able to shuffle even across lanes the other input in a single
10170   // instruction so skip this pattern.
10171   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10172                                  isShuffleMaskInputInPlace(1, Mask))))
10173     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10174             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10175       return Result;
10176
10177   // If we have AVX2 then we always want to lower with a blend because an v4 we
10178   // can fully permute the elements.
10179   if (Subtarget->hasAVX2())
10180     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10181                                                       Mask, DAG);
10182
10183   // Otherwise fall back on generic lowering.
10184   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10185 }
10186
10187 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10188 ///
10189 /// This routine is only called when we have AVX2 and thus a reasonable
10190 /// instruction set for v4i64 shuffling..
10191 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10192                                        const X86Subtarget *Subtarget,
10193                                        SelectionDAG &DAG) {
10194   SDLoc DL(Op);
10195   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10196   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10197   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10198   ArrayRef<int> Mask = SVOp->getMask();
10199   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10200   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10201
10202   SmallVector<int, 4> WidenedMask;
10203   if (canWidenShuffleElements(Mask, WidenedMask))
10204     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10205                                     DAG);
10206
10207   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10208                                                 Subtarget, DAG))
10209     return Blend;
10210
10211   // Check for being able to broadcast a single element.
10212   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10213                                                         Mask, Subtarget, DAG))
10214     return Broadcast;
10215
10216   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10217   // use lower latency instructions that will operate on both 128-bit lanes.
10218   SmallVector<int, 2> RepeatedMask;
10219   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10220     if (isSingleInputShuffleMask(Mask)) {
10221       int PSHUFDMask[] = {-1, -1, -1, -1};
10222       for (int i = 0; i < 2; ++i)
10223         if (RepeatedMask[i] >= 0) {
10224           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10225           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10226         }
10227       return DAG.getBitcast(
10228           MVT::v4i64,
10229           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10230                       DAG.getBitcast(MVT::v8i32, V1),
10231                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10232     }
10233   }
10234
10235   // AVX2 provides a direct instruction for permuting a single input across
10236   // lanes.
10237   if (isSingleInputShuffleMask(Mask))
10238     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10239                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10240
10241   // Try to use shift instructions.
10242   if (SDValue Shift =
10243           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10244     return Shift;
10245
10246   // Use dedicated unpack instructions for masks that match their pattern.
10247   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10248     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
10249   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10250     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
10251   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10252     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
10253   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10254     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
10255
10256   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10257   // shuffle. However, if we have AVX2 and either inputs are already in place,
10258   // we will be able to shuffle even across lanes the other input in a single
10259   // instruction so skip this pattern.
10260   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10261                                  isShuffleMaskInputInPlace(1, Mask))))
10262     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10263             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10264       return Result;
10265
10266   // Otherwise fall back on generic blend lowering.
10267   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10268                                                     Mask, DAG);
10269 }
10270
10271 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10272 ///
10273 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10274 /// isn't available.
10275 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10276                                        const X86Subtarget *Subtarget,
10277                                        SelectionDAG &DAG) {
10278   SDLoc DL(Op);
10279   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10280   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10281   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10282   ArrayRef<int> Mask = SVOp->getMask();
10283   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10284
10285   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10286                                                 Subtarget, DAG))
10287     return Blend;
10288
10289   // Check for being able to broadcast a single element.
10290   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10291                                                         Mask, Subtarget, DAG))
10292     return Broadcast;
10293
10294   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10295   // options to efficiently lower the shuffle.
10296   SmallVector<int, 4> RepeatedMask;
10297   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10298     assert(RepeatedMask.size() == 4 &&
10299            "Repeated masks must be half the mask width!");
10300
10301     // Use even/odd duplicate instructions for masks that match their pattern.
10302     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10303       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10304     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10305       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10306
10307     if (isSingleInputShuffleMask(Mask))
10308       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10309                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10310
10311     // Use dedicated unpack instructions for masks that match their pattern.
10312     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10313       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10314     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10315       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10316     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10317       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10318     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10319       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10320
10321     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10322     // have already handled any direct blends. We also need to squash the
10323     // repeated mask into a simulated v4f32 mask.
10324     for (int i = 0; i < 4; ++i)
10325       if (RepeatedMask[i] >= 8)
10326         RepeatedMask[i] -= 4;
10327     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10328   }
10329
10330   // If we have a single input shuffle with different shuffle patterns in the
10331   // two 128-bit lanes use the variable mask to VPERMILPS.
10332   if (isSingleInputShuffleMask(Mask)) {
10333     SDValue VPermMask[8];
10334     for (int i = 0; i < 8; ++i)
10335       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10336                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10337     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10338       return DAG.getNode(
10339           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10340           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10341
10342     if (Subtarget->hasAVX2())
10343       return DAG.getNode(
10344           X86ISD::VPERMV, DL, MVT::v8f32,
10345           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10346                                                  MVT::v8i32, VPermMask)),
10347           V1);
10348
10349     // Otherwise, fall back.
10350     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10351                                                    DAG);
10352   }
10353
10354   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10355   // shuffle.
10356   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10357           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10358     return Result;
10359
10360   // If we have AVX2 then we always want to lower with a blend because at v8 we
10361   // can fully permute the elements.
10362   if (Subtarget->hasAVX2())
10363     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10364                                                       Mask, DAG);
10365
10366   // Otherwise fall back on generic lowering.
10367   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10368 }
10369
10370 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10371 ///
10372 /// This routine is only called when we have AVX2 and thus a reasonable
10373 /// instruction set for v8i32 shuffling..
10374 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10375                                        const X86Subtarget *Subtarget,
10376                                        SelectionDAG &DAG) {
10377   SDLoc DL(Op);
10378   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10379   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10380   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10381   ArrayRef<int> Mask = SVOp->getMask();
10382   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10383   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10384
10385   // Whenever we can lower this as a zext, that instruction is strictly faster
10386   // than any alternative. It also allows us to fold memory operands into the
10387   // shuffle in many cases.
10388   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10389                                                          Mask, Subtarget, DAG))
10390     return ZExt;
10391
10392   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10393                                                 Subtarget, DAG))
10394     return Blend;
10395
10396   // Check for being able to broadcast a single element.
10397   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10398                                                         Mask, Subtarget, DAG))
10399     return Broadcast;
10400
10401   // If the shuffle mask is repeated in each 128-bit lane we can use more
10402   // efficient instructions that mirror the shuffles across the two 128-bit
10403   // lanes.
10404   SmallVector<int, 4> RepeatedMask;
10405   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10406     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10407     if (isSingleInputShuffleMask(Mask))
10408       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10409                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10410
10411     // Use dedicated unpack instructions for masks that match their pattern.
10412     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10413       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10414     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10415       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10416     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10417       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10418     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10419       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10420   }
10421
10422   // Try to use shift instructions.
10423   if (SDValue Shift =
10424           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10425     return Shift;
10426
10427   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10428           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10429     return Rotate;
10430
10431   // If the shuffle patterns aren't repeated but it is a single input, directly
10432   // generate a cross-lane VPERMD instruction.
10433   if (isSingleInputShuffleMask(Mask)) {
10434     SDValue VPermMask[8];
10435     for (int i = 0; i < 8; ++i)
10436       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10437                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10438     return DAG.getNode(
10439         X86ISD::VPERMV, DL, MVT::v8i32,
10440         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10441   }
10442
10443   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10444   // shuffle.
10445   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10446           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10447     return Result;
10448
10449   // Otherwise fall back on generic blend lowering.
10450   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10451                                                     Mask, DAG);
10452 }
10453
10454 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10455 ///
10456 /// This routine is only called when we have AVX2 and thus a reasonable
10457 /// instruction set for v16i16 shuffling..
10458 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10459                                         const X86Subtarget *Subtarget,
10460                                         SelectionDAG &DAG) {
10461   SDLoc DL(Op);
10462   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10463   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10464   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10465   ArrayRef<int> Mask = SVOp->getMask();
10466   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10467   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10468
10469   // Whenever we can lower this as a zext, that instruction is strictly faster
10470   // than any alternative. It also allows us to fold memory operands into the
10471   // shuffle in many cases.
10472   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10473                                                          Mask, Subtarget, DAG))
10474     return ZExt;
10475
10476   // Check for being able to broadcast a single element.
10477   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10478                                                         Mask, Subtarget, DAG))
10479     return Broadcast;
10480
10481   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10482                                                 Subtarget, DAG))
10483     return Blend;
10484
10485   // Use dedicated unpack instructions for masks that match their pattern.
10486   if (isShuffleEquivalent(V1, V2, Mask,
10487                           {// First 128-bit lane:
10488                            0, 16, 1, 17, 2, 18, 3, 19,
10489                            // Second 128-bit lane:
10490                            8, 24, 9, 25, 10, 26, 11, 27}))
10491     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10492   if (isShuffleEquivalent(V1, V2, Mask,
10493                           {// First 128-bit lane:
10494                            4, 20, 5, 21, 6, 22, 7, 23,
10495                            // Second 128-bit lane:
10496                            12, 28, 13, 29, 14, 30, 15, 31}))
10497     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10498
10499   // Try to use shift instructions.
10500   if (SDValue Shift =
10501           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10502     return Shift;
10503
10504   // Try to use byte rotation instructions.
10505   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10506           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10507     return Rotate;
10508
10509   if (isSingleInputShuffleMask(Mask)) {
10510     // There are no generalized cross-lane shuffle operations available on i16
10511     // element types.
10512     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10513       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10514                                                      Mask, DAG);
10515
10516     SmallVector<int, 8> RepeatedMask;
10517     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10518       // As this is a single-input shuffle, the repeated mask should be
10519       // a strictly valid v8i16 mask that we can pass through to the v8i16
10520       // lowering to handle even the v16 case.
10521       return lowerV8I16GeneralSingleInputVectorShuffle(
10522           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10523     }
10524
10525     SDValue PSHUFBMask[32];
10526     for (int i = 0; i < 16; ++i) {
10527       if (Mask[i] == -1) {
10528         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10529         continue;
10530       }
10531
10532       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10533       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10534       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10535       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10536     }
10537     return DAG.getBitcast(MVT::v16i16,
10538                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10539                                       DAG.getBitcast(MVT::v32i8, V1),
10540                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10541                                                   MVT::v32i8, PSHUFBMask)));
10542   }
10543
10544   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10545   // shuffle.
10546   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10547           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10548     return Result;
10549
10550   // Otherwise fall back on generic lowering.
10551   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10552 }
10553
10554 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10555 ///
10556 /// This routine is only called when we have AVX2 and thus a reasonable
10557 /// instruction set for v32i8 shuffling..
10558 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10559                                        const X86Subtarget *Subtarget,
10560                                        SelectionDAG &DAG) {
10561   SDLoc DL(Op);
10562   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10563   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10564   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10565   ArrayRef<int> Mask = SVOp->getMask();
10566   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10567   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10568
10569   // Whenever we can lower this as a zext, that instruction is strictly faster
10570   // than any alternative. It also allows us to fold memory operands into the
10571   // shuffle in many cases.
10572   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10573                                                          Mask, Subtarget, DAG))
10574     return ZExt;
10575
10576   // Check for being able to broadcast a single element.
10577   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10578                                                         Mask, Subtarget, DAG))
10579     return Broadcast;
10580
10581   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10582                                                 Subtarget, DAG))
10583     return Blend;
10584
10585   // Use dedicated unpack instructions for masks that match their pattern.
10586   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10587   // 256-bit lanes.
10588   if (isShuffleEquivalent(
10589           V1, V2, Mask,
10590           {// First 128-bit lane:
10591            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10592            // Second 128-bit lane:
10593            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10594     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10595   if (isShuffleEquivalent(
10596           V1, V2, Mask,
10597           {// First 128-bit lane:
10598            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10599            // Second 128-bit lane:
10600            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10601     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10602
10603   // Try to use shift instructions.
10604   if (SDValue Shift =
10605           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10606     return Shift;
10607
10608   // Try to use byte rotation instructions.
10609   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10610           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10611     return Rotate;
10612
10613   if (isSingleInputShuffleMask(Mask)) {
10614     // There are no generalized cross-lane shuffle operations available on i8
10615     // element types.
10616     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10617       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10618                                                      Mask, DAG);
10619
10620     SDValue PSHUFBMask[32];
10621     for (int i = 0; i < 32; ++i)
10622       PSHUFBMask[i] =
10623           Mask[i] < 0
10624               ? DAG.getUNDEF(MVT::i8)
10625               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10626                                 MVT::i8);
10627
10628     return DAG.getNode(
10629         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10630         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10631   }
10632
10633   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10634   // shuffle.
10635   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10636           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10637     return Result;
10638
10639   // Otherwise fall back on generic lowering.
10640   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10641 }
10642
10643 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10644 ///
10645 /// This routine either breaks down the specific type of a 256-bit x86 vector
10646 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10647 /// together based on the available instructions.
10648 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10649                                         MVT VT, const X86Subtarget *Subtarget,
10650                                         SelectionDAG &DAG) {
10651   SDLoc DL(Op);
10652   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10653   ArrayRef<int> Mask = SVOp->getMask();
10654
10655   // If we have a single input to the zero element, insert that into V1 if we
10656   // can do so cheaply.
10657   int NumElts = VT.getVectorNumElements();
10658   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10659     return M >= NumElts;
10660   });
10661
10662   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10663     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10664                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10665       return Insertion;
10666
10667   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10668   // check for those subtargets here and avoid much of the subtarget querying in
10669   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10670   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10671   // floating point types there eventually, just immediately cast everything to
10672   // a float and operate entirely in that domain.
10673   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10674     int ElementBits = VT.getScalarSizeInBits();
10675     if (ElementBits < 32)
10676       // No floating point type available, decompose into 128-bit vectors.
10677       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10678
10679     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10680                                 VT.getVectorNumElements());
10681     V1 = DAG.getBitcast(FpVT, V1);
10682     V2 = DAG.getBitcast(FpVT, V2);
10683     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10684   }
10685
10686   switch (VT.SimpleTy) {
10687   case MVT::v4f64:
10688     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10689   case MVT::v4i64:
10690     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10691   case MVT::v8f32:
10692     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10693   case MVT::v8i32:
10694     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10695   case MVT::v16i16:
10696     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10697   case MVT::v32i8:
10698     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10699
10700   default:
10701     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10702   }
10703 }
10704
10705 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10706                                            ArrayRef<int> Mask, SDValue V1,
10707                                            SDValue V2, SelectionDAG &DAG) {
10708
10709   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10710
10711   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10712   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10713
10714   SmallVector<SDValue, 32>  VPermMask;
10715   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i)
10716     VPermMask.push_back(Mask[i] < 0 ? DAG.getUNDEF(MaskEltVT) :
10717                         DAG.getConstant(Mask[i], DL, MaskEltVT));
10718   SDValue MaskNode = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVecVT,
10719                                  VPermMask);
10720   if (isSingleInputShuffleMask(Mask))
10721     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10722
10723   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10724 }
10725
10726 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10727 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10728                                        const X86Subtarget *Subtarget,
10729                                        SelectionDAG &DAG) {
10730   SDLoc DL(Op);
10731   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10732   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10733   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10734   ArrayRef<int> Mask = SVOp->getMask();
10735   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10736
10737   if (SDValue Unpck =
10738           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
10739     return Unpck;
10740
10741   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10742 }
10743
10744 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10745 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10746                                        const X86Subtarget *Subtarget,
10747                                        SelectionDAG &DAG) {
10748   SDLoc DL(Op);
10749   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10750   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10751   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10752   ArrayRef<int> Mask = SVOp->getMask();
10753   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10754
10755   if (SDValue Unpck =
10756           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
10757     return Unpck;
10758
10759   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
10760 }
10761
10762 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10763 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10764                                        const X86Subtarget *Subtarget,
10765                                        SelectionDAG &DAG) {
10766   SDLoc DL(Op);
10767   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10768   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10769   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10770   ArrayRef<int> Mask = SVOp->getMask();
10771   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10772
10773   if (SDValue Unpck =
10774           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
10775     return Unpck;
10776
10777   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
10778 }
10779
10780 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10781 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10782                                        const X86Subtarget *Subtarget,
10783                                        SelectionDAG &DAG) {
10784   SDLoc DL(Op);
10785   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10786   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10787   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10788   ArrayRef<int> Mask = SVOp->getMask();
10789   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10790
10791   if (SDValue Unpck =
10792           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
10793     return Unpck;
10794
10795   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
10796 }
10797
10798 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10799 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10800                                         const X86Subtarget *Subtarget,
10801                                         SelectionDAG &DAG) {
10802   SDLoc DL(Op);
10803   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10804   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10805   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10806   ArrayRef<int> Mask = SVOp->getMask();
10807   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10808   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10809
10810   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
10811 }
10812
10813 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10814 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10815                                        const X86Subtarget *Subtarget,
10816                                        SelectionDAG &DAG) {
10817   SDLoc DL(Op);
10818   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10819   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10820   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10821   ArrayRef<int> Mask = SVOp->getMask();
10822   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10823   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10824
10825   // FIXME: Implement direct support for this type!
10826   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10827 }
10828
10829 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10830 ///
10831 /// This routine either breaks down the specific type of a 512-bit x86 vector
10832 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10833 /// together based on the available instructions.
10834 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10835                                         MVT VT, const X86Subtarget *Subtarget,
10836                                         SelectionDAG &DAG) {
10837   SDLoc DL(Op);
10838   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10839   ArrayRef<int> Mask = SVOp->getMask();
10840   assert(Subtarget->hasAVX512() &&
10841          "Cannot lower 512-bit vectors w/ basic ISA!");
10842
10843   // Check for being able to broadcast a single element.
10844   if (SDValue Broadcast =
10845           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10846     return Broadcast;
10847
10848   // Dispatch to each element type for lowering. If we don't have supprot for
10849   // specific element type shuffles at 512 bits, immediately split them and
10850   // lower them. Each lowering routine of a given type is allowed to assume that
10851   // the requisite ISA extensions for that element type are available.
10852   switch (VT.SimpleTy) {
10853   case MVT::v8f64:
10854     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10855   case MVT::v16f32:
10856     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10857   case MVT::v8i64:
10858     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10859   case MVT::v16i32:
10860     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10861   case MVT::v32i16:
10862     if (Subtarget->hasBWI())
10863       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10864     break;
10865   case MVT::v64i8:
10866     if (Subtarget->hasBWI())
10867       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10868     break;
10869
10870   default:
10871     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10872   }
10873
10874   // Otherwise fall back on splitting.
10875   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10876 }
10877
10878 // Lower vXi1 vector shuffles.
10879 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
10880 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
10881 // vector, shuffle and then truncate it back.
10882 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10883                                       MVT VT, const X86Subtarget *Subtarget,
10884                                       SelectionDAG &DAG) {
10885   SDLoc DL(Op);
10886   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10887   ArrayRef<int> Mask = SVOp->getMask();
10888   assert(Subtarget->hasAVX512() &&
10889          "Cannot lower 512-bit vectors w/o basic ISA!");
10890   EVT ExtVT;
10891   switch (VT.SimpleTy) {
10892   default:
10893     assert(false && "Expected a vector of i1 elements");
10894     break;
10895   case MVT::v2i1:
10896     ExtVT = MVT::v2i64;
10897     break;
10898   case MVT::v4i1:
10899     ExtVT = MVT::v4i32;
10900     break;
10901   case MVT::v8i1:
10902     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
10903     break;
10904   case MVT::v16i1:
10905     ExtVT = MVT::v16i32;
10906     break;
10907   case MVT::v32i1:
10908     ExtVT = MVT::v32i16;
10909     break;
10910   case MVT::v64i1:
10911     ExtVT = MVT::v64i8;
10912     break;
10913   }
10914
10915   if (ISD::isBuildVectorAllZeros(V1.getNode()))
10916     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10917   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
10918     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10919   else
10920     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
10921
10922   if (V2.isUndef())
10923     V2 = DAG.getUNDEF(ExtVT);
10924   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
10925     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10926   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
10927     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10928   else
10929     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
10930   return DAG.getNode(ISD::TRUNCATE, DL, VT,
10931                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
10932 }
10933 /// \brief Top-level lowering for x86 vector shuffles.
10934 ///
10935 /// This handles decomposition, canonicalization, and lowering of all x86
10936 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10937 /// above in helper routines. The canonicalization attempts to widen shuffles
10938 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10939 /// s.t. only one of the two inputs needs to be tested, etc.
10940 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10941                                   SelectionDAG &DAG) {
10942   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10943   ArrayRef<int> Mask = SVOp->getMask();
10944   SDValue V1 = Op.getOperand(0);
10945   SDValue V2 = Op.getOperand(1);
10946   MVT VT = Op.getSimpleValueType();
10947   int NumElements = VT.getVectorNumElements();
10948   SDLoc dl(Op);
10949   bool Is1BitVector = (VT.getScalarType() == MVT::i1);
10950
10951   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
10952          "Can't lower MMX shuffles");
10953
10954   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10955   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10956   if (V1IsUndef && V2IsUndef)
10957     return DAG.getUNDEF(VT);
10958
10959   // When we create a shuffle node we put the UNDEF node to second operand,
10960   // but in some cases the first operand may be transformed to UNDEF.
10961   // In this case we should just commute the node.
10962   if (V1IsUndef)
10963     return DAG.getCommutedVectorShuffle(*SVOp);
10964
10965   // Check for non-undef masks pointing at an undef vector and make the masks
10966   // undef as well. This makes it easier to match the shuffle based solely on
10967   // the mask.
10968   if (V2IsUndef)
10969     for (int M : Mask)
10970       if (M >= NumElements) {
10971         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10972         for (int &M : NewMask)
10973           if (M >= NumElements)
10974             M = -1;
10975         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10976       }
10977
10978   // We actually see shuffles that are entirely re-arrangements of a set of
10979   // zero inputs. This mostly happens while decomposing complex shuffles into
10980   // simple ones. Directly lower these as a buildvector of zeros.
10981   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10982   if (Zeroable.all())
10983     return getZeroVector(VT, Subtarget, DAG, dl);
10984
10985   // Try to collapse shuffles into using a vector type with fewer elements but
10986   // wider element types. We cap this to not form integers or floating point
10987   // elements wider than 64 bits, but it might be interesting to form i128
10988   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10989   SmallVector<int, 16> WidenedMask;
10990   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
10991       canWidenShuffleElements(Mask, WidenedMask)) {
10992     MVT NewEltVT = VT.isFloatingPoint()
10993                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10994                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10995     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10996     // Make sure that the new vector type is legal. For example, v2f64 isn't
10997     // legal on SSE1.
10998     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10999       V1 = DAG.getBitcast(NewVT, V1);
11000       V2 = DAG.getBitcast(NewVT, V2);
11001       return DAG.getBitcast(
11002           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11003     }
11004   }
11005
11006   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11007   for (int M : SVOp->getMask())
11008     if (M < 0)
11009       ++NumUndefElements;
11010     else if (M < NumElements)
11011       ++NumV1Elements;
11012     else
11013       ++NumV2Elements;
11014
11015   // Commute the shuffle as needed such that more elements come from V1 than
11016   // V2. This allows us to match the shuffle pattern strictly on how many
11017   // elements come from V1 without handling the symmetric cases.
11018   if (NumV2Elements > NumV1Elements)
11019     return DAG.getCommutedVectorShuffle(*SVOp);
11020
11021   // When the number of V1 and V2 elements are the same, try to minimize the
11022   // number of uses of V2 in the low half of the vector. When that is tied,
11023   // ensure that the sum of indices for V1 is equal to or lower than the sum
11024   // indices for V2. When those are equal, try to ensure that the number of odd
11025   // indices for V1 is lower than the number of odd indices for V2.
11026   if (NumV1Elements == NumV2Elements) {
11027     int LowV1Elements = 0, LowV2Elements = 0;
11028     for (int M : SVOp->getMask().slice(0, NumElements / 2))
11029       if (M >= NumElements)
11030         ++LowV2Elements;
11031       else if (M >= 0)
11032         ++LowV1Elements;
11033     if (LowV2Elements > LowV1Elements) {
11034       return DAG.getCommutedVectorShuffle(*SVOp);
11035     } else if (LowV2Elements == LowV1Elements) {
11036       int SumV1Indices = 0, SumV2Indices = 0;
11037       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11038         if (SVOp->getMask()[i] >= NumElements)
11039           SumV2Indices += i;
11040         else if (SVOp->getMask()[i] >= 0)
11041           SumV1Indices += i;
11042       if (SumV2Indices < SumV1Indices) {
11043         return DAG.getCommutedVectorShuffle(*SVOp);
11044       } else if (SumV2Indices == SumV1Indices) {
11045         int NumV1OddIndices = 0, NumV2OddIndices = 0;
11046         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11047           if (SVOp->getMask()[i] >= NumElements)
11048             NumV2OddIndices += i % 2;
11049           else if (SVOp->getMask()[i] >= 0)
11050             NumV1OddIndices += i % 2;
11051         if (NumV2OddIndices < NumV1OddIndices)
11052           return DAG.getCommutedVectorShuffle(*SVOp);
11053       }
11054     }
11055   }
11056
11057   // For each vector width, delegate to a specialized lowering routine.
11058   if (VT.getSizeInBits() == 128)
11059     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11060
11061   if (VT.getSizeInBits() == 256)
11062     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11063
11064   if (VT.getSizeInBits() == 512)
11065     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11066
11067   if (Is1BitVector)
11068     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11069   llvm_unreachable("Unimplemented!");
11070 }
11071
11072 // This function assumes its argument is a BUILD_VECTOR of constants or
11073 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11074 // true.
11075 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11076                                     unsigned &MaskValue) {
11077   MaskValue = 0;
11078   unsigned NumElems = BuildVector->getNumOperands();
11079   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11080   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11081   unsigned NumElemsInLane = NumElems / NumLanes;
11082
11083   // Blend for v16i16 should be symmetric for the both lanes.
11084   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11085     SDValue EltCond = BuildVector->getOperand(i);
11086     SDValue SndLaneEltCond =
11087         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11088
11089     int Lane1Cond = -1, Lane2Cond = -1;
11090     if (isa<ConstantSDNode>(EltCond))
11091       Lane1Cond = !isZero(EltCond);
11092     if (isa<ConstantSDNode>(SndLaneEltCond))
11093       Lane2Cond = !isZero(SndLaneEltCond);
11094
11095     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11096       // Lane1Cond != 0, means we want the first argument.
11097       // Lane1Cond == 0, means we want the second argument.
11098       // The encoding of this argument is 0 for the first argument, 1
11099       // for the second. Therefore, invert the condition.
11100       MaskValue |= !Lane1Cond << i;
11101     else if (Lane1Cond < 0)
11102       MaskValue |= !Lane2Cond << i;
11103     else
11104       return false;
11105   }
11106   return true;
11107 }
11108
11109 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11110 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11111                                            const X86Subtarget *Subtarget,
11112                                            SelectionDAG &DAG) {
11113   SDValue Cond = Op.getOperand(0);
11114   SDValue LHS = Op.getOperand(1);
11115   SDValue RHS = Op.getOperand(2);
11116   SDLoc dl(Op);
11117   MVT VT = Op.getSimpleValueType();
11118
11119   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11120     return SDValue();
11121   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11122
11123   // Only non-legal VSELECTs reach this lowering, convert those into generic
11124   // shuffles and re-use the shuffle lowering path for blends.
11125   SmallVector<int, 32> Mask;
11126   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11127     SDValue CondElt = CondBV->getOperand(i);
11128     Mask.push_back(
11129         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
11130   }
11131   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11132 }
11133
11134 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11135   // A vselect where all conditions and data are constants can be optimized into
11136   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11137   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11138       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11139       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11140     return SDValue();
11141
11142   // Try to lower this to a blend-style vector shuffle. This can handle all
11143   // constant condition cases.
11144   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11145     return BlendOp;
11146
11147   // Variable blends are only legal from SSE4.1 onward.
11148   if (!Subtarget->hasSSE41())
11149     return SDValue();
11150
11151   // Only some types will be legal on some subtargets. If we can emit a legal
11152   // VSELECT-matching blend, return Op, and but if we need to expand, return
11153   // a null value.
11154   switch (Op.getSimpleValueType().SimpleTy) {
11155   default:
11156     // Most of the vector types have blends past SSE4.1.
11157     return Op;
11158
11159   case MVT::v32i8:
11160     // The byte blends for AVX vectors were introduced only in AVX2.
11161     if (Subtarget->hasAVX2())
11162       return Op;
11163
11164     return SDValue();
11165
11166   case MVT::v8i16:
11167   case MVT::v16i16:
11168     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11169     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11170       return Op;
11171
11172     // FIXME: We should custom lower this by fixing the condition and using i8
11173     // blends.
11174     return SDValue();
11175   }
11176 }
11177
11178 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11179   MVT VT = Op.getSimpleValueType();
11180   SDLoc dl(Op);
11181
11182   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11183     return SDValue();
11184
11185   if (VT.getSizeInBits() == 8) {
11186     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11187                                   Op.getOperand(0), Op.getOperand(1));
11188     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11189                                   DAG.getValueType(VT));
11190     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11191   }
11192
11193   if (VT.getSizeInBits() == 16) {
11194     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11195     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11196     if (Idx == 0)
11197       return DAG.getNode(
11198           ISD::TRUNCATE, dl, MVT::i16,
11199           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11200                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11201                       Op.getOperand(1)));
11202     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11203                                   Op.getOperand(0), Op.getOperand(1));
11204     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11205                                   DAG.getValueType(VT));
11206     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11207   }
11208
11209   if (VT == MVT::f32) {
11210     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11211     // the result back to FR32 register. It's only worth matching if the
11212     // result has a single use which is a store or a bitcast to i32.  And in
11213     // the case of a store, it's not worth it if the index is a constant 0,
11214     // because a MOVSSmr can be used instead, which is smaller and faster.
11215     if (!Op.hasOneUse())
11216       return SDValue();
11217     SDNode *User = *Op.getNode()->use_begin();
11218     if ((User->getOpcode() != ISD::STORE ||
11219          (isa<ConstantSDNode>(Op.getOperand(1)) &&
11220           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11221         (User->getOpcode() != ISD::BITCAST ||
11222          User->getValueType(0) != MVT::i32))
11223       return SDValue();
11224     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11225                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11226                                   Op.getOperand(1));
11227     return DAG.getBitcast(MVT::f32, Extract);
11228   }
11229
11230   if (VT == MVT::i32 || VT == MVT::i64) {
11231     // ExtractPS/pextrq works with constant index.
11232     if (isa<ConstantSDNode>(Op.getOperand(1)))
11233       return Op;
11234   }
11235   return SDValue();
11236 }
11237
11238 /// Extract one bit from mask vector, like v16i1 or v8i1.
11239 /// AVX-512 feature.
11240 SDValue
11241 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11242   SDValue Vec = Op.getOperand(0);
11243   SDLoc dl(Vec);
11244   MVT VecVT = Vec.getSimpleValueType();
11245   SDValue Idx = Op.getOperand(1);
11246   MVT EltVT = Op.getSimpleValueType();
11247
11248   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11249   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11250          "Unexpected vector type in ExtractBitFromMaskVector");
11251
11252   // variable index can't be handled in mask registers,
11253   // extend vector to VR512
11254   if (!isa<ConstantSDNode>(Idx)) {
11255     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11256     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11257     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11258                               ExtVT.getVectorElementType(), Ext, Idx);
11259     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11260   }
11261
11262   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11263   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11264   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11265     rc = getRegClassFor(MVT::v16i1);
11266   unsigned MaxSift = rc->getSize()*8 - 1;
11267   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11268                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11269   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11270                     DAG.getConstant(MaxSift, dl, MVT::i8));
11271   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11272                        DAG.getIntPtrConstant(0, dl));
11273 }
11274
11275 SDValue
11276 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11277                                            SelectionDAG &DAG) const {
11278   SDLoc dl(Op);
11279   SDValue Vec = Op.getOperand(0);
11280   MVT VecVT = Vec.getSimpleValueType();
11281   SDValue Idx = Op.getOperand(1);
11282
11283   if (Op.getSimpleValueType() == MVT::i1)
11284     return ExtractBitFromMaskVector(Op, DAG);
11285
11286   if (!isa<ConstantSDNode>(Idx)) {
11287     if (VecVT.is512BitVector() ||
11288         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11289          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11290
11291       MVT MaskEltVT =
11292         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11293       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11294                                     MaskEltVT.getSizeInBits());
11295
11296       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11297       auto PtrVT = getPointerTy(DAG.getDataLayout());
11298       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11299                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11300                                  DAG.getConstant(0, dl, PtrVT));
11301       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11302       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11303                          DAG.getConstant(0, dl, PtrVT));
11304     }
11305     return SDValue();
11306   }
11307
11308   // If this is a 256-bit vector result, first extract the 128-bit vector and
11309   // then extract the element from the 128-bit vector.
11310   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11311
11312     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11313     // Get the 128-bit vector.
11314     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11315     MVT EltVT = VecVT.getVectorElementType();
11316
11317     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11318
11319     //if (IdxVal >= NumElems/2)
11320     //  IdxVal -= NumElems/2;
11321     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
11322     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11323                        DAG.getConstant(IdxVal, dl, MVT::i32));
11324   }
11325
11326   assert(VecVT.is128BitVector() && "Unexpected vector length");
11327
11328   if (Subtarget->hasSSE41())
11329     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11330       return Res;
11331
11332   MVT VT = Op.getSimpleValueType();
11333   // TODO: handle v16i8.
11334   if (VT.getSizeInBits() == 16) {
11335     SDValue Vec = Op.getOperand(0);
11336     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11337     if (Idx == 0)
11338       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11339                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11340                                      DAG.getBitcast(MVT::v4i32, Vec),
11341                                      Op.getOperand(1)));
11342     // Transform it so it match pextrw which produces a 32-bit result.
11343     MVT EltVT = MVT::i32;
11344     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11345                                   Op.getOperand(0), Op.getOperand(1));
11346     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11347                                   DAG.getValueType(VT));
11348     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11349   }
11350
11351   if (VT.getSizeInBits() == 32) {
11352     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11353     if (Idx == 0)
11354       return Op;
11355
11356     // SHUFPS the element to the lowest double word, then movss.
11357     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11358     MVT VVT = Op.getOperand(0).getSimpleValueType();
11359     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11360                                        DAG.getUNDEF(VVT), Mask);
11361     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11362                        DAG.getIntPtrConstant(0, dl));
11363   }
11364
11365   if (VT.getSizeInBits() == 64) {
11366     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11367     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11368     //        to match extract_elt for f64.
11369     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11370     if (Idx == 0)
11371       return Op;
11372
11373     // UNPCKHPD the element to the lowest double word, then movsd.
11374     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11375     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11376     int Mask[2] = { 1, -1 };
11377     MVT VVT = Op.getOperand(0).getSimpleValueType();
11378     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11379                                        DAG.getUNDEF(VVT), Mask);
11380     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11381                        DAG.getIntPtrConstant(0, dl));
11382   }
11383
11384   return SDValue();
11385 }
11386
11387 /// Insert one bit to mask vector, like v16i1 or v8i1.
11388 /// AVX-512 feature.
11389 SDValue
11390 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11391   SDLoc dl(Op);
11392   SDValue Vec = Op.getOperand(0);
11393   SDValue Elt = Op.getOperand(1);
11394   SDValue Idx = Op.getOperand(2);
11395   MVT VecVT = Vec.getSimpleValueType();
11396
11397   if (!isa<ConstantSDNode>(Idx)) {
11398     // Non constant index. Extend source and destination,
11399     // insert element and then truncate the result.
11400     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11401     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11402     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11403       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11404       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11405     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11406   }
11407
11408   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11409   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11410   if (IdxVal)
11411     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11412                            DAG.getConstant(IdxVal, dl, MVT::i8));
11413   if (Vec.getOpcode() == ISD::UNDEF)
11414     return EltInVec;
11415   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11416 }
11417
11418 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11419                                                   SelectionDAG &DAG) const {
11420   MVT VT = Op.getSimpleValueType();
11421   MVT EltVT = VT.getVectorElementType();
11422
11423   if (EltVT == MVT::i1)
11424     return InsertBitToMaskVector(Op, DAG);
11425
11426   SDLoc dl(Op);
11427   SDValue N0 = Op.getOperand(0);
11428   SDValue N1 = Op.getOperand(1);
11429   SDValue N2 = Op.getOperand(2);
11430   if (!isa<ConstantSDNode>(N2))
11431     return SDValue();
11432   auto *N2C = cast<ConstantSDNode>(N2);
11433   unsigned IdxVal = N2C->getZExtValue();
11434
11435   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11436   // into that, and then insert the subvector back into the result.
11437   if (VT.is256BitVector() || VT.is512BitVector()) {
11438     // With a 256-bit vector, we can insert into the zero element efficiently
11439     // using a blend if we have AVX or AVX2 and the right data type.
11440     if (VT.is256BitVector() && IdxVal == 0) {
11441       // TODO: It is worthwhile to cast integer to floating point and back
11442       // and incur a domain crossing penalty if that's what we'll end up
11443       // doing anyway after extracting to a 128-bit vector.
11444       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11445           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11446         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11447         N2 = DAG.getIntPtrConstant(1, dl);
11448         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11449       }
11450     }
11451
11452     // Get the desired 128-bit vector chunk.
11453     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11454
11455     // Insert the element into the desired chunk.
11456     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11457     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11458
11459     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11460                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11461
11462     // Insert the changed part back into the bigger vector
11463     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11464   }
11465   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11466
11467   if (Subtarget->hasSSE41()) {
11468     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11469       unsigned Opc;
11470       if (VT == MVT::v8i16) {
11471         Opc = X86ISD::PINSRW;
11472       } else {
11473         assert(VT == MVT::v16i8);
11474         Opc = X86ISD::PINSRB;
11475       }
11476
11477       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11478       // argument.
11479       if (N1.getValueType() != MVT::i32)
11480         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11481       if (N2.getValueType() != MVT::i32)
11482         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11483       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11484     }
11485
11486     if (EltVT == MVT::f32) {
11487       // Bits [7:6] of the constant are the source select. This will always be
11488       //   zero here. The DAG Combiner may combine an extract_elt index into
11489       //   these bits. For example (insert (extract, 3), 2) could be matched by
11490       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11491       // Bits [5:4] of the constant are the destination select. This is the
11492       //   value of the incoming immediate.
11493       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11494       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11495
11496       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11497       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11498         // If this is an insertion of 32-bits into the low 32-bits of
11499         // a vector, we prefer to generate a blend with immediate rather
11500         // than an insertps. Blends are simpler operations in hardware and so
11501         // will always have equal or better performance than insertps.
11502         // But if optimizing for size and there's a load folding opportunity,
11503         // generate insertps because blendps does not have a 32-bit memory
11504         // operand form.
11505         N2 = DAG.getIntPtrConstant(1, dl);
11506         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11507         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11508       }
11509       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11510       // Create this as a scalar to vector..
11511       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11512       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11513     }
11514
11515     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11516       // PINSR* works with constant index.
11517       return Op;
11518     }
11519   }
11520
11521   if (EltVT == MVT::i8)
11522     return SDValue();
11523
11524   if (EltVT.getSizeInBits() == 16) {
11525     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11526     // as its second argument.
11527     if (N1.getValueType() != MVT::i32)
11528       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11529     if (N2.getValueType() != MVT::i32)
11530       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11531     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11532   }
11533   return SDValue();
11534 }
11535
11536 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11537   SDLoc dl(Op);
11538   MVT OpVT = Op.getSimpleValueType();
11539
11540   // If this is a 256-bit vector result, first insert into a 128-bit
11541   // vector and then insert into the 256-bit vector.
11542   if (!OpVT.is128BitVector()) {
11543     // Insert into a 128-bit vector.
11544     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11545     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11546                                  OpVT.getVectorNumElements() / SizeFactor);
11547
11548     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11549
11550     // Insert the 128-bit vector.
11551     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11552   }
11553
11554   if (OpVT == MVT::v1i64 &&
11555       Op.getOperand(0).getValueType() == MVT::i64)
11556     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11557
11558   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11559   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11560   return DAG.getBitcast(
11561       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11562 }
11563
11564 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11565 // a simple subregister reference or explicit instructions to grab
11566 // upper bits of a vector.
11567 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11568                                       SelectionDAG &DAG) {
11569   SDLoc dl(Op);
11570   SDValue In =  Op.getOperand(0);
11571   SDValue Idx = Op.getOperand(1);
11572   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11573   MVT ResVT   = Op.getSimpleValueType();
11574   MVT InVT    = In.getSimpleValueType();
11575
11576   if (Subtarget->hasFp256()) {
11577     if (ResVT.is128BitVector() &&
11578         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11579         isa<ConstantSDNode>(Idx)) {
11580       return Extract128BitVector(In, IdxVal, DAG, dl);
11581     }
11582     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11583         isa<ConstantSDNode>(Idx)) {
11584       return Extract256BitVector(In, IdxVal, DAG, dl);
11585     }
11586   }
11587   return SDValue();
11588 }
11589
11590 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11591 // simple superregister reference or explicit instructions to insert
11592 // the upper bits of a vector.
11593 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11594                                      SelectionDAG &DAG) {
11595   if (!Subtarget->hasAVX())
11596     return SDValue();
11597
11598   SDLoc dl(Op);
11599   SDValue Vec = Op.getOperand(0);
11600   SDValue SubVec = Op.getOperand(1);
11601   SDValue Idx = Op.getOperand(2);
11602
11603   if (!isa<ConstantSDNode>(Idx))
11604     return SDValue();
11605
11606   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11607   MVT OpVT = Op.getSimpleValueType();
11608   MVT SubVecVT = SubVec.getSimpleValueType();
11609
11610   // Fold two 16-byte subvector loads into one 32-byte load:
11611   // (insert_subvector (insert_subvector undef, (load addr), 0),
11612   //                   (load addr + 16), Elts/2)
11613   // --> load32 addr
11614   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11615       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11616       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11617     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11618     if (Idx2 && Idx2->getZExtValue() == 0) {
11619       SDValue SubVec2 = Vec.getOperand(1);
11620       // If needed, look through a bitcast to get to the load.
11621       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11622         SubVec2 = SubVec2.getOperand(0);
11623
11624       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11625         bool Fast;
11626         unsigned Alignment = FirstLd->getAlignment();
11627         unsigned AS = FirstLd->getAddressSpace();
11628         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11629         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11630                                     OpVT, AS, Alignment, &Fast) && Fast) {
11631           SDValue Ops[] = { SubVec2, SubVec };
11632           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11633             return Ld;
11634         }
11635       }
11636     }
11637   }
11638
11639   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11640       SubVecVT.is128BitVector())
11641     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11642
11643   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11644     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11645
11646   if (OpVT.getVectorElementType() == MVT::i1) {
11647     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11648       return Op;
11649     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11650     SDValue Undef = DAG.getUNDEF(OpVT);
11651     unsigned NumElems = OpVT.getVectorNumElements();
11652     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11653
11654     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11655       // Zero upper bits of the Vec
11656       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11657       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11658
11659       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11660                                  SubVec, ZeroIdx);
11661       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11662       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11663     }
11664     if (IdxVal == 0) {
11665       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11666                                  SubVec, ZeroIdx);
11667       // Zero upper bits of the Vec2
11668       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11669       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11670       // Zero lower bits of the Vec
11671       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11672       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11673       // Merge them together
11674       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11675     }
11676   }
11677   return SDValue();
11678 }
11679
11680 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11681 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11682 // one of the above mentioned nodes. It has to be wrapped because otherwise
11683 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11684 // be used to form addressing mode. These wrapped nodes will be selected
11685 // into MOV32ri.
11686 SDValue
11687 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11688   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11689
11690   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11691   // global base reg.
11692   unsigned char OpFlag = 0;
11693   unsigned WrapperKind = X86ISD::Wrapper;
11694   CodeModel::Model M = DAG.getTarget().getCodeModel();
11695
11696   if (Subtarget->isPICStyleRIPRel() &&
11697       (M == CodeModel::Small || M == CodeModel::Kernel))
11698     WrapperKind = X86ISD::WrapperRIP;
11699   else if (Subtarget->isPICStyleGOT())
11700     OpFlag = X86II::MO_GOTOFF;
11701   else if (Subtarget->isPICStyleStubPIC())
11702     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11703
11704   auto PtrVT = getPointerTy(DAG.getDataLayout());
11705   SDValue Result = DAG.getTargetConstantPool(
11706       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11707   SDLoc DL(CP);
11708   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11709   // With PIC, the address is actually $g + Offset.
11710   if (OpFlag) {
11711     Result =
11712         DAG.getNode(ISD::ADD, DL, PtrVT,
11713                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11714   }
11715
11716   return Result;
11717 }
11718
11719 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11720   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11721
11722   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11723   // global base reg.
11724   unsigned char OpFlag = 0;
11725   unsigned WrapperKind = X86ISD::Wrapper;
11726   CodeModel::Model M = DAG.getTarget().getCodeModel();
11727
11728   if (Subtarget->isPICStyleRIPRel() &&
11729       (M == CodeModel::Small || M == CodeModel::Kernel))
11730     WrapperKind = X86ISD::WrapperRIP;
11731   else if (Subtarget->isPICStyleGOT())
11732     OpFlag = X86II::MO_GOTOFF;
11733   else if (Subtarget->isPICStyleStubPIC())
11734     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11735
11736   auto PtrVT = getPointerTy(DAG.getDataLayout());
11737   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11738   SDLoc DL(JT);
11739   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11740
11741   // With PIC, the address is actually $g + Offset.
11742   if (OpFlag)
11743     Result =
11744         DAG.getNode(ISD::ADD, DL, PtrVT,
11745                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11746
11747   return Result;
11748 }
11749
11750 SDValue
11751 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11752   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11753
11754   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11755   // global base reg.
11756   unsigned char OpFlag = 0;
11757   unsigned WrapperKind = X86ISD::Wrapper;
11758   CodeModel::Model M = DAG.getTarget().getCodeModel();
11759
11760   if (Subtarget->isPICStyleRIPRel() &&
11761       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11762     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11763       OpFlag = X86II::MO_GOTPCREL;
11764     WrapperKind = X86ISD::WrapperRIP;
11765   } else if (Subtarget->isPICStyleGOT()) {
11766     OpFlag = X86II::MO_GOT;
11767   } else if (Subtarget->isPICStyleStubPIC()) {
11768     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11769   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11770     OpFlag = X86II::MO_DARWIN_NONLAZY;
11771   }
11772
11773   auto PtrVT = getPointerTy(DAG.getDataLayout());
11774   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11775
11776   SDLoc DL(Op);
11777   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11778
11779   // With PIC, the address is actually $g + Offset.
11780   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11781       !Subtarget->is64Bit()) {
11782     Result =
11783         DAG.getNode(ISD::ADD, DL, PtrVT,
11784                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11785   }
11786
11787   // For symbols that require a load from a stub to get the address, emit the
11788   // load.
11789   if (isGlobalStubReference(OpFlag))
11790     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11791                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11792                          false, false, false, 0);
11793
11794   return Result;
11795 }
11796
11797 SDValue
11798 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11799   // Create the TargetBlockAddressAddress node.
11800   unsigned char OpFlags =
11801     Subtarget->ClassifyBlockAddressReference();
11802   CodeModel::Model M = DAG.getTarget().getCodeModel();
11803   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11804   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11805   SDLoc dl(Op);
11806   auto PtrVT = getPointerTy(DAG.getDataLayout());
11807   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11808
11809   if (Subtarget->isPICStyleRIPRel() &&
11810       (M == CodeModel::Small || M == CodeModel::Kernel))
11811     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11812   else
11813     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11814
11815   // With PIC, the address is actually $g + Offset.
11816   if (isGlobalRelativeToPICBase(OpFlags)) {
11817     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11818                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11819   }
11820
11821   return Result;
11822 }
11823
11824 SDValue
11825 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11826                                       int64_t Offset, SelectionDAG &DAG) const {
11827   // Create the TargetGlobalAddress node, folding in the constant
11828   // offset if it is legal.
11829   unsigned char OpFlags =
11830       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11831   CodeModel::Model M = DAG.getTarget().getCodeModel();
11832   auto PtrVT = getPointerTy(DAG.getDataLayout());
11833   SDValue Result;
11834   if (OpFlags == X86II::MO_NO_FLAG &&
11835       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11836     // A direct static reference to a global.
11837     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11838     Offset = 0;
11839   } else {
11840     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11841   }
11842
11843   if (Subtarget->isPICStyleRIPRel() &&
11844       (M == CodeModel::Small || M == CodeModel::Kernel))
11845     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11846   else
11847     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11848
11849   // With PIC, the address is actually $g + Offset.
11850   if (isGlobalRelativeToPICBase(OpFlags)) {
11851     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11852                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11853   }
11854
11855   // For globals that require a load from a stub to get the address, emit the
11856   // load.
11857   if (isGlobalStubReference(OpFlags))
11858     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11859                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11860                          false, false, false, 0);
11861
11862   // If there was a non-zero offset that we didn't fold, create an explicit
11863   // addition for it.
11864   if (Offset != 0)
11865     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11866                          DAG.getConstant(Offset, dl, PtrVT));
11867
11868   return Result;
11869 }
11870
11871 SDValue
11872 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11873   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11874   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11875   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11876 }
11877
11878 static SDValue
11879 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11880            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11881            unsigned char OperandFlags, bool LocalDynamic = false) {
11882   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11883   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11884   SDLoc dl(GA);
11885   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11886                                            GA->getValueType(0),
11887                                            GA->getOffset(),
11888                                            OperandFlags);
11889
11890   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11891                                            : X86ISD::TLSADDR;
11892
11893   if (InFlag) {
11894     SDValue Ops[] = { Chain,  TGA, *InFlag };
11895     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11896   } else {
11897     SDValue Ops[]  = { Chain, TGA };
11898     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11899   }
11900
11901   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11902   MFI->setAdjustsStack(true);
11903   MFI->setHasCalls(true);
11904
11905   SDValue Flag = Chain.getValue(1);
11906   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11907 }
11908
11909 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11910 static SDValue
11911 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11912                                 const EVT PtrVT) {
11913   SDValue InFlag;
11914   SDLoc dl(GA);  // ? function entry point might be better
11915   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11916                                    DAG.getNode(X86ISD::GlobalBaseReg,
11917                                                SDLoc(), PtrVT), InFlag);
11918   InFlag = Chain.getValue(1);
11919
11920   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11921 }
11922
11923 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11924 static SDValue
11925 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11926                                 const EVT PtrVT) {
11927   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11928                     X86::RAX, X86II::MO_TLSGD);
11929 }
11930
11931 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11932                                            SelectionDAG &DAG,
11933                                            const EVT PtrVT,
11934                                            bool is64Bit) {
11935   SDLoc dl(GA);
11936
11937   // Get the start address of the TLS block for this module.
11938   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11939       .getInfo<X86MachineFunctionInfo>();
11940   MFI->incNumLocalDynamicTLSAccesses();
11941
11942   SDValue Base;
11943   if (is64Bit) {
11944     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11945                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11946   } else {
11947     SDValue InFlag;
11948     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11949         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11950     InFlag = Chain.getValue(1);
11951     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11952                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11953   }
11954
11955   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11956   // of Base.
11957
11958   // Build x@dtpoff.
11959   unsigned char OperandFlags = X86II::MO_DTPOFF;
11960   unsigned WrapperKind = X86ISD::Wrapper;
11961   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11962                                            GA->getValueType(0),
11963                                            GA->getOffset(), OperandFlags);
11964   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11965
11966   // Add x@dtpoff with the base.
11967   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11968 }
11969
11970 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11971 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11972                                    const EVT PtrVT, TLSModel::Model model,
11973                                    bool is64Bit, bool isPIC) {
11974   SDLoc dl(GA);
11975
11976   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11977   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11978                                                          is64Bit ? 257 : 256));
11979
11980   SDValue ThreadPointer =
11981       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11982                   MachinePointerInfo(Ptr), false, false, false, 0);
11983
11984   unsigned char OperandFlags = 0;
11985   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11986   // initialexec.
11987   unsigned WrapperKind = X86ISD::Wrapper;
11988   if (model == TLSModel::LocalExec) {
11989     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11990   } else if (model == TLSModel::InitialExec) {
11991     if (is64Bit) {
11992       OperandFlags = X86II::MO_GOTTPOFF;
11993       WrapperKind = X86ISD::WrapperRIP;
11994     } else {
11995       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11996     }
11997   } else {
11998     llvm_unreachable("Unexpected model");
11999   }
12000
12001   // emit "addl x@ntpoff,%eax" (local exec)
12002   // or "addl x@indntpoff,%eax" (initial exec)
12003   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12004   SDValue TGA =
12005       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12006                                  GA->getOffset(), OperandFlags);
12007   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12008
12009   if (model == TLSModel::InitialExec) {
12010     if (isPIC && !is64Bit) {
12011       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12012                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12013                            Offset);
12014     }
12015
12016     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12017                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12018                          false, false, false, 0);
12019   }
12020
12021   // The address of the thread local variable is the add of the thread
12022   // pointer with the offset of the variable.
12023   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12024 }
12025
12026 SDValue
12027 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12028
12029   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12030   const GlobalValue *GV = GA->getGlobal();
12031   auto PtrVT = getPointerTy(DAG.getDataLayout());
12032
12033   if (Subtarget->isTargetELF()) {
12034     if (DAG.getTarget().Options.EmulatedTLS)
12035       return LowerToTLSEmulatedModel(GA, DAG);
12036     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12037     switch (model) {
12038       case TLSModel::GeneralDynamic:
12039         if (Subtarget->is64Bit())
12040           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12041         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12042       case TLSModel::LocalDynamic:
12043         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12044                                            Subtarget->is64Bit());
12045       case TLSModel::InitialExec:
12046       case TLSModel::LocalExec:
12047         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12048                                    DAG.getTarget().getRelocationModel() ==
12049                                        Reloc::PIC_);
12050     }
12051     llvm_unreachable("Unknown TLS model.");
12052   }
12053
12054   if (Subtarget->isTargetDarwin()) {
12055     // Darwin only has one model of TLS.  Lower to that.
12056     unsigned char OpFlag = 0;
12057     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12058                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12059
12060     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12061     // global base reg.
12062     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12063                  !Subtarget->is64Bit();
12064     if (PIC32)
12065       OpFlag = X86II::MO_TLVP_PIC_BASE;
12066     else
12067       OpFlag = X86II::MO_TLVP;
12068     SDLoc DL(Op);
12069     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12070                                                 GA->getValueType(0),
12071                                                 GA->getOffset(), OpFlag);
12072     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12073
12074     // With PIC32, the address is actually $g + Offset.
12075     if (PIC32)
12076       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12077                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12078                            Offset);
12079
12080     // Lowering the machine isd will make sure everything is in the right
12081     // location.
12082     SDValue Chain = DAG.getEntryNode();
12083     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12084     SDValue Args[] = { Chain, Offset };
12085     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12086
12087     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12088     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12089     MFI->setAdjustsStack(true);
12090
12091     // And our return value (tls address) is in the standard call return value
12092     // location.
12093     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12094     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12095   }
12096
12097   if (Subtarget->isTargetKnownWindowsMSVC() ||
12098       Subtarget->isTargetWindowsGNU()) {
12099     // Just use the implicit TLS architecture
12100     // Need to generate someting similar to:
12101     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12102     //                                  ; from TEB
12103     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12104     //   mov     rcx, qword [rdx+rcx*8]
12105     //   mov     eax, .tls$:tlsvar
12106     //   [rax+rcx] contains the address
12107     // Windows 64bit: gs:0x58
12108     // Windows 32bit: fs:__tls_array
12109
12110     SDLoc dl(GA);
12111     SDValue Chain = DAG.getEntryNode();
12112
12113     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12114     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12115     // use its literal value of 0x2C.
12116     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12117                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12118                                                              256)
12119                                         : Type::getInt32PtrTy(*DAG.getContext(),
12120                                                               257));
12121
12122     SDValue TlsArray = Subtarget->is64Bit()
12123                            ? DAG.getIntPtrConstant(0x58, dl)
12124                            : (Subtarget->isTargetWindowsGNU()
12125                                   ? DAG.getIntPtrConstant(0x2C, dl)
12126                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12127
12128     SDValue ThreadPointer =
12129         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12130                     false, false, 0);
12131
12132     SDValue res;
12133     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12134       res = ThreadPointer;
12135     } else {
12136       // Load the _tls_index variable
12137       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12138       if (Subtarget->is64Bit())
12139         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12140                              MachinePointerInfo(), MVT::i32, false, false,
12141                              false, 0);
12142       else
12143         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12144                           false, false, 0);
12145
12146       auto &DL = DAG.getDataLayout();
12147       SDValue Scale =
12148           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12149       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12150
12151       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12152     }
12153
12154     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12155                       false, 0);
12156
12157     // Get the offset of start of .tls section
12158     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12159                                              GA->getValueType(0),
12160                                              GA->getOffset(), X86II::MO_SECREL);
12161     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12162
12163     // The address of the thread local variable is the add of the thread
12164     // pointer with the offset of the variable.
12165     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12166   }
12167
12168   llvm_unreachable("TLS not implemented for this target.");
12169 }
12170
12171 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12172 /// and take a 2 x i32 value to shift plus a shift amount.
12173 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12174   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12175   MVT VT = Op.getSimpleValueType();
12176   unsigned VTBits = VT.getSizeInBits();
12177   SDLoc dl(Op);
12178   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12179   SDValue ShOpLo = Op.getOperand(0);
12180   SDValue ShOpHi = Op.getOperand(1);
12181   SDValue ShAmt  = Op.getOperand(2);
12182   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12183   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12184   // during isel.
12185   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12186                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12187   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12188                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12189                        : DAG.getConstant(0, dl, VT);
12190
12191   SDValue Tmp2, Tmp3;
12192   if (Op.getOpcode() == ISD::SHL_PARTS) {
12193     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12194     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12195   } else {
12196     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12197     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12198   }
12199
12200   // If the shift amount is larger or equal than the width of a part we can't
12201   // rely on the results of shld/shrd. Insert a test and select the appropriate
12202   // values for large shift amounts.
12203   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12204                                 DAG.getConstant(VTBits, dl, MVT::i8));
12205   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12206                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12207
12208   SDValue Hi, Lo;
12209   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12210   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12211   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12212
12213   if (Op.getOpcode() == ISD::SHL_PARTS) {
12214     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12215     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12216   } else {
12217     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12218     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12219   }
12220
12221   SDValue Ops[2] = { Lo, Hi };
12222   return DAG.getMergeValues(Ops, dl);
12223 }
12224
12225 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12226                                            SelectionDAG &DAG) const {
12227   SDValue Src = Op.getOperand(0);
12228   MVT SrcVT = Src.getSimpleValueType();
12229   MVT VT = Op.getSimpleValueType();
12230   SDLoc dl(Op);
12231
12232   if (SrcVT.isVector()) {
12233     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12234       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12235                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12236                          DAG.getUNDEF(SrcVT)));
12237     }
12238     if (SrcVT.getVectorElementType() == MVT::i1) {
12239       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12240       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12241                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12242     }
12243     return SDValue();
12244   }
12245
12246   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12247          "Unknown SINT_TO_FP to lower!");
12248
12249   // These are really Legal; return the operand so the caller accepts it as
12250   // Legal.
12251   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12252     return Op;
12253   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12254       Subtarget->is64Bit()) {
12255     return Op;
12256   }
12257
12258   unsigned Size = SrcVT.getSizeInBits()/8;
12259   MachineFunction &MF = DAG.getMachineFunction();
12260   auto PtrVT = getPointerTy(MF.getDataLayout());
12261   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12262   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12263   SDValue Chain = DAG.getStore(
12264       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12265       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12266       false, 0);
12267   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12268 }
12269
12270 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12271                                      SDValue StackSlot,
12272                                      SelectionDAG &DAG) const {
12273   // Build the FILD
12274   SDLoc DL(Op);
12275   SDVTList Tys;
12276   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12277   if (useSSE)
12278     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12279   else
12280     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12281
12282   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12283
12284   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12285   MachineMemOperand *MMO;
12286   if (FI) {
12287     int SSFI = FI->getIndex();
12288     MMO = DAG.getMachineFunction().getMachineMemOperand(
12289         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12290         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12291   } else {
12292     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12293     StackSlot = StackSlot.getOperand(1);
12294   }
12295   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12296   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12297                                            X86ISD::FILD, DL,
12298                                            Tys, Ops, SrcVT, MMO);
12299
12300   if (useSSE) {
12301     Chain = Result.getValue(1);
12302     SDValue InFlag = Result.getValue(2);
12303
12304     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12305     // shouldn't be necessary except that RFP cannot be live across
12306     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12307     MachineFunction &MF = DAG.getMachineFunction();
12308     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12309     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12310     auto PtrVT = getPointerTy(MF.getDataLayout());
12311     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12312     Tys = DAG.getVTList(MVT::Other);
12313     SDValue Ops[] = {
12314       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12315     };
12316     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12317         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12318         MachineMemOperand::MOStore, SSFISize, SSFISize);
12319
12320     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12321                                     Ops, Op.getValueType(), MMO);
12322     Result = DAG.getLoad(
12323         Op.getValueType(), DL, Chain, StackSlot,
12324         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12325         false, false, false, 0);
12326   }
12327
12328   return Result;
12329 }
12330
12331 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12332 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12333                                                SelectionDAG &DAG) const {
12334   // This algorithm is not obvious. Here it is what we're trying to output:
12335   /*
12336      movq       %rax,  %xmm0
12337      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12338      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12339      #ifdef __SSE3__
12340        haddpd   %xmm0, %xmm0
12341      #else
12342        pshufd   $0x4e, %xmm0, %xmm1
12343        addpd    %xmm1, %xmm0
12344      #endif
12345   */
12346
12347   SDLoc dl(Op);
12348   LLVMContext *Context = DAG.getContext();
12349
12350   // Build some magic constants.
12351   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12352   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12353   auto PtrVT = getPointerTy(DAG.getDataLayout());
12354   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12355
12356   SmallVector<Constant*,2> CV1;
12357   CV1.push_back(
12358     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12359                                       APInt(64, 0x4330000000000000ULL))));
12360   CV1.push_back(
12361     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12362                                       APInt(64, 0x4530000000000000ULL))));
12363   Constant *C1 = ConstantVector::get(CV1);
12364   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12365
12366   // Load the 64-bit value into an XMM register.
12367   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12368                             Op.getOperand(0));
12369   SDValue CLod0 =
12370       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12371                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12372                   false, false, false, 16);
12373   SDValue Unpck1 =
12374       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12375
12376   SDValue CLod1 =
12377       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12378                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12379                   false, false, false, 16);
12380   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12381   // TODO: Are there any fast-math-flags to propagate here?
12382   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12383   SDValue Result;
12384
12385   if (Subtarget->hasSSE3()) {
12386     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12387     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12388   } else {
12389     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12390     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12391                                            S2F, 0x4E, DAG);
12392     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12393                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12394   }
12395
12396   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12397                      DAG.getIntPtrConstant(0, dl));
12398 }
12399
12400 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12401 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12402                                                SelectionDAG &DAG) const {
12403   SDLoc dl(Op);
12404   // FP constant to bias correct the final result.
12405   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12406                                    MVT::f64);
12407
12408   // Load the 32-bit value into an XMM register.
12409   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12410                              Op.getOperand(0));
12411
12412   // Zero out the upper parts of the register.
12413   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12414
12415   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12416                      DAG.getBitcast(MVT::v2f64, Load),
12417                      DAG.getIntPtrConstant(0, dl));
12418
12419   // Or the load with the bias.
12420   SDValue Or = DAG.getNode(
12421       ISD::OR, dl, MVT::v2i64,
12422       DAG.getBitcast(MVT::v2i64,
12423                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12424       DAG.getBitcast(MVT::v2i64,
12425                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12426   Or =
12427       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12428                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12429
12430   // Subtract the bias.
12431   // TODO: Are there any fast-math-flags to propagate here?
12432   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12433
12434   // Handle final rounding.
12435   EVT DestVT = Op.getValueType();
12436
12437   if (DestVT.bitsLT(MVT::f64))
12438     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12439                        DAG.getIntPtrConstant(0, dl));
12440   if (DestVT.bitsGT(MVT::f64))
12441     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12442
12443   // Handle final rounding.
12444   return Sub;
12445 }
12446
12447 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12448                                      const X86Subtarget &Subtarget) {
12449   // The algorithm is the following:
12450   // #ifdef __SSE4_1__
12451   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12452   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12453   //                                 (uint4) 0x53000000, 0xaa);
12454   // #else
12455   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12456   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12457   // #endif
12458   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12459   //     return (float4) lo + fhi;
12460
12461   SDLoc DL(Op);
12462   SDValue V = Op->getOperand(0);
12463   EVT VecIntVT = V.getValueType();
12464   bool Is128 = VecIntVT == MVT::v4i32;
12465   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12466   // If we convert to something else than the supported type, e.g., to v4f64,
12467   // abort early.
12468   if (VecFloatVT != Op->getValueType(0))
12469     return SDValue();
12470
12471   unsigned NumElts = VecIntVT.getVectorNumElements();
12472   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12473          "Unsupported custom type");
12474   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12475
12476   // In the #idef/#else code, we have in common:
12477   // - The vector of constants:
12478   // -- 0x4b000000
12479   // -- 0x53000000
12480   // - A shift:
12481   // -- v >> 16
12482
12483   // Create the splat vector for 0x4b000000.
12484   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12485   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12486                            CstLow, CstLow, CstLow, CstLow};
12487   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12488                                   makeArrayRef(&CstLowArray[0], NumElts));
12489   // Create the splat vector for 0x53000000.
12490   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12491   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12492                             CstHigh, CstHigh, CstHigh, CstHigh};
12493   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12494                                    makeArrayRef(&CstHighArray[0], NumElts));
12495
12496   // Create the right shift.
12497   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12498   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12499                              CstShift, CstShift, CstShift, CstShift};
12500   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12501                                     makeArrayRef(&CstShiftArray[0], NumElts));
12502   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12503
12504   SDValue Low, High;
12505   if (Subtarget.hasSSE41()) {
12506     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12507     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12508     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12509     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12510     // Low will be bitcasted right away, so do not bother bitcasting back to its
12511     // original type.
12512     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12513                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12514     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12515     //                                 (uint4) 0x53000000, 0xaa);
12516     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12517     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12518     // High will be bitcasted right away, so do not bother bitcasting back to
12519     // its original type.
12520     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12521                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12522   } else {
12523     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12524     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12525                                      CstMask, CstMask, CstMask);
12526     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12527     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12528     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12529
12530     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12531     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12532   }
12533
12534   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12535   SDValue CstFAdd = DAG.getConstantFP(
12536       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12537   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12538                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12539   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12540                                    makeArrayRef(&CstFAddArray[0], NumElts));
12541
12542   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12543   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12544   // TODO: Are there any fast-math-flags to propagate here?
12545   SDValue FHigh =
12546       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12547   //     return (float4) lo + fhi;
12548   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12549   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12550 }
12551
12552 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12553                                                SelectionDAG &DAG) const {
12554   SDValue N0 = Op.getOperand(0);
12555   MVT SVT = N0.getSimpleValueType();
12556   SDLoc dl(Op);
12557
12558   switch (SVT.SimpleTy) {
12559   default:
12560     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12561   case MVT::v4i8:
12562   case MVT::v4i16:
12563   case MVT::v8i8:
12564   case MVT::v8i16: {
12565     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12566     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12567                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12568   }
12569   case MVT::v4i32:
12570   case MVT::v8i32:
12571     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12572   case MVT::v16i8:
12573   case MVT::v16i16:
12574     if (Subtarget->hasAVX512())
12575       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12576                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12577   }
12578   llvm_unreachable(nullptr);
12579 }
12580
12581 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12582                                            SelectionDAG &DAG) const {
12583   SDValue N0 = Op.getOperand(0);
12584   SDLoc dl(Op);
12585   auto PtrVT = getPointerTy(DAG.getDataLayout());
12586
12587   if (Op.getValueType().isVector())
12588     return lowerUINT_TO_FP_vec(Op, DAG);
12589
12590   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12591   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12592   // the optimization here.
12593   if (DAG.SignBitIsZero(N0))
12594     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12595
12596   MVT SrcVT = N0.getSimpleValueType();
12597   MVT DstVT = Op.getSimpleValueType();
12598
12599   if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
12600       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
12601     // Conversions from unsigned i32 to f32/f64 are legal,
12602     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
12603     return Op;
12604   }
12605
12606   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12607     return LowerUINT_TO_FP_i64(Op, DAG);
12608   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12609     return LowerUINT_TO_FP_i32(Op, DAG);
12610   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12611     return SDValue();
12612
12613   // Make a 64-bit buffer, and use it to build an FILD.
12614   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12615   if (SrcVT == MVT::i32) {
12616     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12617     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12618     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12619                                   StackSlot, MachinePointerInfo(),
12620                                   false, false, 0);
12621     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12622                                   OffsetSlot, MachinePointerInfo(),
12623                                   false, false, 0);
12624     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12625     return Fild;
12626   }
12627
12628   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12629   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12630                                StackSlot, MachinePointerInfo(),
12631                                false, false, 0);
12632   // For i64 source, we need to add the appropriate power of 2 if the input
12633   // was negative.  This is the same as the optimization in
12634   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12635   // we must be careful to do the computation in x87 extended precision, not
12636   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12637   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12638   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12639       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12640       MachineMemOperand::MOLoad, 8, 8);
12641
12642   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12643   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12644   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12645                                          MVT::i64, MMO);
12646
12647   APInt FF(32, 0x5F800000ULL);
12648
12649   // Check whether the sign bit is set.
12650   SDValue SignSet = DAG.getSetCC(
12651       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12652       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12653
12654   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12655   SDValue FudgePtr = DAG.getConstantPool(
12656       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12657
12658   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12659   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12660   SDValue Four = DAG.getIntPtrConstant(4, dl);
12661   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12662                                Zero, Four);
12663   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12664
12665   // Load the value out, extending it from f32 to f80.
12666   // FIXME: Avoid the extend by constructing the right constant pool?
12667   SDValue Fudge = DAG.getExtLoad(
12668       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12669       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12670       false, false, false, 4);
12671   // Extend everything to 80 bits to force it to be done on x87.
12672   // TODO: Are there any fast-math-flags to propagate here?
12673   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12674   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12675                      DAG.getIntPtrConstant(0, dl));
12676 }
12677
12678 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12679 // is legal, or has an f16 source (which needs to be promoted to f32),
12680 // just return an <SDValue(), SDValue()> pair.
12681 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12682 // to i16, i32 or i64, and we lower it to a legal sequence.
12683 // If lowered to the final integer result we return a <result, SDValue()> pair.
12684 // Otherwise we lower it to a sequence ending with a FIST, return a
12685 // <FIST, StackSlot> pair, and the caller is responsible for loading
12686 // the final integer result from StackSlot.
12687 std::pair<SDValue,SDValue>
12688 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12689                                    bool IsSigned, bool IsReplace) const {
12690   SDLoc DL(Op);
12691
12692   EVT DstTy = Op.getValueType();
12693   EVT TheVT = Op.getOperand(0).getValueType();
12694   auto PtrVT = getPointerTy(DAG.getDataLayout());
12695
12696   if (TheVT == MVT::f16)
12697     // We need to promote the f16 to f32 before using the lowering
12698     // in this routine.
12699     return std::make_pair(SDValue(), SDValue());
12700
12701   assert((TheVT == MVT::f32 ||
12702           TheVT == MVT::f64 ||
12703           TheVT == MVT::f80) &&
12704          "Unexpected FP operand type in FP_TO_INTHelper");
12705
12706   // If using FIST to compute an unsigned i64, we'll need some fixup
12707   // to handle values above the maximum signed i64.  A FIST is always
12708   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12709   bool UnsignedFixup = !IsSigned &&
12710                        DstTy == MVT::i64 &&
12711                        (!Subtarget->is64Bit() ||
12712                         !isScalarFPTypeInSSEReg(TheVT));
12713
12714   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12715     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12716     // The low 32 bits of the fist result will have the correct uint32 result.
12717     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12718     DstTy = MVT::i64;
12719   }
12720
12721   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12722          DstTy.getSimpleVT() >= MVT::i16 &&
12723          "Unknown FP_TO_INT to lower!");
12724
12725   // These are really Legal.
12726   if (DstTy == MVT::i32 &&
12727       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12728     return std::make_pair(SDValue(), SDValue());
12729   if (Subtarget->is64Bit() &&
12730       DstTy == MVT::i64 &&
12731       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12732     return std::make_pair(SDValue(), SDValue());
12733
12734   // We lower FP->int64 into FISTP64 followed by a load from a temporary
12735   // stack slot.
12736   MachineFunction &MF = DAG.getMachineFunction();
12737   unsigned MemSize = DstTy.getSizeInBits()/8;
12738   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12739   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12740
12741   unsigned Opc;
12742   switch (DstTy.getSimpleVT().SimpleTy) {
12743   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12744   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12745   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12746   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12747   }
12748
12749   SDValue Chain = DAG.getEntryNode();
12750   SDValue Value = Op.getOperand(0);
12751   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12752
12753   if (UnsignedFixup) {
12754     //
12755     // Conversion to unsigned i64 is implemented with a select,
12756     // depending on whether the source value fits in the range
12757     // of a signed i64.  Let Thresh be the FP equivalent of
12758     // 0x8000000000000000ULL.
12759     //
12760     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12761     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
12762     //  Fist-to-mem64 FistSrc
12763     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12764     //  to XOR'ing the high 32 bits with Adjust.
12765     //
12766     // Being a power of 2, Thresh is exactly representable in all FP formats.
12767     // For X87 we'd like to use the smallest FP type for this constant, but
12768     // for DAG type consistency we have to match the FP operand type.
12769
12770     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12771     APFloat::opStatus Status = APFloat::opOK;
12772     bool LosesInfo = false;
12773     if (TheVT == MVT::f64)
12774       // The rounding mode is irrelevant as the conversion should be exact.
12775       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12776                               &LosesInfo);
12777     else if (TheVT == MVT::f80)
12778       Status = Thresh.convert(APFloat::x87DoubleExtended,
12779                               APFloat::rmNearestTiesToEven, &LosesInfo);
12780
12781     assert(Status == APFloat::opOK && !LosesInfo &&
12782            "FP conversion should have been exact");
12783
12784     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12785
12786     SDValue Cmp = DAG.getSetCC(DL,
12787                                getSetCCResultType(DAG.getDataLayout(),
12788                                                   *DAG.getContext(), TheVT),
12789                                Value, ThreshVal, ISD::SETLT);
12790     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12791                            DAG.getConstant(0, DL, MVT::i32),
12792                            DAG.getConstant(0x80000000, DL, MVT::i32));
12793     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12794     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12795                                               *DAG.getContext(), TheVT),
12796                        Value, ThreshVal, ISD::SETLT);
12797     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12798   }
12799
12800   // FIXME This causes a redundant load/store if the SSE-class value is already
12801   // in memory, such as if it is on the callstack.
12802   if (isScalarFPTypeInSSEReg(TheVT)) {
12803     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12804     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12805                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12806                          false, 0);
12807     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12808     SDValue Ops[] = {
12809       Chain, StackSlot, DAG.getValueType(TheVT)
12810     };
12811
12812     MachineMemOperand *MMO =
12813         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12814                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12815     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12816     Chain = Value.getValue(1);
12817     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12818     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12819   }
12820
12821   MachineMemOperand *MMO =
12822       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12823                               MachineMemOperand::MOStore, MemSize, MemSize);
12824
12825   if (UnsignedFixup) {
12826
12827     // Insert the FIST, load its result as two i32's,
12828     // and XOR the high i32 with Adjust.
12829
12830     SDValue FistOps[] = { Chain, Value, StackSlot };
12831     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12832                                            FistOps, DstTy, MMO);
12833
12834     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12835                                 MachinePointerInfo(),
12836                                 false, false, false, 0);
12837     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12838                                    DAG.getConstant(4, DL, PtrVT));
12839
12840     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12841                                  MachinePointerInfo(),
12842                                  false, false, false, 0);
12843     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12844
12845     if (Subtarget->is64Bit()) {
12846       // Join High32 and Low32 into a 64-bit result.
12847       // (High32 << 32) | Low32
12848       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12849       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12850       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12851                            DAG.getConstant(32, DL, MVT::i8));
12852       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12853       return std::make_pair(Result, SDValue());
12854     }
12855
12856     SDValue ResultOps[] = { Low32, High32 };
12857
12858     SDValue pair = IsReplace
12859       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12860       : DAG.getMergeValues(ResultOps, DL);
12861     return std::make_pair(pair, SDValue());
12862   } else {
12863     // Build the FP_TO_INT*_IN_MEM
12864     SDValue Ops[] = { Chain, Value, StackSlot };
12865     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12866                                            Ops, DstTy, MMO);
12867     return std::make_pair(FIST, StackSlot);
12868   }
12869 }
12870
12871 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12872                               const X86Subtarget *Subtarget) {
12873   MVT VT = Op->getSimpleValueType(0);
12874   SDValue In = Op->getOperand(0);
12875   MVT InVT = In.getSimpleValueType();
12876   SDLoc dl(Op);
12877
12878   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12879     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12880
12881   // Optimize vectors in AVX mode:
12882   //
12883   //   v8i16 -> v8i32
12884   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12885   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12886   //   Concat upper and lower parts.
12887   //
12888   //   v4i32 -> v4i64
12889   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12890   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12891   //   Concat upper and lower parts.
12892   //
12893
12894   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12895       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12896       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12897     return SDValue();
12898
12899   if (Subtarget->hasInt256())
12900     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12901
12902   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12903   SDValue Undef = DAG.getUNDEF(InVT);
12904   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12905   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12906   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12907
12908   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12909                              VT.getVectorNumElements()/2);
12910
12911   OpLo = DAG.getBitcast(HVT, OpLo);
12912   OpHi = DAG.getBitcast(HVT, OpHi);
12913
12914   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12915 }
12916
12917 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12918                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12919   MVT VT = Op->getSimpleValueType(0);
12920   SDValue In = Op->getOperand(0);
12921   MVT InVT = In.getSimpleValueType();
12922   SDLoc DL(Op);
12923   unsigned int NumElts = VT.getVectorNumElements();
12924   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12925     return SDValue();
12926
12927   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12928     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12929
12930   assert(InVT.getVectorElementType() == MVT::i1);
12931   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12932   SDValue One =
12933    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12934   SDValue Zero =
12935    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12936
12937   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12938   if (VT.is512BitVector())
12939     return V;
12940   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12941 }
12942
12943 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12944                                SelectionDAG &DAG) {
12945   if (Subtarget->hasFp256())
12946     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12947       return Res;
12948
12949   return SDValue();
12950 }
12951
12952 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12953                                 SelectionDAG &DAG) {
12954   SDLoc DL(Op);
12955   MVT VT = Op.getSimpleValueType();
12956   SDValue In = Op.getOperand(0);
12957   MVT SVT = In.getSimpleValueType();
12958
12959   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12960     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12961
12962   if (Subtarget->hasFp256())
12963     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12964       return Res;
12965
12966   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12967          VT.getVectorNumElements() != SVT.getVectorNumElements());
12968   return SDValue();
12969 }
12970
12971 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12972   SDLoc DL(Op);
12973   MVT VT = Op.getSimpleValueType();
12974   SDValue In = Op.getOperand(0);
12975   MVT InVT = In.getSimpleValueType();
12976
12977   if (VT == MVT::i1) {
12978     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12979            "Invalid scalar TRUNCATE operation");
12980     if (InVT.getSizeInBits() >= 32)
12981       return SDValue();
12982     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12983     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12984   }
12985   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12986          "Invalid TRUNCATE operation");
12987
12988   // move vector to mask - truncate solution for SKX
12989   if (VT.getVectorElementType() == MVT::i1) {
12990     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12991         Subtarget->hasBWI())
12992       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12993     if ((InVT.is256BitVector() || InVT.is128BitVector())
12994         && InVT.getScalarSizeInBits() <= 16 &&
12995         Subtarget->hasBWI() && Subtarget->hasVLX())
12996       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12997     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12998         Subtarget->hasDQI())
12999       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
13000     if ((InVT.is256BitVector() || InVT.is128BitVector())
13001         && InVT.getScalarSizeInBits() >= 32 &&
13002         Subtarget->hasDQI() && Subtarget->hasVLX())
13003       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
13004   }
13005
13006   if (VT.getVectorElementType() == MVT::i1) {
13007     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13008     unsigned NumElts = InVT.getVectorNumElements();
13009     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
13010     if (InVT.getSizeInBits() < 512) {
13011       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
13012       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13013       InVT = ExtVT;
13014     }
13015
13016     SDValue OneV =
13017      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
13018     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
13019     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
13020   }
13021
13022   // vpmovqb/w/d, vpmovdb/w, vpmovwb
13023   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
13024       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
13025     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13026
13027   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13028     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13029     if (Subtarget->hasInt256()) {
13030       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13031       In = DAG.getBitcast(MVT::v8i32, In);
13032       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13033                                 ShufMask);
13034       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13035                          DAG.getIntPtrConstant(0, DL));
13036     }
13037
13038     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13039                                DAG.getIntPtrConstant(0, DL));
13040     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13041                                DAG.getIntPtrConstant(2, DL));
13042     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13043     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13044     static const int ShufMask[] = {0, 2, 4, 6};
13045     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13046   }
13047
13048   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13049     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13050     if (Subtarget->hasInt256()) {
13051       In = DAG.getBitcast(MVT::v32i8, In);
13052
13053       SmallVector<SDValue,32> pshufbMask;
13054       for (unsigned i = 0; i < 2; ++i) {
13055         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13056         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13057         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13058         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13059         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13060         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13061         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13062         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13063         for (unsigned j = 0; j < 8; ++j)
13064           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13065       }
13066       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13067       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13068       In = DAG.getBitcast(MVT::v4i64, In);
13069
13070       static const int ShufMask[] = {0,  2,  -1,  -1};
13071       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13072                                 &ShufMask[0]);
13073       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13074                        DAG.getIntPtrConstant(0, DL));
13075       return DAG.getBitcast(VT, In);
13076     }
13077
13078     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13079                                DAG.getIntPtrConstant(0, DL));
13080
13081     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13082                                DAG.getIntPtrConstant(4, DL));
13083
13084     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13085     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13086
13087     // The PSHUFB mask:
13088     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13089                                    -1, -1, -1, -1, -1, -1, -1, -1};
13090
13091     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13092     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13093     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13094
13095     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13096     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13097
13098     // The MOVLHPS Mask:
13099     static const int ShufMask2[] = {0, 1, 4, 5};
13100     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13101     return DAG.getBitcast(MVT::v8i16, res);
13102   }
13103
13104   // Handle truncation of V256 to V128 using shuffles.
13105   if (!VT.is128BitVector() || !InVT.is256BitVector())
13106     return SDValue();
13107
13108   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13109
13110   unsigned NumElems = VT.getVectorNumElements();
13111   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13112
13113   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13114   // Prepare truncation shuffle mask
13115   for (unsigned i = 0; i != NumElems; ++i)
13116     MaskVec[i] = i * 2;
13117   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13118                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13119   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13120                      DAG.getIntPtrConstant(0, DL));
13121 }
13122
13123 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13124                                            SelectionDAG &DAG) const {
13125   assert(!Op.getSimpleValueType().isVector());
13126
13127   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13128     /*IsSigned=*/ true, /*IsReplace=*/ false);
13129   SDValue FIST = Vals.first, StackSlot = Vals.second;
13130   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13131   if (!FIST.getNode())
13132     return Op;
13133
13134   if (StackSlot.getNode())
13135     // Load the result.
13136     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13137                        FIST, StackSlot, MachinePointerInfo(),
13138                        false, false, false, 0);
13139
13140   // The node is the result.
13141   return FIST;
13142 }
13143
13144 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13145                                            SelectionDAG &DAG) const {
13146   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13147     /*IsSigned=*/ false, /*IsReplace=*/ false);
13148   SDValue FIST = Vals.first, StackSlot = Vals.second;
13149   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13150   if (!FIST.getNode())
13151     return Op;
13152
13153   if (StackSlot.getNode())
13154     // Load the result.
13155     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13156                        FIST, StackSlot, MachinePointerInfo(),
13157                        false, false, false, 0);
13158
13159   // The node is the result.
13160   return FIST;
13161 }
13162
13163 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13164   SDLoc DL(Op);
13165   MVT VT = Op.getSimpleValueType();
13166   SDValue In = Op.getOperand(0);
13167   MVT SVT = In.getSimpleValueType();
13168
13169   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13170
13171   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13172                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13173                                  In, DAG.getUNDEF(SVT)));
13174 }
13175
13176 /// The only differences between FABS and FNEG are the mask and the logic op.
13177 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13178 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13179   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13180          "Wrong opcode for lowering FABS or FNEG.");
13181
13182   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13183
13184   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13185   // into an FNABS. We'll lower the FABS after that if it is still in use.
13186   if (IsFABS)
13187     for (SDNode *User : Op->uses())
13188       if (User->getOpcode() == ISD::FNEG)
13189         return Op;
13190
13191   SDLoc dl(Op);
13192   MVT VT = Op.getSimpleValueType();
13193
13194   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13195   // decide if we should generate a 16-byte constant mask when we only need 4 or
13196   // 8 bytes for the scalar case.
13197
13198   MVT LogicVT;
13199   MVT EltVT;
13200   unsigned NumElts;
13201
13202   if (VT.isVector()) {
13203     LogicVT = VT;
13204     EltVT = VT.getVectorElementType();
13205     NumElts = VT.getVectorNumElements();
13206   } else {
13207     // There are no scalar bitwise logical SSE/AVX instructions, so we
13208     // generate a 16-byte vector constant and logic op even for the scalar case.
13209     // Using a 16-byte mask allows folding the load of the mask with
13210     // the logic op, so it can save (~4 bytes) on code size.
13211     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13212     EltVT = VT;
13213     NumElts = (VT == MVT::f64) ? 2 : 4;
13214   }
13215
13216   unsigned EltBits = EltVT.getSizeInBits();
13217   LLVMContext *Context = DAG.getContext();
13218   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13219   APInt MaskElt =
13220     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13221   Constant *C = ConstantInt::get(*Context, MaskElt);
13222   C = ConstantVector::getSplat(NumElts, C);
13223   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13224   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13225   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13226   SDValue Mask =
13227       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13228                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13229                   false, false, false, Alignment);
13230
13231   SDValue Op0 = Op.getOperand(0);
13232   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13233   unsigned LogicOp =
13234     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13235   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13236
13237   if (VT.isVector())
13238     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13239
13240   // For the scalar case extend to a 128-bit vector, perform the logic op,
13241   // and extract the scalar result back out.
13242   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13243   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13244   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13245                      DAG.getIntPtrConstant(0, dl));
13246 }
13247
13248 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13249   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13250   LLVMContext *Context = DAG.getContext();
13251   SDValue Op0 = Op.getOperand(0);
13252   SDValue Op1 = Op.getOperand(1);
13253   SDLoc dl(Op);
13254   MVT VT = Op.getSimpleValueType();
13255   MVT SrcVT = Op1.getSimpleValueType();
13256
13257   // If second operand is smaller, extend it first.
13258   if (SrcVT.bitsLT(VT)) {
13259     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13260     SrcVT = VT;
13261   }
13262   // And if it is bigger, shrink it first.
13263   if (SrcVT.bitsGT(VT)) {
13264     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13265     SrcVT = VT;
13266   }
13267
13268   // At this point the operands and the result should have the same
13269   // type, and that won't be f80 since that is not custom lowered.
13270
13271   const fltSemantics &Sem =
13272       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
13273   const unsigned SizeInBits = VT.getSizeInBits();
13274
13275   SmallVector<Constant *, 4> CV(
13276       VT == MVT::f64 ? 2 : 4,
13277       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13278
13279   // First, clear all bits but the sign bit from the second operand (sign).
13280   CV[0] = ConstantFP::get(*Context,
13281                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13282   Constant *C = ConstantVector::get(CV);
13283   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13284   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13285
13286   // Perform all logic operations as 16-byte vectors because there are no
13287   // scalar FP logic instructions in SSE. This allows load folding of the
13288   // constants into the logic instructions.
13289   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13290   SDValue Mask1 =
13291       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13292                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13293                   false, false, false, 16);
13294   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13295   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13296
13297   // Next, clear the sign bit from the first operand (magnitude).
13298   // If it's a constant, we can clear it here.
13299   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13300     APFloat APF = Op0CN->getValueAPF();
13301     // If the magnitude is a positive zero, the sign bit alone is enough.
13302     if (APF.isPosZero())
13303       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13304                          DAG.getIntPtrConstant(0, dl));
13305     APF.clearSign();
13306     CV[0] = ConstantFP::get(*Context, APF);
13307   } else {
13308     CV[0] = ConstantFP::get(
13309         *Context,
13310         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13311   }
13312   C = ConstantVector::get(CV);
13313   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13314   SDValue Val =
13315       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13316                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13317                   false, false, false, 16);
13318   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13319   if (!isa<ConstantFPSDNode>(Op0)) {
13320     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13321     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13322   }
13323   // OR the magnitude value with the sign bit.
13324   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13325   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13326                      DAG.getIntPtrConstant(0, dl));
13327 }
13328
13329 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13330   SDValue N0 = Op.getOperand(0);
13331   SDLoc dl(Op);
13332   MVT VT = Op.getSimpleValueType();
13333
13334   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13335   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13336                                   DAG.getConstant(1, dl, VT));
13337   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13338 }
13339
13340 // Check whether an OR'd tree is PTEST-able.
13341 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13342                                       SelectionDAG &DAG) {
13343   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13344
13345   if (!Subtarget->hasSSE41())
13346     return SDValue();
13347
13348   if (!Op->hasOneUse())
13349     return SDValue();
13350
13351   SDNode *N = Op.getNode();
13352   SDLoc DL(N);
13353
13354   SmallVector<SDValue, 8> Opnds;
13355   DenseMap<SDValue, unsigned> VecInMap;
13356   SmallVector<SDValue, 8> VecIns;
13357   EVT VT = MVT::Other;
13358
13359   // Recognize a special case where a vector is casted into wide integer to
13360   // test all 0s.
13361   Opnds.push_back(N->getOperand(0));
13362   Opnds.push_back(N->getOperand(1));
13363
13364   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13365     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13366     // BFS traverse all OR'd operands.
13367     if (I->getOpcode() == ISD::OR) {
13368       Opnds.push_back(I->getOperand(0));
13369       Opnds.push_back(I->getOperand(1));
13370       // Re-evaluate the number of nodes to be traversed.
13371       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13372       continue;
13373     }
13374
13375     // Quit if a non-EXTRACT_VECTOR_ELT
13376     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13377       return SDValue();
13378
13379     // Quit if without a constant index.
13380     SDValue Idx = I->getOperand(1);
13381     if (!isa<ConstantSDNode>(Idx))
13382       return SDValue();
13383
13384     SDValue ExtractedFromVec = I->getOperand(0);
13385     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13386     if (M == VecInMap.end()) {
13387       VT = ExtractedFromVec.getValueType();
13388       // Quit if not 128/256-bit vector.
13389       if (!VT.is128BitVector() && !VT.is256BitVector())
13390         return SDValue();
13391       // Quit if not the same type.
13392       if (VecInMap.begin() != VecInMap.end() &&
13393           VT != VecInMap.begin()->first.getValueType())
13394         return SDValue();
13395       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13396       VecIns.push_back(ExtractedFromVec);
13397     }
13398     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13399   }
13400
13401   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13402          "Not extracted from 128-/256-bit vector.");
13403
13404   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13405
13406   for (DenseMap<SDValue, unsigned>::const_iterator
13407         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13408     // Quit if not all elements are used.
13409     if (I->second != FullMask)
13410       return SDValue();
13411   }
13412
13413   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13414
13415   // Cast all vectors into TestVT for PTEST.
13416   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13417     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13418
13419   // If more than one full vectors are evaluated, OR them first before PTEST.
13420   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13421     // Each iteration will OR 2 nodes and append the result until there is only
13422     // 1 node left, i.e. the final OR'd value of all vectors.
13423     SDValue LHS = VecIns[Slot];
13424     SDValue RHS = VecIns[Slot + 1];
13425     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13426   }
13427
13428   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13429                      VecIns.back(), VecIns.back());
13430 }
13431
13432 /// \brief return true if \c Op has a use that doesn't just read flags.
13433 static bool hasNonFlagsUse(SDValue Op) {
13434   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13435        ++UI) {
13436     SDNode *User = *UI;
13437     unsigned UOpNo = UI.getOperandNo();
13438     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13439       // Look pass truncate.
13440       UOpNo = User->use_begin().getOperandNo();
13441       User = *User->use_begin();
13442     }
13443
13444     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13445         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13446       return true;
13447   }
13448   return false;
13449 }
13450
13451 /// Emit nodes that will be selected as "test Op0,Op0", or something
13452 /// equivalent.
13453 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13454                                     SelectionDAG &DAG) const {
13455   if (Op.getValueType() == MVT::i1) {
13456     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13457     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13458                        DAG.getConstant(0, dl, MVT::i8));
13459   }
13460   // CF and OF aren't always set the way we want. Determine which
13461   // of these we need.
13462   bool NeedCF = false;
13463   bool NeedOF = false;
13464   switch (X86CC) {
13465   default: break;
13466   case X86::COND_A: case X86::COND_AE:
13467   case X86::COND_B: case X86::COND_BE:
13468     NeedCF = true;
13469     break;
13470   case X86::COND_G: case X86::COND_GE:
13471   case X86::COND_L: case X86::COND_LE:
13472   case X86::COND_O: case X86::COND_NO: {
13473     // Check if we really need to set the
13474     // Overflow flag. If NoSignedWrap is present
13475     // that is not actually needed.
13476     switch (Op->getOpcode()) {
13477     case ISD::ADD:
13478     case ISD::SUB:
13479     case ISD::MUL:
13480     case ISD::SHL: {
13481       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13482       if (BinNode->Flags.hasNoSignedWrap())
13483         break;
13484     }
13485     default:
13486       NeedOF = true;
13487       break;
13488     }
13489     break;
13490   }
13491   }
13492   // See if we can use the EFLAGS value from the operand instead of
13493   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13494   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13495   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13496     // Emit a CMP with 0, which is the TEST pattern.
13497     //if (Op.getValueType() == MVT::i1)
13498     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13499     //                     DAG.getConstant(0, MVT::i1));
13500     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13501                        DAG.getConstant(0, dl, Op.getValueType()));
13502   }
13503   unsigned Opcode = 0;
13504   unsigned NumOperands = 0;
13505
13506   // Truncate operations may prevent the merge of the SETCC instruction
13507   // and the arithmetic instruction before it. Attempt to truncate the operands
13508   // of the arithmetic instruction and use a reduced bit-width instruction.
13509   bool NeedTruncation = false;
13510   SDValue ArithOp = Op;
13511   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13512     SDValue Arith = Op->getOperand(0);
13513     // Both the trunc and the arithmetic op need to have one user each.
13514     if (Arith->hasOneUse())
13515       switch (Arith.getOpcode()) {
13516         default: break;
13517         case ISD::ADD:
13518         case ISD::SUB:
13519         case ISD::AND:
13520         case ISD::OR:
13521         case ISD::XOR: {
13522           NeedTruncation = true;
13523           ArithOp = Arith;
13524         }
13525       }
13526   }
13527
13528   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13529   // which may be the result of a CAST.  We use the variable 'Op', which is the
13530   // non-casted variable when we check for possible users.
13531   switch (ArithOp.getOpcode()) {
13532   case ISD::ADD:
13533     // Due to an isel shortcoming, be conservative if this add is likely to be
13534     // selected as part of a load-modify-store instruction. When the root node
13535     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13536     // uses of other nodes in the match, such as the ADD in this case. This
13537     // leads to the ADD being left around and reselected, with the result being
13538     // two adds in the output.  Alas, even if none our users are stores, that
13539     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13540     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13541     // climbing the DAG back to the root, and it doesn't seem to be worth the
13542     // effort.
13543     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13544          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13545       if (UI->getOpcode() != ISD::CopyToReg &&
13546           UI->getOpcode() != ISD::SETCC &&
13547           UI->getOpcode() != ISD::STORE)
13548         goto default_case;
13549
13550     if (ConstantSDNode *C =
13551         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13552       // An add of one will be selected as an INC.
13553       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13554         Opcode = X86ISD::INC;
13555         NumOperands = 1;
13556         break;
13557       }
13558
13559       // An add of negative one (subtract of one) will be selected as a DEC.
13560       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13561         Opcode = X86ISD::DEC;
13562         NumOperands = 1;
13563         break;
13564       }
13565     }
13566
13567     // Otherwise use a regular EFLAGS-setting add.
13568     Opcode = X86ISD::ADD;
13569     NumOperands = 2;
13570     break;
13571   case ISD::SHL:
13572   case ISD::SRL:
13573     // If we have a constant logical shift that's only used in a comparison
13574     // against zero turn it into an equivalent AND. This allows turning it into
13575     // a TEST instruction later.
13576     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13577         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13578       EVT VT = Op.getValueType();
13579       unsigned BitWidth = VT.getSizeInBits();
13580       unsigned ShAmt = Op->getConstantOperandVal(1);
13581       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13582         break;
13583       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13584                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13585                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13586       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13587         break;
13588       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13589                                 DAG.getConstant(Mask, dl, VT));
13590       DAG.ReplaceAllUsesWith(Op, New);
13591       Op = New;
13592     }
13593     break;
13594
13595   case ISD::AND:
13596     // If the primary and result isn't used, don't bother using X86ISD::AND,
13597     // because a TEST instruction will be better.
13598     if (!hasNonFlagsUse(Op))
13599       break;
13600     // FALL THROUGH
13601   case ISD::SUB:
13602   case ISD::OR:
13603   case ISD::XOR:
13604     // Due to the ISEL shortcoming noted above, be conservative if this op is
13605     // likely to be selected as part of a load-modify-store instruction.
13606     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13607            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13608       if (UI->getOpcode() == ISD::STORE)
13609         goto default_case;
13610
13611     // Otherwise use a regular EFLAGS-setting instruction.
13612     switch (ArithOp.getOpcode()) {
13613     default: llvm_unreachable("unexpected operator!");
13614     case ISD::SUB: Opcode = X86ISD::SUB; break;
13615     case ISD::XOR: Opcode = X86ISD::XOR; break;
13616     case ISD::AND: Opcode = X86ISD::AND; break;
13617     case ISD::OR: {
13618       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13619         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13620         if (EFLAGS.getNode())
13621           return EFLAGS;
13622       }
13623       Opcode = X86ISD::OR;
13624       break;
13625     }
13626     }
13627
13628     NumOperands = 2;
13629     break;
13630   case X86ISD::ADD:
13631   case X86ISD::SUB:
13632   case X86ISD::INC:
13633   case X86ISD::DEC:
13634   case X86ISD::OR:
13635   case X86ISD::XOR:
13636   case X86ISD::AND:
13637     return SDValue(Op.getNode(), 1);
13638   default:
13639   default_case:
13640     break;
13641   }
13642
13643   // If we found that truncation is beneficial, perform the truncation and
13644   // update 'Op'.
13645   if (NeedTruncation) {
13646     EVT VT = Op.getValueType();
13647     SDValue WideVal = Op->getOperand(0);
13648     EVT WideVT = WideVal.getValueType();
13649     unsigned ConvertedOp = 0;
13650     // Use a target machine opcode to prevent further DAGCombine
13651     // optimizations that may separate the arithmetic operations
13652     // from the setcc node.
13653     switch (WideVal.getOpcode()) {
13654       default: break;
13655       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13656       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13657       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13658       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13659       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13660     }
13661
13662     if (ConvertedOp) {
13663       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13664       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13665         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13666         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13667         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13668       }
13669     }
13670   }
13671
13672   if (Opcode == 0)
13673     // Emit a CMP with 0, which is the TEST pattern.
13674     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13675                        DAG.getConstant(0, dl, Op.getValueType()));
13676
13677   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13678   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13679
13680   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13681   DAG.ReplaceAllUsesWith(Op, New);
13682   return SDValue(New.getNode(), 1);
13683 }
13684
13685 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13686 /// equivalent.
13687 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13688                                    SDLoc dl, SelectionDAG &DAG) const {
13689   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13690     if (C->getAPIntValue() == 0)
13691       return EmitTest(Op0, X86CC, dl, DAG);
13692
13693      if (Op0.getValueType() == MVT::i1)
13694        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13695   }
13696
13697   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13698        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13699     // Do the comparison at i32 if it's smaller, besides the Atom case.
13700     // This avoids subregister aliasing issues. Keep the smaller reference
13701     // if we're optimizing for size, however, as that'll allow better folding
13702     // of memory operations.
13703     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13704         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13705         !Subtarget->isAtom()) {
13706       unsigned ExtendOp =
13707           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13708       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13709       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13710     }
13711     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13712     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13713     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13714                               Op0, Op1);
13715     return SDValue(Sub.getNode(), 1);
13716   }
13717   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13718 }
13719
13720 /// Convert a comparison if required by the subtarget.
13721 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13722                                                  SelectionDAG &DAG) const {
13723   // If the subtarget does not support the FUCOMI instruction, floating-point
13724   // comparisons have to be converted.
13725   if (Subtarget->hasCMov() ||
13726       Cmp.getOpcode() != X86ISD::CMP ||
13727       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13728       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13729     return Cmp;
13730
13731   // The instruction selector will select an FUCOM instruction instead of
13732   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13733   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13734   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13735   SDLoc dl(Cmp);
13736   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13737   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13738   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13739                             DAG.getConstant(8, dl, MVT::i8));
13740   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13741   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13742 }
13743
13744 /// The minimum architected relative accuracy is 2^-12. We need one
13745 /// Newton-Raphson step to have a good float result (24 bits of precision).
13746 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13747                                             DAGCombinerInfo &DCI,
13748                                             unsigned &RefinementSteps,
13749                                             bool &UseOneConstNR) const {
13750   EVT VT = Op.getValueType();
13751   const char *RecipOp;
13752
13753   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13754   // TODO: Add support for AVX512 (v16f32).
13755   // It is likely not profitable to do this for f64 because a double-precision
13756   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13757   // instructions: convert to single, rsqrtss, convert back to double, refine
13758   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13759   // along with FMA, this could be a throughput win.
13760   if (VT == MVT::f32 && Subtarget->hasSSE1())
13761     RecipOp = "sqrtf";
13762   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13763            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13764     RecipOp = "vec-sqrtf";
13765   else
13766     return SDValue();
13767
13768   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13769   if (!Recips.isEnabled(RecipOp))
13770     return SDValue();
13771
13772   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13773   UseOneConstNR = false;
13774   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13775 }
13776
13777 /// The minimum architected relative accuracy is 2^-12. We need one
13778 /// Newton-Raphson step to have a good float result (24 bits of precision).
13779 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13780                                             DAGCombinerInfo &DCI,
13781                                             unsigned &RefinementSteps) const {
13782   EVT VT = Op.getValueType();
13783   const char *RecipOp;
13784
13785   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13786   // TODO: Add support for AVX512 (v16f32).
13787   // It is likely not profitable to do this for f64 because a double-precision
13788   // reciprocal estimate with refinement on x86 prior to FMA requires
13789   // 15 instructions: convert to single, rcpss, convert back to double, refine
13790   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13791   // along with FMA, this could be a throughput win.
13792   if (VT == MVT::f32 && Subtarget->hasSSE1())
13793     RecipOp = "divf";
13794   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13795            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13796     RecipOp = "vec-divf";
13797   else
13798     return SDValue();
13799
13800   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13801   if (!Recips.isEnabled(RecipOp))
13802     return SDValue();
13803
13804   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13805   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13806 }
13807
13808 /// If we have at least two divisions that use the same divisor, convert to
13809 /// multplication by a reciprocal. This may need to be adjusted for a given
13810 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13811 /// This is because we still need one division to calculate the reciprocal and
13812 /// then we need two multiplies by that reciprocal as replacements for the
13813 /// original divisions.
13814 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13815   return 2;
13816 }
13817
13818 static bool isAllOnes(SDValue V) {
13819   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13820   return C && C->isAllOnesValue();
13821 }
13822
13823 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13824 /// if it's possible.
13825 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13826                                      SDLoc dl, SelectionDAG &DAG) const {
13827   SDValue Op0 = And.getOperand(0);
13828   SDValue Op1 = And.getOperand(1);
13829   if (Op0.getOpcode() == ISD::TRUNCATE)
13830     Op0 = Op0.getOperand(0);
13831   if (Op1.getOpcode() == ISD::TRUNCATE)
13832     Op1 = Op1.getOperand(0);
13833
13834   SDValue LHS, RHS;
13835   if (Op1.getOpcode() == ISD::SHL)
13836     std::swap(Op0, Op1);
13837   if (Op0.getOpcode() == ISD::SHL) {
13838     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13839       if (And00C->getZExtValue() == 1) {
13840         // If we looked past a truncate, check that it's only truncating away
13841         // known zeros.
13842         unsigned BitWidth = Op0.getValueSizeInBits();
13843         unsigned AndBitWidth = And.getValueSizeInBits();
13844         if (BitWidth > AndBitWidth) {
13845           APInt Zeros, Ones;
13846           DAG.computeKnownBits(Op0, Zeros, Ones);
13847           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13848             return SDValue();
13849         }
13850         LHS = Op1;
13851         RHS = Op0.getOperand(1);
13852       }
13853   } else if (Op1.getOpcode() == ISD::Constant) {
13854     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13855     uint64_t AndRHSVal = AndRHS->getZExtValue();
13856     SDValue AndLHS = Op0;
13857
13858     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13859       LHS = AndLHS.getOperand(0);
13860       RHS = AndLHS.getOperand(1);
13861     }
13862
13863     // Use BT if the immediate can't be encoded in a TEST instruction.
13864     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13865       LHS = AndLHS;
13866       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13867     }
13868   }
13869
13870   if (LHS.getNode()) {
13871     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13872     // instruction.  Since the shift amount is in-range-or-undefined, we know
13873     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13874     // the encoding for the i16 version is larger than the i32 version.
13875     // Also promote i16 to i32 for performance / code size reason.
13876     if (LHS.getValueType() == MVT::i8 ||
13877         LHS.getValueType() == MVT::i16)
13878       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13879
13880     // If the operand types disagree, extend the shift amount to match.  Since
13881     // BT ignores high bits (like shifts) we can use anyextend.
13882     if (LHS.getValueType() != RHS.getValueType())
13883       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13884
13885     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13886     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13887     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13888                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13889   }
13890
13891   return SDValue();
13892 }
13893
13894 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13895 /// mask CMPs.
13896 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13897                               SDValue &Op1) {
13898   unsigned SSECC;
13899   bool Swap = false;
13900
13901   // SSE Condition code mapping:
13902   //  0 - EQ
13903   //  1 - LT
13904   //  2 - LE
13905   //  3 - UNORD
13906   //  4 - NEQ
13907   //  5 - NLT
13908   //  6 - NLE
13909   //  7 - ORD
13910   switch (SetCCOpcode) {
13911   default: llvm_unreachable("Unexpected SETCC condition");
13912   case ISD::SETOEQ:
13913   case ISD::SETEQ:  SSECC = 0; break;
13914   case ISD::SETOGT:
13915   case ISD::SETGT:  Swap = true; // Fallthrough
13916   case ISD::SETLT:
13917   case ISD::SETOLT: SSECC = 1; break;
13918   case ISD::SETOGE:
13919   case ISD::SETGE:  Swap = true; // Fallthrough
13920   case ISD::SETLE:
13921   case ISD::SETOLE: SSECC = 2; break;
13922   case ISD::SETUO:  SSECC = 3; break;
13923   case ISD::SETUNE:
13924   case ISD::SETNE:  SSECC = 4; break;
13925   case ISD::SETULE: Swap = true; // Fallthrough
13926   case ISD::SETUGE: SSECC = 5; break;
13927   case ISD::SETULT: Swap = true; // Fallthrough
13928   case ISD::SETUGT: SSECC = 6; break;
13929   case ISD::SETO:   SSECC = 7; break;
13930   case ISD::SETUEQ:
13931   case ISD::SETONE: SSECC = 8; break;
13932   }
13933   if (Swap)
13934     std::swap(Op0, Op1);
13935
13936   return SSECC;
13937 }
13938
13939 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13940 // ones, and then concatenate the result back.
13941 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13942   MVT VT = Op.getSimpleValueType();
13943
13944   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13945          "Unsupported value type for operation");
13946
13947   unsigned NumElems = VT.getVectorNumElements();
13948   SDLoc dl(Op);
13949   SDValue CC = Op.getOperand(2);
13950
13951   // Extract the LHS vectors
13952   SDValue LHS = Op.getOperand(0);
13953   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13954   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13955
13956   // Extract the RHS vectors
13957   SDValue RHS = Op.getOperand(1);
13958   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13959   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13960
13961   // Issue the operation on the smaller types and concatenate the result back
13962   MVT EltVT = VT.getVectorElementType();
13963   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13964   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13965                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13966                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13967 }
13968
13969 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13970   SDValue Op0 = Op.getOperand(0);
13971   SDValue Op1 = Op.getOperand(1);
13972   SDValue CC = Op.getOperand(2);
13973   MVT VT = Op.getSimpleValueType();
13974   SDLoc dl(Op);
13975
13976   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13977          "Unexpected type for boolean compare operation");
13978   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13979   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13980                                DAG.getConstant(-1, dl, VT));
13981   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13982                                DAG.getConstant(-1, dl, VT));
13983   switch (SetCCOpcode) {
13984   default: llvm_unreachable("Unexpected SETCC condition");
13985   case ISD::SETEQ:
13986     // (x == y) -> ~(x ^ y)
13987     return DAG.getNode(ISD::XOR, dl, VT,
13988                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13989                        DAG.getConstant(-1, dl, VT));
13990   case ISD::SETNE:
13991     // (x != y) -> (x ^ y)
13992     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13993   case ISD::SETUGT:
13994   case ISD::SETGT:
13995     // (x > y) -> (x & ~y)
13996     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13997   case ISD::SETULT:
13998   case ISD::SETLT:
13999     // (x < y) -> (~x & y)
14000     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14001   case ISD::SETULE:
14002   case ISD::SETLE:
14003     // (x <= y) -> (~x | y)
14004     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14005   case ISD::SETUGE:
14006   case ISD::SETGE:
14007     // (x >=y) -> (x | ~y)
14008     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14009   }
14010 }
14011
14012 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14013                                      const X86Subtarget *Subtarget) {
14014   SDValue Op0 = Op.getOperand(0);
14015   SDValue Op1 = Op.getOperand(1);
14016   SDValue CC = Op.getOperand(2);
14017   MVT VT = Op.getSimpleValueType();
14018   SDLoc dl(Op);
14019
14020   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
14021          Op.getValueType().getScalarType() == MVT::i1 &&
14022          "Cannot set masked compare for this operation");
14023
14024   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14025   unsigned  Opc = 0;
14026   bool Unsigned = false;
14027   bool Swap = false;
14028   unsigned SSECC;
14029   switch (SetCCOpcode) {
14030   default: llvm_unreachable("Unexpected SETCC condition");
14031   case ISD::SETNE:  SSECC = 4; break;
14032   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14033   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14034   case ISD::SETLT:  Swap = true; //fall-through
14035   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14036   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14037   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14038   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14039   case ISD::SETULE: Unsigned = true; //fall-through
14040   case ISD::SETLE:  SSECC = 2; break;
14041   }
14042
14043   if (Swap)
14044     std::swap(Op0, Op1);
14045   if (Opc)
14046     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14047   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14048   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14049                      DAG.getConstant(SSECC, dl, MVT::i8));
14050 }
14051
14052 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14053 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14054 /// return an empty value.
14055 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14056 {
14057   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14058   if (!BV)
14059     return SDValue();
14060
14061   MVT VT = Op1.getSimpleValueType();
14062   MVT EVT = VT.getVectorElementType();
14063   unsigned n = VT.getVectorNumElements();
14064   SmallVector<SDValue, 8> ULTOp1;
14065
14066   for (unsigned i = 0; i < n; ++i) {
14067     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14068     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
14069       return SDValue();
14070
14071     // Avoid underflow.
14072     APInt Val = Elt->getAPIntValue();
14073     if (Val == 0)
14074       return SDValue();
14075
14076     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14077   }
14078
14079   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14080 }
14081
14082 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14083                            SelectionDAG &DAG) {
14084   SDValue Op0 = Op.getOperand(0);
14085   SDValue Op1 = Op.getOperand(1);
14086   SDValue CC = Op.getOperand(2);
14087   MVT VT = Op.getSimpleValueType();
14088   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14089   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14090   SDLoc dl(Op);
14091
14092   if (isFP) {
14093 #ifndef NDEBUG
14094     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14095     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14096 #endif
14097
14098     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14099     unsigned Opc = X86ISD::CMPP;
14100     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14101       assert(VT.getVectorNumElements() <= 16);
14102       Opc = X86ISD::CMPM;
14103     }
14104     // In the two special cases we can't handle, emit two comparisons.
14105     if (SSECC == 8) {
14106       unsigned CC0, CC1;
14107       unsigned CombineOpc;
14108       if (SetCCOpcode == ISD::SETUEQ) {
14109         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14110       } else {
14111         assert(SetCCOpcode == ISD::SETONE);
14112         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14113       }
14114
14115       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14116                                  DAG.getConstant(CC0, dl, MVT::i8));
14117       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14118                                  DAG.getConstant(CC1, dl, MVT::i8));
14119       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14120     }
14121     // Handle all other FP comparisons here.
14122     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14123                        DAG.getConstant(SSECC, dl, MVT::i8));
14124   }
14125
14126   // Break 256-bit integer vector compare into smaller ones.
14127   if (VT.is256BitVector() && !Subtarget->hasInt256())
14128     return Lower256IntVSETCC(Op, DAG);
14129
14130   EVT OpVT = Op1.getValueType();
14131   if (OpVT.getVectorElementType() == MVT::i1)
14132     return LowerBoolVSETCC_AVX512(Op, DAG);
14133
14134   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14135   if (Subtarget->hasAVX512()) {
14136     if (Op1.getValueType().is512BitVector() ||
14137         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14138         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14139       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14140
14141     // In AVX-512 architecture setcc returns mask with i1 elements,
14142     // But there is no compare instruction for i8 and i16 elements in KNL.
14143     // We are not talking about 512-bit operands in this case, these
14144     // types are illegal.
14145     if (MaskResult &&
14146         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14147          OpVT.getVectorElementType().getSizeInBits() >= 8))
14148       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14149                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14150   }
14151
14152   // We are handling one of the integer comparisons here.  Since SSE only has
14153   // GT and EQ comparisons for integer, swapping operands and multiple
14154   // operations may be required for some comparisons.
14155   unsigned Opc;
14156   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14157   bool Subus = false;
14158
14159   switch (SetCCOpcode) {
14160   default: llvm_unreachable("Unexpected SETCC condition");
14161   case ISD::SETNE:  Invert = true;
14162   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14163   case ISD::SETLT:  Swap = true;
14164   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14165   case ISD::SETGE:  Swap = true;
14166   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14167                     Invert = true; break;
14168   case ISD::SETULT: Swap = true;
14169   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14170                     FlipSigns = true; break;
14171   case ISD::SETUGE: Swap = true;
14172   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14173                     FlipSigns = true; Invert = true; break;
14174   }
14175
14176   // Special case: Use min/max operations for SETULE/SETUGE
14177   MVT VET = VT.getVectorElementType();
14178   bool hasMinMax =
14179        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14180     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14181
14182   if (hasMinMax) {
14183     switch (SetCCOpcode) {
14184     default: break;
14185     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14186     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14187     }
14188
14189     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14190   }
14191
14192   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14193   if (!MinMax && hasSubus) {
14194     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14195     // Op0 u<= Op1:
14196     //   t = psubus Op0, Op1
14197     //   pcmpeq t, <0..0>
14198     switch (SetCCOpcode) {
14199     default: break;
14200     case ISD::SETULT: {
14201       // If the comparison is against a constant we can turn this into a
14202       // setule.  With psubus, setule does not require a swap.  This is
14203       // beneficial because the constant in the register is no longer
14204       // destructed as the destination so it can be hoisted out of a loop.
14205       // Only do this pre-AVX since vpcmp* is no longer destructive.
14206       if (Subtarget->hasAVX())
14207         break;
14208       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14209       if (ULEOp1.getNode()) {
14210         Op1 = ULEOp1;
14211         Subus = true; Invert = false; Swap = false;
14212       }
14213       break;
14214     }
14215     // Psubus is better than flip-sign because it requires no inversion.
14216     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14217     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14218     }
14219
14220     if (Subus) {
14221       Opc = X86ISD::SUBUS;
14222       FlipSigns = false;
14223     }
14224   }
14225
14226   if (Swap)
14227     std::swap(Op0, Op1);
14228
14229   // Check that the operation in question is available (most are plain SSE2,
14230   // but PCMPGTQ and PCMPEQQ have different requirements).
14231   if (VT == MVT::v2i64) {
14232     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14233       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14234
14235       // First cast everything to the right type.
14236       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14237       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14238
14239       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14240       // bits of the inputs before performing those operations. The lower
14241       // compare is always unsigned.
14242       SDValue SB;
14243       if (FlipSigns) {
14244         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14245       } else {
14246         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14247         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14248         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14249                          Sign, Zero, Sign, Zero);
14250       }
14251       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14252       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14253
14254       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14255       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14256       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14257
14258       // Create masks for only the low parts/high parts of the 64 bit integers.
14259       static const int MaskHi[] = { 1, 1, 3, 3 };
14260       static const int MaskLo[] = { 0, 0, 2, 2 };
14261       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14262       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14263       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14264
14265       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14266       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14267
14268       if (Invert)
14269         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14270
14271       return DAG.getBitcast(VT, Result);
14272     }
14273
14274     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14275       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14276       // pcmpeqd + pshufd + pand.
14277       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14278
14279       // First cast everything to the right type.
14280       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14281       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14282
14283       // Do the compare.
14284       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14285
14286       // Make sure the lower and upper halves are both all-ones.
14287       static const int Mask[] = { 1, 0, 3, 2 };
14288       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14289       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14290
14291       if (Invert)
14292         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14293
14294       return DAG.getBitcast(VT, Result);
14295     }
14296   }
14297
14298   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14299   // bits of the inputs before performing those operations.
14300   if (FlipSigns) {
14301     EVT EltVT = VT.getVectorElementType();
14302     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14303                                  VT);
14304     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14305     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14306   }
14307
14308   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14309
14310   // If the logical-not of the result is required, perform that now.
14311   if (Invert)
14312     Result = DAG.getNOT(dl, Result, VT);
14313
14314   if (MinMax)
14315     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14316
14317   if (Subus)
14318     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14319                          getZeroVector(VT, Subtarget, DAG, dl));
14320
14321   return Result;
14322 }
14323
14324 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14325
14326   MVT VT = Op.getSimpleValueType();
14327
14328   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14329
14330   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14331          && "SetCC type must be 8-bit or 1-bit integer");
14332   SDValue Op0 = Op.getOperand(0);
14333   SDValue Op1 = Op.getOperand(1);
14334   SDLoc dl(Op);
14335   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14336
14337   // Optimize to BT if possible.
14338   // Lower (X & (1 << N)) == 0 to BT(X, N).
14339   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14340   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14341   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14342       Op1.getOpcode() == ISD::Constant &&
14343       cast<ConstantSDNode>(Op1)->isNullValue() &&
14344       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14345     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14346     if (NewSetCC.getNode()) {
14347       if (VT == MVT::i1)
14348         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14349       return NewSetCC;
14350     }
14351   }
14352
14353   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14354   // these.
14355   if (Op1.getOpcode() == ISD::Constant &&
14356       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14357        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14358       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14359
14360     // If the input is a setcc, then reuse the input setcc or use a new one with
14361     // the inverted condition.
14362     if (Op0.getOpcode() == X86ISD::SETCC) {
14363       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14364       bool Invert = (CC == ISD::SETNE) ^
14365         cast<ConstantSDNode>(Op1)->isNullValue();
14366       if (!Invert)
14367         return Op0;
14368
14369       CCode = X86::GetOppositeBranchCondition(CCode);
14370       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14371                                   DAG.getConstant(CCode, dl, MVT::i8),
14372                                   Op0.getOperand(1));
14373       if (VT == MVT::i1)
14374         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14375       return SetCC;
14376     }
14377   }
14378   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14379       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14380       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14381
14382     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14383     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14384   }
14385
14386   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14387   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14388   if (X86CC == X86::COND_INVALID)
14389     return SDValue();
14390
14391   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14392   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14393   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14394                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14395   if (VT == MVT::i1)
14396     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14397   return SetCC;
14398 }
14399
14400 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14401 static bool isX86LogicalCmp(SDValue Op) {
14402   unsigned Opc = Op.getNode()->getOpcode();
14403   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14404       Opc == X86ISD::SAHF)
14405     return true;
14406   if (Op.getResNo() == 1 &&
14407       (Opc == X86ISD::ADD ||
14408        Opc == X86ISD::SUB ||
14409        Opc == X86ISD::ADC ||
14410        Opc == X86ISD::SBB ||
14411        Opc == X86ISD::SMUL ||
14412        Opc == X86ISD::UMUL ||
14413        Opc == X86ISD::INC ||
14414        Opc == X86ISD::DEC ||
14415        Opc == X86ISD::OR ||
14416        Opc == X86ISD::XOR ||
14417        Opc == X86ISD::AND))
14418     return true;
14419
14420   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14421     return true;
14422
14423   return false;
14424 }
14425
14426 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14427   if (V.getOpcode() != ISD::TRUNCATE)
14428     return false;
14429
14430   SDValue VOp0 = V.getOperand(0);
14431   unsigned InBits = VOp0.getValueSizeInBits();
14432   unsigned Bits = V.getValueSizeInBits();
14433   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14434 }
14435
14436 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14437   bool addTest = true;
14438   SDValue Cond  = Op.getOperand(0);
14439   SDValue Op1 = Op.getOperand(1);
14440   SDValue Op2 = Op.getOperand(2);
14441   SDLoc DL(Op);
14442   EVT VT = Op1.getValueType();
14443   SDValue CC;
14444
14445   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14446   // are available or VBLENDV if AVX is available.
14447   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14448   if (Cond.getOpcode() == ISD::SETCC &&
14449       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14450        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14451       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14452     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14453     int SSECC = translateX86FSETCC(
14454         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14455
14456     if (SSECC != 8) {
14457       if (Subtarget->hasAVX512()) {
14458         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14459                                   DAG.getConstant(SSECC, DL, MVT::i8));
14460         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14461       }
14462
14463       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14464                                 DAG.getConstant(SSECC, DL, MVT::i8));
14465
14466       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14467       // of 3 logic instructions for size savings and potentially speed.
14468       // Unfortunately, there is no scalar form of VBLENDV.
14469
14470       // If either operand is a constant, don't try this. We can expect to
14471       // optimize away at least one of the logic instructions later in that
14472       // case, so that sequence would be faster than a variable blend.
14473
14474       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14475       // uses XMM0 as the selection register. That may need just as many
14476       // instructions as the AND/ANDN/OR sequence due to register moves, so
14477       // don't bother.
14478
14479       if (Subtarget->hasAVX() &&
14480           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14481
14482         // Convert to vectors, do a VSELECT, and convert back to scalar.
14483         // All of the conversions should be optimized away.
14484
14485         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14486         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14487         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14488         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14489
14490         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14491         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14492
14493         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14494
14495         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14496                            VSel, DAG.getIntPtrConstant(0, DL));
14497       }
14498       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14499       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14500       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14501     }
14502   }
14503
14504   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14505     SDValue Op1Scalar;
14506     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14507       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14508     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14509       Op1Scalar = Op1.getOperand(0);
14510     SDValue Op2Scalar;
14511     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14512       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14513     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14514       Op2Scalar = Op2.getOperand(0);
14515     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14516       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14517                                       Op1Scalar.getValueType(),
14518                                       Cond, Op1Scalar, Op2Scalar);
14519       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14520         return DAG.getBitcast(VT, newSelect);
14521       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14522       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14523                          DAG.getIntPtrConstant(0, DL));
14524     }
14525   }
14526
14527   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14528     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14529     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14530                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14531     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14532                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14533     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14534                                     Cond, Op1, Op2);
14535     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14536   }
14537
14538   if (Cond.getOpcode() == ISD::SETCC) {
14539     SDValue NewCond = LowerSETCC(Cond, DAG);
14540     if (NewCond.getNode())
14541       Cond = NewCond;
14542   }
14543
14544   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14545   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14546   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14547   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14548   if (Cond.getOpcode() == X86ISD::SETCC &&
14549       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14550       isZero(Cond.getOperand(1).getOperand(1))) {
14551     SDValue Cmp = Cond.getOperand(1);
14552
14553     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14554
14555     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14556         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14557       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14558
14559       SDValue CmpOp0 = Cmp.getOperand(0);
14560       // Apply further optimizations for special cases
14561       // (select (x != 0), -1, 0) -> neg & sbb
14562       // (select (x == 0), 0, -1) -> neg & sbb
14563       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14564         if (YC->isNullValue() &&
14565             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14566           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14567           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14568                                     DAG.getConstant(0, DL,
14569                                                     CmpOp0.getValueType()),
14570                                     CmpOp0);
14571           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14572                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14573                                     SDValue(Neg.getNode(), 1));
14574           return Res;
14575         }
14576
14577       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14578                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14579       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14580
14581       SDValue Res =   // Res = 0 or -1.
14582         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14583                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14584
14585       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14586         Res = DAG.getNOT(DL, Res, Res.getValueType());
14587
14588       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14589       if (!N2C || !N2C->isNullValue())
14590         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14591       return Res;
14592     }
14593   }
14594
14595   // Look past (and (setcc_carry (cmp ...)), 1).
14596   if (Cond.getOpcode() == ISD::AND &&
14597       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14598     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14599     if (C && C->getAPIntValue() == 1)
14600       Cond = Cond.getOperand(0);
14601   }
14602
14603   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14604   // setting operand in place of the X86ISD::SETCC.
14605   unsigned CondOpcode = Cond.getOpcode();
14606   if (CondOpcode == X86ISD::SETCC ||
14607       CondOpcode == X86ISD::SETCC_CARRY) {
14608     CC = Cond.getOperand(0);
14609
14610     SDValue Cmp = Cond.getOperand(1);
14611     unsigned Opc = Cmp.getOpcode();
14612     MVT VT = Op.getSimpleValueType();
14613
14614     bool IllegalFPCMov = false;
14615     if (VT.isFloatingPoint() && !VT.isVector() &&
14616         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14617       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14618
14619     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14620         Opc == X86ISD::BT) { // FIXME
14621       Cond = Cmp;
14622       addTest = false;
14623     }
14624   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14625              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14626              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14627               Cond.getOperand(0).getValueType() != MVT::i8)) {
14628     SDValue LHS = Cond.getOperand(0);
14629     SDValue RHS = Cond.getOperand(1);
14630     unsigned X86Opcode;
14631     unsigned X86Cond;
14632     SDVTList VTs;
14633     switch (CondOpcode) {
14634     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14635     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14636     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14637     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14638     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14639     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14640     default: llvm_unreachable("unexpected overflowing operator");
14641     }
14642     if (CondOpcode == ISD::UMULO)
14643       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14644                           MVT::i32);
14645     else
14646       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14647
14648     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14649
14650     if (CondOpcode == ISD::UMULO)
14651       Cond = X86Op.getValue(2);
14652     else
14653       Cond = X86Op.getValue(1);
14654
14655     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14656     addTest = false;
14657   }
14658
14659   if (addTest) {
14660     // Look past the truncate if the high bits are known zero.
14661     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14662       Cond = Cond.getOperand(0);
14663
14664     // We know the result of AND is compared against zero. Try to match
14665     // it to BT.
14666     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14667       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14668       if (NewSetCC.getNode()) {
14669         CC = NewSetCC.getOperand(0);
14670         Cond = NewSetCC.getOperand(1);
14671         addTest = false;
14672       }
14673     }
14674   }
14675
14676   if (addTest) {
14677     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14678     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14679   }
14680
14681   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14682   // a <  b ?  0 : -1 -> RES = setcc_carry
14683   // a >= b ? -1 :  0 -> RES = setcc_carry
14684   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14685   if (Cond.getOpcode() == X86ISD::SUB) {
14686     Cond = ConvertCmpIfNecessary(Cond, DAG);
14687     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14688
14689     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14690         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14691       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14692                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14693                                 Cond);
14694       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14695         return DAG.getNOT(DL, Res, Res.getValueType());
14696       return Res;
14697     }
14698   }
14699
14700   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14701   // widen the cmov and push the truncate through. This avoids introducing a new
14702   // branch during isel and doesn't add any extensions.
14703   if (Op.getValueType() == MVT::i8 &&
14704       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14705     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14706     if (T1.getValueType() == T2.getValueType() &&
14707         // Blacklist CopyFromReg to avoid partial register stalls.
14708         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14709       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14710       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14711       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14712     }
14713   }
14714
14715   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14716   // condition is true.
14717   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14718   SDValue Ops[] = { Op2, Op1, CC, Cond };
14719   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14720 }
14721
14722 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14723                                        const X86Subtarget *Subtarget,
14724                                        SelectionDAG &DAG) {
14725   MVT VT = Op->getSimpleValueType(0);
14726   SDValue In = Op->getOperand(0);
14727   MVT InVT = In.getSimpleValueType();
14728   MVT VTElt = VT.getVectorElementType();
14729   MVT InVTElt = InVT.getVectorElementType();
14730   SDLoc dl(Op);
14731
14732   // SKX processor
14733   if ((InVTElt == MVT::i1) &&
14734       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14735         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14736
14737        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14738         VTElt.getSizeInBits() <= 16)) ||
14739
14740        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14741         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14742
14743        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14744         VTElt.getSizeInBits() >= 32))))
14745     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14746
14747   unsigned int NumElts = VT.getVectorNumElements();
14748
14749   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14750     return SDValue();
14751
14752   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14753     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14754       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14755     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14756   }
14757
14758   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14759   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14760   SDValue NegOne =
14761    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14762                    ExtVT);
14763   SDValue Zero =
14764    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14765
14766   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14767   if (VT.is512BitVector())
14768     return V;
14769   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14770 }
14771
14772 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14773                                              const X86Subtarget *Subtarget,
14774                                              SelectionDAG &DAG) {
14775   SDValue In = Op->getOperand(0);
14776   MVT VT = Op->getSimpleValueType(0);
14777   MVT InVT = In.getSimpleValueType();
14778   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14779
14780   MVT InSVT = InVT.getScalarType();
14781   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14782
14783   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14784     return SDValue();
14785   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14786     return SDValue();
14787
14788   SDLoc dl(Op);
14789
14790   // SSE41 targets can use the pmovsx* instructions directly.
14791   if (Subtarget->hasSSE41())
14792     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14793
14794   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14795   SDValue Curr = In;
14796   MVT CurrVT = InVT;
14797
14798   // As SRAI is only available on i16/i32 types, we expand only up to i32
14799   // and handle i64 separately.
14800   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14801     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14802     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14803     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14804     Curr = DAG.getBitcast(CurrVT, Curr);
14805   }
14806
14807   SDValue SignExt = Curr;
14808   if (CurrVT != InVT) {
14809     unsigned SignExtShift =
14810         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14811     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14812                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14813   }
14814
14815   if (CurrVT == VT)
14816     return SignExt;
14817
14818   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14819     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14820                                DAG.getConstant(31, dl, MVT::i8));
14821     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14822     return DAG.getBitcast(VT, Ext);
14823   }
14824
14825   return SDValue();
14826 }
14827
14828 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14829                                 SelectionDAG &DAG) {
14830   MVT VT = Op->getSimpleValueType(0);
14831   SDValue In = Op->getOperand(0);
14832   MVT InVT = In.getSimpleValueType();
14833   SDLoc dl(Op);
14834
14835   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14836     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14837
14838   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14839       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14840       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14841     return SDValue();
14842
14843   if (Subtarget->hasInt256())
14844     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14845
14846   // Optimize vectors in AVX mode
14847   // Sign extend  v8i16 to v8i32 and
14848   //              v4i32 to v4i64
14849   //
14850   // Divide input vector into two parts
14851   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14852   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14853   // concat the vectors to original VT
14854
14855   unsigned NumElems = InVT.getVectorNumElements();
14856   SDValue Undef = DAG.getUNDEF(InVT);
14857
14858   SmallVector<int,8> ShufMask1(NumElems, -1);
14859   for (unsigned i = 0; i != NumElems/2; ++i)
14860     ShufMask1[i] = i;
14861
14862   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14863
14864   SmallVector<int,8> ShufMask2(NumElems, -1);
14865   for (unsigned i = 0; i != NumElems/2; ++i)
14866     ShufMask2[i] = i + NumElems/2;
14867
14868   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14869
14870   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14871                                 VT.getVectorNumElements()/2);
14872
14873   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14874   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14875
14876   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14877 }
14878
14879 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14880 // may emit an illegal shuffle but the expansion is still better than scalar
14881 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14882 // we'll emit a shuffle and a arithmetic shift.
14883 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14884 // TODO: It is possible to support ZExt by zeroing the undef values during
14885 // the shuffle phase or after the shuffle.
14886 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14887                                  SelectionDAG &DAG) {
14888   MVT RegVT = Op.getSimpleValueType();
14889   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14890   assert(RegVT.isInteger() &&
14891          "We only custom lower integer vector sext loads.");
14892
14893   // Nothing useful we can do without SSE2 shuffles.
14894   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14895
14896   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14897   SDLoc dl(Ld);
14898   EVT MemVT = Ld->getMemoryVT();
14899   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14900   unsigned RegSz = RegVT.getSizeInBits();
14901
14902   ISD::LoadExtType Ext = Ld->getExtensionType();
14903
14904   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14905          && "Only anyext and sext are currently implemented.");
14906   assert(MemVT != RegVT && "Cannot extend to the same type");
14907   assert(MemVT.isVector() && "Must load a vector from memory");
14908
14909   unsigned NumElems = RegVT.getVectorNumElements();
14910   unsigned MemSz = MemVT.getSizeInBits();
14911   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14912
14913   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14914     // The only way in which we have a legal 256-bit vector result but not the
14915     // integer 256-bit operations needed to directly lower a sextload is if we
14916     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14917     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14918     // correctly legalized. We do this late to allow the canonical form of
14919     // sextload to persist throughout the rest of the DAG combiner -- it wants
14920     // to fold together any extensions it can, and so will fuse a sign_extend
14921     // of an sextload into a sextload targeting a wider value.
14922     SDValue Load;
14923     if (MemSz == 128) {
14924       // Just switch this to a normal load.
14925       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14926                                        "it must be a legal 128-bit vector "
14927                                        "type!");
14928       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14929                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14930                   Ld->isInvariant(), Ld->getAlignment());
14931     } else {
14932       assert(MemSz < 128 &&
14933              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14934       // Do an sext load to a 128-bit vector type. We want to use the same
14935       // number of elements, but elements half as wide. This will end up being
14936       // recursively lowered by this routine, but will succeed as we definitely
14937       // have all the necessary features if we're using AVX1.
14938       EVT HalfEltVT =
14939           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14940       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14941       Load =
14942           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14943                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14944                          Ld->isNonTemporal(), Ld->isInvariant(),
14945                          Ld->getAlignment());
14946     }
14947
14948     // Replace chain users with the new chain.
14949     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14950     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14951
14952     // Finally, do a normal sign-extend to the desired register.
14953     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14954   }
14955
14956   // All sizes must be a power of two.
14957   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14958          "Non-power-of-two elements are not custom lowered!");
14959
14960   // Attempt to load the original value using scalar loads.
14961   // Find the largest scalar type that divides the total loaded size.
14962   MVT SclrLoadTy = MVT::i8;
14963   for (MVT Tp : MVT::integer_valuetypes()) {
14964     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14965       SclrLoadTy = Tp;
14966     }
14967   }
14968
14969   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14970   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14971       (64 <= MemSz))
14972     SclrLoadTy = MVT::f64;
14973
14974   // Calculate the number of scalar loads that we need to perform
14975   // in order to load our vector from memory.
14976   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14977
14978   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14979          "Can only lower sext loads with a single scalar load!");
14980
14981   unsigned loadRegZize = RegSz;
14982   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14983     loadRegZize = 128;
14984
14985   // Represent our vector as a sequence of elements which are the
14986   // largest scalar that we can load.
14987   EVT LoadUnitVecVT = EVT::getVectorVT(
14988       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14989
14990   // Represent the data using the same element type that is stored in
14991   // memory. In practice, we ''widen'' MemVT.
14992   EVT WideVecVT =
14993       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14994                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14995
14996   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14997          "Invalid vector type");
14998
14999   // We can't shuffle using an illegal type.
15000   assert(TLI.isTypeLegal(WideVecVT) &&
15001          "We only lower types that form legal widened vector types");
15002
15003   SmallVector<SDValue, 8> Chains;
15004   SDValue Ptr = Ld->getBasePtr();
15005   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15006                                       TLI.getPointerTy(DAG.getDataLayout()));
15007   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15008
15009   for (unsigned i = 0; i < NumLoads; ++i) {
15010     // Perform a single load.
15011     SDValue ScalarLoad =
15012         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15013                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15014                     Ld->getAlignment());
15015     Chains.push_back(ScalarLoad.getValue(1));
15016     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15017     // another round of DAGCombining.
15018     if (i == 0)
15019       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15020     else
15021       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15022                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
15023
15024     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15025   }
15026
15027   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15028
15029   // Bitcast the loaded value to a vector of the original element type, in
15030   // the size of the target vector type.
15031   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15032   unsigned SizeRatio = RegSz / MemSz;
15033
15034   if (Ext == ISD::SEXTLOAD) {
15035     // If we have SSE4.1, we can directly emit a VSEXT node.
15036     if (Subtarget->hasSSE41()) {
15037       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15038       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15039       return Sext;
15040     }
15041
15042     // Otherwise we'll shuffle the small elements in the high bits of the
15043     // larger type and perform an arithmetic shift. If the shift is not legal
15044     // it's better to scalarize.
15045     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
15046            "We can't implement a sext load without an arithmetic right shift!");
15047
15048     // Redistribute the loaded elements into the different locations.
15049     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15050     for (unsigned i = 0; i != NumElems; ++i)
15051       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
15052
15053     SDValue Shuff = DAG.getVectorShuffle(
15054         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15055
15056     Shuff = DAG.getBitcast(RegVT, Shuff);
15057
15058     // Build the arithmetic shift.
15059     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
15060                    MemVT.getVectorElementType().getSizeInBits();
15061     Shuff =
15062         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
15063                     DAG.getConstant(Amt, dl, RegVT));
15064
15065     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15066     return Shuff;
15067   }
15068
15069   // Redistribute the loaded elements into the different locations.
15070   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15071   for (unsigned i = 0; i != NumElems; ++i)
15072     ShuffleVec[i * SizeRatio] = i;
15073
15074   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15075                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15076
15077   // Bitcast to the requested type.
15078   Shuff = DAG.getBitcast(RegVT, Shuff);
15079   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15080   return Shuff;
15081 }
15082
15083 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15084 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15085 // from the AND / OR.
15086 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15087   Opc = Op.getOpcode();
15088   if (Opc != ISD::OR && Opc != ISD::AND)
15089     return false;
15090   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15091           Op.getOperand(0).hasOneUse() &&
15092           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15093           Op.getOperand(1).hasOneUse());
15094 }
15095
15096 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15097 // 1 and that the SETCC node has a single use.
15098 static bool isXor1OfSetCC(SDValue Op) {
15099   if (Op.getOpcode() != ISD::XOR)
15100     return false;
15101   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15102   if (N1C && N1C->getAPIntValue() == 1) {
15103     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15104       Op.getOperand(0).hasOneUse();
15105   }
15106   return false;
15107 }
15108
15109 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15110   bool addTest = true;
15111   SDValue Chain = Op.getOperand(0);
15112   SDValue Cond  = Op.getOperand(1);
15113   SDValue Dest  = Op.getOperand(2);
15114   SDLoc dl(Op);
15115   SDValue CC;
15116   bool Inverted = false;
15117
15118   if (Cond.getOpcode() == ISD::SETCC) {
15119     // Check for setcc([su]{add,sub,mul}o == 0).
15120     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15121         isa<ConstantSDNode>(Cond.getOperand(1)) &&
15122         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
15123         Cond.getOperand(0).getResNo() == 1 &&
15124         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15125          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15126          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15127          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15128          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15129          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15130       Inverted = true;
15131       Cond = Cond.getOperand(0);
15132     } else {
15133       SDValue NewCond = LowerSETCC(Cond, DAG);
15134       if (NewCond.getNode())
15135         Cond = NewCond;
15136     }
15137   }
15138 #if 0
15139   // FIXME: LowerXALUO doesn't handle these!!
15140   else if (Cond.getOpcode() == X86ISD::ADD  ||
15141            Cond.getOpcode() == X86ISD::SUB  ||
15142            Cond.getOpcode() == X86ISD::SMUL ||
15143            Cond.getOpcode() == X86ISD::UMUL)
15144     Cond = LowerXALUO(Cond, DAG);
15145 #endif
15146
15147   // Look pass (and (setcc_carry (cmp ...)), 1).
15148   if (Cond.getOpcode() == ISD::AND &&
15149       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15150     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15151     if (C && C->getAPIntValue() == 1)
15152       Cond = Cond.getOperand(0);
15153   }
15154
15155   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15156   // setting operand in place of the X86ISD::SETCC.
15157   unsigned CondOpcode = Cond.getOpcode();
15158   if (CondOpcode == X86ISD::SETCC ||
15159       CondOpcode == X86ISD::SETCC_CARRY) {
15160     CC = Cond.getOperand(0);
15161
15162     SDValue Cmp = Cond.getOperand(1);
15163     unsigned Opc = Cmp.getOpcode();
15164     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15165     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15166       Cond = Cmp;
15167       addTest = false;
15168     } else {
15169       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15170       default: break;
15171       case X86::COND_O:
15172       case X86::COND_B:
15173         // These can only come from an arithmetic instruction with overflow,
15174         // e.g. SADDO, UADDO.
15175         Cond = Cond.getNode()->getOperand(1);
15176         addTest = false;
15177         break;
15178       }
15179     }
15180   }
15181   CondOpcode = Cond.getOpcode();
15182   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15183       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15184       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15185        Cond.getOperand(0).getValueType() != MVT::i8)) {
15186     SDValue LHS = Cond.getOperand(0);
15187     SDValue RHS = Cond.getOperand(1);
15188     unsigned X86Opcode;
15189     unsigned X86Cond;
15190     SDVTList VTs;
15191     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15192     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15193     // X86ISD::INC).
15194     switch (CondOpcode) {
15195     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15196     case ISD::SADDO:
15197       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15198         if (C->isOne()) {
15199           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15200           break;
15201         }
15202       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15203     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15204     case ISD::SSUBO:
15205       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15206         if (C->isOne()) {
15207           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15208           break;
15209         }
15210       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15211     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15212     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15213     default: llvm_unreachable("unexpected overflowing operator");
15214     }
15215     if (Inverted)
15216       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15217     if (CondOpcode == ISD::UMULO)
15218       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15219                           MVT::i32);
15220     else
15221       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15222
15223     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15224
15225     if (CondOpcode == ISD::UMULO)
15226       Cond = X86Op.getValue(2);
15227     else
15228       Cond = X86Op.getValue(1);
15229
15230     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15231     addTest = false;
15232   } else {
15233     unsigned CondOpc;
15234     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15235       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15236       if (CondOpc == ISD::OR) {
15237         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15238         // two branches instead of an explicit OR instruction with a
15239         // separate test.
15240         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15241             isX86LogicalCmp(Cmp)) {
15242           CC = Cond.getOperand(0).getOperand(0);
15243           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15244                               Chain, Dest, CC, Cmp);
15245           CC = Cond.getOperand(1).getOperand(0);
15246           Cond = Cmp;
15247           addTest = false;
15248         }
15249       } else { // ISD::AND
15250         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15251         // two branches instead of an explicit AND instruction with a
15252         // separate test. However, we only do this if this block doesn't
15253         // have a fall-through edge, because this requires an explicit
15254         // jmp when the condition is false.
15255         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15256             isX86LogicalCmp(Cmp) &&
15257             Op.getNode()->hasOneUse()) {
15258           X86::CondCode CCode =
15259             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15260           CCode = X86::GetOppositeBranchCondition(CCode);
15261           CC = DAG.getConstant(CCode, dl, MVT::i8);
15262           SDNode *User = *Op.getNode()->use_begin();
15263           // Look for an unconditional branch following this conditional branch.
15264           // We need this because we need to reverse the successors in order
15265           // to implement FCMP_OEQ.
15266           if (User->getOpcode() == ISD::BR) {
15267             SDValue FalseBB = User->getOperand(1);
15268             SDNode *NewBR =
15269               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15270             assert(NewBR == User);
15271             (void)NewBR;
15272             Dest = FalseBB;
15273
15274             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15275                                 Chain, Dest, CC, Cmp);
15276             X86::CondCode CCode =
15277               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15278             CCode = X86::GetOppositeBranchCondition(CCode);
15279             CC = DAG.getConstant(CCode, dl, MVT::i8);
15280             Cond = Cmp;
15281             addTest = false;
15282           }
15283         }
15284       }
15285     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15286       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15287       // It should be transformed during dag combiner except when the condition
15288       // is set by a arithmetics with overflow node.
15289       X86::CondCode CCode =
15290         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15291       CCode = X86::GetOppositeBranchCondition(CCode);
15292       CC = DAG.getConstant(CCode, dl, MVT::i8);
15293       Cond = Cond.getOperand(0).getOperand(1);
15294       addTest = false;
15295     } else if (Cond.getOpcode() == ISD::SETCC &&
15296                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15297       // For FCMP_OEQ, we can emit
15298       // two branches instead of an explicit AND instruction with a
15299       // separate test. However, we only do this if this block doesn't
15300       // have a fall-through edge, because this requires an explicit
15301       // jmp when the condition is false.
15302       if (Op.getNode()->hasOneUse()) {
15303         SDNode *User = *Op.getNode()->use_begin();
15304         // Look for an unconditional branch following this conditional branch.
15305         // We need this because we need to reverse the successors in order
15306         // to implement FCMP_OEQ.
15307         if (User->getOpcode() == ISD::BR) {
15308           SDValue FalseBB = User->getOperand(1);
15309           SDNode *NewBR =
15310             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15311           assert(NewBR == User);
15312           (void)NewBR;
15313           Dest = FalseBB;
15314
15315           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15316                                     Cond.getOperand(0), Cond.getOperand(1));
15317           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15318           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15319           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15320                               Chain, Dest, CC, Cmp);
15321           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15322           Cond = Cmp;
15323           addTest = false;
15324         }
15325       }
15326     } else if (Cond.getOpcode() == ISD::SETCC &&
15327                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15328       // For FCMP_UNE, we can emit
15329       // two branches instead of an explicit AND instruction with a
15330       // separate test. However, we only do this if this block doesn't
15331       // have a fall-through edge, because this requires an explicit
15332       // jmp when the condition is false.
15333       if (Op.getNode()->hasOneUse()) {
15334         SDNode *User = *Op.getNode()->use_begin();
15335         // Look for an unconditional branch following this conditional branch.
15336         // We need this because we need to reverse the successors in order
15337         // to implement FCMP_UNE.
15338         if (User->getOpcode() == ISD::BR) {
15339           SDValue FalseBB = User->getOperand(1);
15340           SDNode *NewBR =
15341             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15342           assert(NewBR == User);
15343           (void)NewBR;
15344
15345           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15346                                     Cond.getOperand(0), Cond.getOperand(1));
15347           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15348           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15349           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15350                               Chain, Dest, CC, Cmp);
15351           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15352           Cond = Cmp;
15353           addTest = false;
15354           Dest = FalseBB;
15355         }
15356       }
15357     }
15358   }
15359
15360   if (addTest) {
15361     // Look pass the truncate if the high bits are known zero.
15362     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15363         Cond = Cond.getOperand(0);
15364
15365     // We know the result of AND is compared against zero. Try to match
15366     // it to BT.
15367     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15368       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15369       if (NewSetCC.getNode()) {
15370         CC = NewSetCC.getOperand(0);
15371         Cond = NewSetCC.getOperand(1);
15372         addTest = false;
15373       }
15374     }
15375   }
15376
15377   if (addTest) {
15378     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15379     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15380     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15381   }
15382   Cond = ConvertCmpIfNecessary(Cond, DAG);
15383   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15384                      Chain, Dest, CC, Cond);
15385 }
15386
15387 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15388 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15389 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15390 // that the guard pages used by the OS virtual memory manager are allocated in
15391 // correct sequence.
15392 SDValue
15393 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15394                                            SelectionDAG &DAG) const {
15395   MachineFunction &MF = DAG.getMachineFunction();
15396   bool SplitStack = MF.shouldSplitStack();
15397   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15398                SplitStack;
15399   SDLoc dl(Op);
15400
15401   if (!Lower) {
15402     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15403     SDNode* Node = Op.getNode();
15404
15405     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15406     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15407         " not tell us which reg is the stack pointer!");
15408     EVT VT = Node->getValueType(0);
15409     SDValue Tmp1 = SDValue(Node, 0);
15410     SDValue Tmp2 = SDValue(Node, 1);
15411     SDValue Tmp3 = Node->getOperand(2);
15412     SDValue Chain = Tmp1.getOperand(0);
15413
15414     // Chain the dynamic stack allocation so that it doesn't modify the stack
15415     // pointer when other instructions are using the stack.
15416     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15417         SDLoc(Node));
15418
15419     SDValue Size = Tmp2.getOperand(1);
15420     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15421     Chain = SP.getValue(1);
15422     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15423     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15424     unsigned StackAlign = TFI.getStackAlignment();
15425     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15426     if (Align > StackAlign)
15427       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15428           DAG.getConstant(-(uint64_t)Align, dl, VT));
15429     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15430
15431     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15432         DAG.getIntPtrConstant(0, dl, true), SDValue(),
15433         SDLoc(Node));
15434
15435     SDValue Ops[2] = { Tmp1, Tmp2 };
15436     return DAG.getMergeValues(Ops, dl);
15437   }
15438
15439   // Get the inputs.
15440   SDValue Chain = Op.getOperand(0);
15441   SDValue Size  = Op.getOperand(1);
15442   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15443   EVT VT = Op.getNode()->getValueType(0);
15444
15445   bool Is64Bit = Subtarget->is64Bit();
15446   MVT SPTy = getPointerTy(DAG.getDataLayout());
15447
15448   if (SplitStack) {
15449     MachineRegisterInfo &MRI = MF.getRegInfo();
15450
15451     if (Is64Bit) {
15452       // The 64 bit implementation of segmented stacks needs to clobber both r10
15453       // r11. This makes it impossible to use it along with nested parameters.
15454       const Function *F = MF.getFunction();
15455
15456       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15457            I != E; ++I)
15458         if (I->hasNestAttr())
15459           report_fatal_error("Cannot use segmented stacks with functions that "
15460                              "have nested arguments.");
15461     }
15462
15463     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15464     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15465     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15466     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15467                                 DAG.getRegister(Vreg, SPTy));
15468     SDValue Ops1[2] = { Value, Chain };
15469     return DAG.getMergeValues(Ops1, dl);
15470   } else {
15471     SDValue Flag;
15472     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15473
15474     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15475     Flag = Chain.getValue(1);
15476     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15477
15478     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15479
15480     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15481     unsigned SPReg = RegInfo->getStackRegister();
15482     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15483     Chain = SP.getValue(1);
15484
15485     if (Align) {
15486       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15487                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15488       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15489     }
15490
15491     SDValue Ops1[2] = { SP, Chain };
15492     return DAG.getMergeValues(Ops1, dl);
15493   }
15494 }
15495
15496 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15497   MachineFunction &MF = DAG.getMachineFunction();
15498   auto PtrVT = getPointerTy(MF.getDataLayout());
15499   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15500
15501   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15502   SDLoc DL(Op);
15503
15504   if (!Subtarget->is64Bit() ||
15505       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15506     // vastart just stores the address of the VarArgsFrameIndex slot into the
15507     // memory location argument.
15508     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15509     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15510                         MachinePointerInfo(SV), false, false, 0);
15511   }
15512
15513   // __va_list_tag:
15514   //   gp_offset         (0 - 6 * 8)
15515   //   fp_offset         (48 - 48 + 8 * 16)
15516   //   overflow_arg_area (point to parameters coming in memory).
15517   //   reg_save_area
15518   SmallVector<SDValue, 8> MemOps;
15519   SDValue FIN = Op.getOperand(1);
15520   // Store gp_offset
15521   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15522                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15523                                                DL, MVT::i32),
15524                                FIN, MachinePointerInfo(SV), false, false, 0);
15525   MemOps.push_back(Store);
15526
15527   // Store fp_offset
15528   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15529   Store = DAG.getStore(Op.getOperand(0), DL,
15530                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15531                                        MVT::i32),
15532                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15533   MemOps.push_back(Store);
15534
15535   // Store ptr to overflow_arg_area
15536   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15537   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15538   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15539                        MachinePointerInfo(SV, 8),
15540                        false, false, 0);
15541   MemOps.push_back(Store);
15542
15543   // Store ptr to reg_save_area.
15544   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15545       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15546   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15547   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15548       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15549   MemOps.push_back(Store);
15550   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15551 }
15552
15553 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15554   assert(Subtarget->is64Bit() &&
15555          "LowerVAARG only handles 64-bit va_arg!");
15556   assert(Op.getNode()->getNumOperands() == 4);
15557
15558   MachineFunction &MF = DAG.getMachineFunction();
15559   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15560     // The Win64 ABI uses char* instead of a structure.
15561     return DAG.expandVAArg(Op.getNode());
15562
15563   SDValue Chain = Op.getOperand(0);
15564   SDValue SrcPtr = Op.getOperand(1);
15565   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15566   unsigned Align = Op.getConstantOperandVal(3);
15567   SDLoc dl(Op);
15568
15569   EVT ArgVT = Op.getNode()->getValueType(0);
15570   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15571   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15572   uint8_t ArgMode;
15573
15574   // Decide which area this value should be read from.
15575   // TODO: Implement the AMD64 ABI in its entirety. This simple
15576   // selection mechanism works only for the basic types.
15577   if (ArgVT == MVT::f80) {
15578     llvm_unreachable("va_arg for f80 not yet implemented");
15579   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15580     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15581   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15582     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15583   } else {
15584     llvm_unreachable("Unhandled argument type in LowerVAARG");
15585   }
15586
15587   if (ArgMode == 2) {
15588     // Sanity Check: Make sure using fp_offset makes sense.
15589     assert(!Subtarget->useSoftFloat() &&
15590            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15591            Subtarget->hasSSE1());
15592   }
15593
15594   // Insert VAARG_64 node into the DAG
15595   // VAARG_64 returns two values: Variable Argument Address, Chain
15596   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15597                        DAG.getConstant(ArgMode, dl, MVT::i8),
15598                        DAG.getConstant(Align, dl, MVT::i32)};
15599   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15600   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15601                                           VTs, InstOps, MVT::i64,
15602                                           MachinePointerInfo(SV),
15603                                           /*Align=*/0,
15604                                           /*Volatile=*/false,
15605                                           /*ReadMem=*/true,
15606                                           /*WriteMem=*/true);
15607   Chain = VAARG.getValue(1);
15608
15609   // Load the next argument and return it
15610   return DAG.getLoad(ArgVT, dl,
15611                      Chain,
15612                      VAARG,
15613                      MachinePointerInfo(),
15614                      false, false, false, 0);
15615 }
15616
15617 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15618                            SelectionDAG &DAG) {
15619   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15620   // where a va_list is still an i8*.
15621   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15622   if (Subtarget->isCallingConvWin64(
15623         DAG.getMachineFunction().getFunction()->getCallingConv()))
15624     // Probably a Win64 va_copy.
15625     return DAG.expandVACopy(Op.getNode());
15626
15627   SDValue Chain = Op.getOperand(0);
15628   SDValue DstPtr = Op.getOperand(1);
15629   SDValue SrcPtr = Op.getOperand(2);
15630   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15631   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15632   SDLoc DL(Op);
15633
15634   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15635                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15636                        false, false,
15637                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15638 }
15639
15640 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15641 // amount is a constant. Takes immediate version of shift as input.
15642 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15643                                           SDValue SrcOp, uint64_t ShiftAmt,
15644                                           SelectionDAG &DAG) {
15645   MVT ElementType = VT.getVectorElementType();
15646
15647   // Fold this packed shift into its first operand if ShiftAmt is 0.
15648   if (ShiftAmt == 0)
15649     return SrcOp;
15650
15651   // Check for ShiftAmt >= element width
15652   if (ShiftAmt >= ElementType.getSizeInBits()) {
15653     if (Opc == X86ISD::VSRAI)
15654       ShiftAmt = ElementType.getSizeInBits() - 1;
15655     else
15656       return DAG.getConstant(0, dl, VT);
15657   }
15658
15659   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15660          && "Unknown target vector shift-by-constant node");
15661
15662   // Fold this packed vector shift into a build vector if SrcOp is a
15663   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15664   if (VT == SrcOp.getSimpleValueType() &&
15665       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15666     SmallVector<SDValue, 8> Elts;
15667     unsigned NumElts = SrcOp->getNumOperands();
15668     ConstantSDNode *ND;
15669
15670     switch(Opc) {
15671     default: llvm_unreachable(nullptr);
15672     case X86ISD::VSHLI:
15673       for (unsigned i=0; i!=NumElts; ++i) {
15674         SDValue CurrentOp = SrcOp->getOperand(i);
15675         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15676           Elts.push_back(CurrentOp);
15677           continue;
15678         }
15679         ND = cast<ConstantSDNode>(CurrentOp);
15680         const APInt &C = ND->getAPIntValue();
15681         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15682       }
15683       break;
15684     case X86ISD::VSRLI:
15685       for (unsigned i=0; i!=NumElts; ++i) {
15686         SDValue CurrentOp = SrcOp->getOperand(i);
15687         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15688           Elts.push_back(CurrentOp);
15689           continue;
15690         }
15691         ND = cast<ConstantSDNode>(CurrentOp);
15692         const APInt &C = ND->getAPIntValue();
15693         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15694       }
15695       break;
15696     case X86ISD::VSRAI:
15697       for (unsigned i=0; i!=NumElts; ++i) {
15698         SDValue CurrentOp = SrcOp->getOperand(i);
15699         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15700           Elts.push_back(CurrentOp);
15701           continue;
15702         }
15703         ND = cast<ConstantSDNode>(CurrentOp);
15704         const APInt &C = ND->getAPIntValue();
15705         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15706       }
15707       break;
15708     }
15709
15710     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15711   }
15712
15713   return DAG.getNode(Opc, dl, VT, SrcOp,
15714                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15715 }
15716
15717 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15718 // may or may not be a constant. Takes immediate version of shift as input.
15719 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15720                                    SDValue SrcOp, SDValue ShAmt,
15721                                    SelectionDAG &DAG) {
15722   MVT SVT = ShAmt.getSimpleValueType();
15723   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15724
15725   // Catch shift-by-constant.
15726   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15727     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15728                                       CShAmt->getZExtValue(), DAG);
15729
15730   // Change opcode to non-immediate version
15731   switch (Opc) {
15732     default: llvm_unreachable("Unknown target vector shift node");
15733     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15734     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15735     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15736   }
15737
15738   const X86Subtarget &Subtarget =
15739       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15740   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15741       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15742     // Let the shuffle legalizer expand this shift amount node.
15743     SDValue Op0 = ShAmt.getOperand(0);
15744     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15745     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15746   } else {
15747     // Need to build a vector containing shift amount.
15748     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15749     SmallVector<SDValue, 4> ShOps;
15750     ShOps.push_back(ShAmt);
15751     if (SVT == MVT::i32) {
15752       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15753       ShOps.push_back(DAG.getUNDEF(SVT));
15754     }
15755     ShOps.push_back(DAG.getUNDEF(SVT));
15756
15757     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15758     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15759   }
15760
15761   // The return type has to be a 128-bit type with the same element
15762   // type as the input type.
15763   MVT EltVT = VT.getVectorElementType();
15764   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15765
15766   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15767   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15768 }
15769
15770 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15771 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15772 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15773 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15774                                     SDValue PreservedSrc,
15775                                     const X86Subtarget *Subtarget,
15776                                     SelectionDAG &DAG) {
15777     EVT VT = Op.getValueType();
15778     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15779                                   MVT::i1, VT.getVectorNumElements());
15780     SDValue VMask = SDValue();
15781     unsigned OpcodeSelect = ISD::VSELECT;
15782     SDLoc dl(Op);
15783
15784     assert(MaskVT.isSimple() && "invalid mask type");
15785
15786     if (isAllOnes(Mask))
15787       return Op;
15788
15789     if (MaskVT.bitsGT(Mask.getValueType())) {
15790       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15791                                          MaskVT.getSizeInBits());
15792       VMask = DAG.getBitcast(MaskVT,
15793                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15794     } else {
15795       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15796                                        Mask.getValueType().getSizeInBits());
15797       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15798       // are extracted by EXTRACT_SUBVECTOR.
15799       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15800                           DAG.getBitcast(BitcastVT, Mask),
15801                           DAG.getIntPtrConstant(0, dl));
15802     }
15803
15804     switch (Op.getOpcode()) {
15805       default: break;
15806       case X86ISD::PCMPEQM:
15807       case X86ISD::PCMPGTM:
15808       case X86ISD::CMPM:
15809       case X86ISD::CMPMU:
15810         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15811       case X86ISD::VFPCLASS:
15812         return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
15813       case X86ISD::VTRUNC:
15814       case X86ISD::VTRUNCS:
15815       case X86ISD::VTRUNCUS:
15816         // We can't use ISD::VSELECT here because it is not always "Legal"
15817         // for the destination type. For example vpmovqb require only AVX512
15818         // and vselect that can operate on byte element type require BWI
15819         OpcodeSelect = X86ISD::SELECT;
15820         break;
15821     }
15822     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15823       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15824     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15825 }
15826
15827 /// \brief Creates an SDNode for a predicated scalar operation.
15828 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15829 /// The mask is coming as MVT::i8 and it should be truncated
15830 /// to MVT::i1 while lowering masking intrinsics.
15831 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15832 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15833 /// for a scalar instruction.
15834 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15835                                     SDValue PreservedSrc,
15836                                     const X86Subtarget *Subtarget,
15837                                     SelectionDAG &DAG) {
15838   if (isAllOnes(Mask))
15839     return Op;
15840
15841   EVT VT = Op.getValueType();
15842   SDLoc dl(Op);
15843   // The mask should be of type MVT::i1
15844   SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15845
15846   if (Op.getOpcode() == X86ISD::FSETCC)
15847     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
15848
15849   if (PreservedSrc.getOpcode() == ISD::UNDEF)
15850     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15851   return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15852 }
15853
15854 static int getSEHRegistrationNodeSize(const Function *Fn) {
15855   if (!Fn->hasPersonalityFn())
15856     report_fatal_error(
15857         "querying registration node size for function without personality");
15858   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15859   // WinEHStatePass for the full struct definition.
15860   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15861   case EHPersonality::MSVC_X86SEH: return 24;
15862   case EHPersonality::MSVC_CXX: return 16;
15863   default: break;
15864   }
15865   report_fatal_error("can only recover FP for MSVC EH personality functions");
15866 }
15867
15868 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15869 /// function or when returning to a parent frame after catching an exception, we
15870 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15871 /// Here's the math:
15872 ///   RegNodeBase = EntryEBP - RegNodeSize
15873 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15874 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15875 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15876 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15877                                    SDValue EntryEBP) {
15878   MachineFunction &MF = DAG.getMachineFunction();
15879   SDLoc dl;
15880
15881   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15882   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15883
15884   // It's possible that the parent function no longer has a personality function
15885   // if the exceptional code was optimized away, in which case we just return
15886   // the incoming EBP.
15887   if (!Fn->hasPersonalityFn())
15888     return EntryEBP;
15889
15890   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15891
15892   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15893   // registration.
15894   MCSymbol *OffsetSym =
15895       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15896           GlobalValue::getRealLinkageName(Fn->getName()));
15897   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15898   SDValue RegNodeFrameOffset =
15899       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15900
15901   // RegNodeBase = EntryEBP - RegNodeSize
15902   // ParentFP = RegNodeBase - RegNodeFrameOffset
15903   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15904                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15905   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15906 }
15907
15908 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15909                                        SelectionDAG &DAG) {
15910   SDLoc dl(Op);
15911   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15912   EVT VT = Op.getValueType();
15913   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15914   if (IntrData) {
15915     switch(IntrData->Type) {
15916     case INTR_TYPE_1OP:
15917       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15918     case INTR_TYPE_2OP:
15919       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15920         Op.getOperand(2));
15921     case INTR_TYPE_2OP_IMM8:
15922       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15923                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
15924     case INTR_TYPE_3OP:
15925       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15926         Op.getOperand(2), Op.getOperand(3));
15927     case INTR_TYPE_4OP:
15928       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15929         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15930     case INTR_TYPE_1OP_MASK_RM: {
15931       SDValue Src = Op.getOperand(1);
15932       SDValue PassThru = Op.getOperand(2);
15933       SDValue Mask = Op.getOperand(3);
15934       SDValue RoundingMode;
15935       // We allways add rounding mode to the Node.
15936       // If the rounding mode is not specified, we add the
15937       // "current direction" mode.
15938       if (Op.getNumOperands() == 4)
15939         RoundingMode =
15940           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15941       else
15942         RoundingMode = Op.getOperand(4);
15943       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15944       if (IntrWithRoundingModeOpcode != 0)
15945         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15946             X86::STATIC_ROUNDING::CUR_DIRECTION)
15947           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15948                                       dl, Op.getValueType(), Src, RoundingMode),
15949                                       Mask, PassThru, Subtarget, DAG);
15950       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15951                                               RoundingMode),
15952                                   Mask, PassThru, Subtarget, DAG);
15953     }
15954     case INTR_TYPE_1OP_MASK: {
15955       SDValue Src = Op.getOperand(1);
15956       SDValue PassThru = Op.getOperand(2);
15957       SDValue Mask = Op.getOperand(3);
15958       // We add rounding mode to the Node when
15959       //   - RM Opcode is specified and
15960       //   - RM is not "current direction".
15961       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15962       if (IntrWithRoundingModeOpcode != 0) {
15963         SDValue Rnd = Op.getOperand(4);
15964         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15965         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15966           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15967                                       dl, Op.getValueType(),
15968                                       Src, Rnd),
15969                                       Mask, PassThru, Subtarget, DAG);
15970         }
15971       }
15972       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15973                                   Mask, PassThru, Subtarget, DAG);
15974     }
15975     case INTR_TYPE_SCALAR_MASK: {
15976       SDValue Src1 = Op.getOperand(1);
15977       SDValue Src2 = Op.getOperand(2);
15978       SDValue passThru = Op.getOperand(3);
15979       SDValue Mask = Op.getOperand(4);
15980       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
15981                                   Mask, passThru, Subtarget, DAG);
15982     }
15983     case INTR_TYPE_SCALAR_MASK_RM: {
15984       SDValue Src1 = Op.getOperand(1);
15985       SDValue Src2 = Op.getOperand(2);
15986       SDValue Src0 = Op.getOperand(3);
15987       SDValue Mask = Op.getOperand(4);
15988       // There are 2 kinds of intrinsics in this group:
15989       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15990       // (2) With rounding mode and sae - 7 operands.
15991       if (Op.getNumOperands() == 6) {
15992         SDValue Sae  = Op.getOperand(5);
15993         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15994         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15995                                                 Sae),
15996                                     Mask, Src0, Subtarget, DAG);
15997       }
15998       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15999       SDValue RoundingMode  = Op.getOperand(5);
16000       SDValue Sae  = Op.getOperand(6);
16001       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16002                                               RoundingMode, Sae),
16003                                   Mask, Src0, Subtarget, DAG);
16004     }
16005     case INTR_TYPE_2OP_MASK: {
16006       SDValue Src1 = Op.getOperand(1);
16007       SDValue Src2 = Op.getOperand(2);
16008       SDValue PassThru = Op.getOperand(3);
16009       SDValue Mask = Op.getOperand(4);
16010       // We specify 2 possible opcodes for intrinsics with rounding modes.
16011       // First, we check if the intrinsic may have non-default rounding mode,
16012       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16013       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16014       if (IntrWithRoundingModeOpcode != 0) {
16015         SDValue Rnd = Op.getOperand(5);
16016         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16017         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16018           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16019                                       dl, Op.getValueType(),
16020                                       Src1, Src2, Rnd),
16021                                       Mask, PassThru, Subtarget, DAG);
16022         }
16023       }
16024       // TODO: Intrinsics should have fast-math-flags to propagate.
16025       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16026                                   Mask, PassThru, Subtarget, DAG);
16027     }
16028     case INTR_TYPE_2OP_MASK_RM: {
16029       SDValue Src1 = Op.getOperand(1);
16030       SDValue Src2 = Op.getOperand(2);
16031       SDValue PassThru = Op.getOperand(3);
16032       SDValue Mask = Op.getOperand(4);
16033       // We specify 2 possible modes for intrinsics, with/without rounding modes.
16034       // First, we check if the intrinsic have rounding mode (6 operands),
16035       // if not, we set rounding mode to "current".
16036       SDValue Rnd;
16037       if (Op.getNumOperands() == 6)
16038         Rnd = Op.getOperand(5);
16039       else
16040         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16041       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16042                                               Src1, Src2, Rnd),
16043                                   Mask, PassThru, Subtarget, DAG);
16044     }
16045     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16046       SDValue Src1 = Op.getOperand(1);
16047       SDValue Src2 = Op.getOperand(2);
16048       SDValue Src3 = Op.getOperand(3);
16049       SDValue PassThru = Op.getOperand(4);
16050       SDValue Mask = Op.getOperand(5);
16051       SDValue Sae  = Op.getOperand(6);
16052
16053       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16054                                               Src2, Src3, Sae),
16055                                   Mask, PassThru, Subtarget, DAG);
16056     }
16057     case INTR_TYPE_3OP_MASK_RM: {
16058       SDValue Src1 = Op.getOperand(1);
16059       SDValue Src2 = Op.getOperand(2);
16060       SDValue Imm = Op.getOperand(3);
16061       SDValue PassThru = Op.getOperand(4);
16062       SDValue Mask = Op.getOperand(5);
16063       // We specify 2 possible modes for intrinsics, with/without rounding modes.
16064       // First, we check if the intrinsic have rounding mode (7 operands),
16065       // if not, we set rounding mode to "current".
16066       SDValue Rnd;
16067       if (Op.getNumOperands() == 7)
16068         Rnd = Op.getOperand(6);
16069       else
16070         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16071       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16072         Src1, Src2, Imm, Rnd),
16073         Mask, PassThru, Subtarget, DAG);
16074     }
16075     case INTR_TYPE_3OP_IMM8_MASK:
16076     case INTR_TYPE_3OP_MASK:
16077     case INSERT_SUBVEC: {
16078       SDValue Src1 = Op.getOperand(1);
16079       SDValue Src2 = Op.getOperand(2);
16080       SDValue Src3 = Op.getOperand(3);
16081       SDValue PassThru = Op.getOperand(4);
16082       SDValue Mask = Op.getOperand(5);
16083
16084       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16085         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16086       else if (IntrData->Type == INSERT_SUBVEC) {
16087         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16088         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16089         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16090         Imm *= Src2.getValueType().getVectorNumElements();
16091         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16092       }
16093
16094       // We specify 2 possible opcodes for intrinsics with rounding modes.
16095       // First, we check if the intrinsic may have non-default rounding mode,
16096       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16097       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16098       if (IntrWithRoundingModeOpcode != 0) {
16099         SDValue Rnd = Op.getOperand(6);
16100         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16101         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16102           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16103                                       dl, Op.getValueType(),
16104                                       Src1, Src2, Src3, Rnd),
16105                                       Mask, PassThru, Subtarget, DAG);
16106         }
16107       }
16108       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16109                                               Src1, Src2, Src3),
16110                                   Mask, PassThru, Subtarget, DAG);
16111     }
16112     case VPERM_3OP_MASKZ:
16113     case VPERM_3OP_MASK:
16114     case FMA_OP_MASK3:
16115     case FMA_OP_MASKZ:
16116     case FMA_OP_MASK: {
16117       SDValue Src1 = Op.getOperand(1);
16118       SDValue Src2 = Op.getOperand(2);
16119       SDValue Src3 = Op.getOperand(3);
16120       SDValue Mask = Op.getOperand(4);
16121       EVT VT = Op.getValueType();
16122       SDValue PassThru = SDValue();
16123
16124       // set PassThru element
16125       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
16126         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16127       else if (IntrData->Type == FMA_OP_MASK3)
16128         PassThru = Src3;
16129       else
16130         PassThru = Src1;
16131
16132       // We specify 2 possible opcodes for intrinsics with rounding modes.
16133       // First, we check if the intrinsic may have non-default rounding mode,
16134       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16135       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16136       if (IntrWithRoundingModeOpcode != 0) {
16137         SDValue Rnd = Op.getOperand(5);
16138         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16139             X86::STATIC_ROUNDING::CUR_DIRECTION)
16140           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16141                                                   dl, Op.getValueType(),
16142                                                   Src1, Src2, Src3, Rnd),
16143                                       Mask, PassThru, Subtarget, DAG);
16144       }
16145       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16146                                               dl, Op.getValueType(),
16147                                               Src1, Src2, Src3),
16148                                   Mask, PassThru, Subtarget, DAG);
16149     }
16150     case FPCLASS: {
16151       // FPclass intrinsics with mask
16152        SDValue Src1 = Op.getOperand(1);
16153        EVT VT = Src1.getValueType();
16154        EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16155                                       VT.getVectorNumElements());
16156        SDValue Imm = Op.getOperand(2);
16157        SDValue Mask = Op.getOperand(3);
16158        EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16159                                         Mask.getValueType().getSizeInBits());
16160        SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16161        SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16162                                                  DAG.getTargetConstant(0, dl, MaskVT),
16163                                                  Subtarget, DAG);
16164        SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16165                                  DAG.getUNDEF(BitcastVT), FPclassMask,
16166                                  DAG.getIntPtrConstant(0, dl));
16167        return DAG.getBitcast(Op.getValueType(), Res);
16168     }
16169     case CMP_MASK:
16170     case CMP_MASK_CC: {
16171       // Comparison intrinsics with masks.
16172       // Example of transformation:
16173       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16174       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16175       // (i8 (bitcast
16176       //   (v8i1 (insert_subvector undef,
16177       //           (v2i1 (and (PCMPEQM %a, %b),
16178       //                      (extract_subvector
16179       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16180       EVT VT = Op.getOperand(1).getValueType();
16181       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16182                                     VT.getVectorNumElements());
16183       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16184       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16185                                        Mask.getValueType().getSizeInBits());
16186       SDValue Cmp;
16187       if (IntrData->Type == CMP_MASK_CC) {
16188         SDValue CC = Op.getOperand(3);
16189         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16190         // We specify 2 possible opcodes for intrinsics with rounding modes.
16191         // First, we check if the intrinsic may have non-default rounding mode,
16192         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16193         if (IntrData->Opc1 != 0) {
16194           SDValue Rnd = Op.getOperand(5);
16195           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16196               X86::STATIC_ROUNDING::CUR_DIRECTION)
16197             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16198                               Op.getOperand(2), CC, Rnd);
16199         }
16200         //default rounding mode
16201         if(!Cmp.getNode())
16202             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16203                               Op.getOperand(2), CC);
16204
16205       } else {
16206         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16207         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16208                           Op.getOperand(2));
16209       }
16210       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16211                                              DAG.getTargetConstant(0, dl,
16212                                                                    MaskVT),
16213                                              Subtarget, DAG);
16214       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16215                                 DAG.getUNDEF(BitcastVT), CmpMask,
16216                                 DAG.getIntPtrConstant(0, dl));
16217       return DAG.getBitcast(Op.getValueType(), Res);
16218     }
16219     case CMP_MASK_SCALAR_CC: {
16220       SDValue Src1 = Op.getOperand(1);
16221       SDValue Src2 = Op.getOperand(2);
16222       SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16223       SDValue Mask = Op.getOperand(4);
16224
16225       SDValue Cmp;
16226       if (IntrData->Opc1 != 0) {
16227         SDValue Rnd = Op.getOperand(5);
16228         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16229             X86::STATIC_ROUNDING::CUR_DIRECTION)
16230           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16231       }
16232       //default rounding mode
16233       if(!Cmp.getNode())
16234         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16235
16236       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16237                                              DAG.getTargetConstant(0, dl,
16238                                                                    MVT::i1),
16239                                              Subtarget, DAG);
16240
16241       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16242                          DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16243                          DAG.getValueType(MVT::i1));
16244     }
16245     case COMI: { // Comparison intrinsics
16246       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16247       SDValue LHS = Op.getOperand(1);
16248       SDValue RHS = Op.getOperand(2);
16249       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16250       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16251       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16252       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16253                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16254       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16255     }
16256     case VSHIFT:
16257       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16258                                  Op.getOperand(1), Op.getOperand(2), DAG);
16259     case VSHIFT_MASK:
16260       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16261                                                       Op.getSimpleValueType(),
16262                                                       Op.getOperand(1),
16263                                                       Op.getOperand(2), DAG),
16264                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16265                                   DAG);
16266     case COMPRESS_EXPAND_IN_REG: {
16267       SDValue Mask = Op.getOperand(3);
16268       SDValue DataToCompress = Op.getOperand(1);
16269       SDValue PassThru = Op.getOperand(2);
16270       if (isAllOnes(Mask)) // return data as is
16271         return Op.getOperand(1);
16272
16273       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16274                                               DataToCompress),
16275                                   Mask, PassThru, Subtarget, DAG);
16276     }
16277     case BLEND: {
16278       SDValue Mask = Op.getOperand(3);
16279       EVT VT = Op.getValueType();
16280       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16281                                     VT.getVectorNumElements());
16282       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16283                                        Mask.getValueType().getSizeInBits());
16284       SDLoc dl(Op);
16285       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16286                                   DAG.getBitcast(BitcastVT, Mask),
16287                                   DAG.getIntPtrConstant(0, dl));
16288       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16289                          Op.getOperand(2));
16290     }
16291     default:
16292       break;
16293     }
16294   }
16295
16296   switch (IntNo) {
16297   default: return SDValue();    // Don't custom lower most intrinsics.
16298
16299   case Intrinsic::x86_avx2_permd:
16300   case Intrinsic::x86_avx2_permps:
16301     // Operands intentionally swapped. Mask is last operand to intrinsic,
16302     // but second operand for node/instruction.
16303     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16304                        Op.getOperand(2), Op.getOperand(1));
16305
16306   // ptest and testp intrinsics. The intrinsic these come from are designed to
16307   // return an integer value, not just an instruction so lower it to the ptest
16308   // or testp pattern and a setcc for the result.
16309   case Intrinsic::x86_sse41_ptestz:
16310   case Intrinsic::x86_sse41_ptestc:
16311   case Intrinsic::x86_sse41_ptestnzc:
16312   case Intrinsic::x86_avx_ptestz_256:
16313   case Intrinsic::x86_avx_ptestc_256:
16314   case Intrinsic::x86_avx_ptestnzc_256:
16315   case Intrinsic::x86_avx_vtestz_ps:
16316   case Intrinsic::x86_avx_vtestc_ps:
16317   case Intrinsic::x86_avx_vtestnzc_ps:
16318   case Intrinsic::x86_avx_vtestz_pd:
16319   case Intrinsic::x86_avx_vtestc_pd:
16320   case Intrinsic::x86_avx_vtestnzc_pd:
16321   case Intrinsic::x86_avx_vtestz_ps_256:
16322   case Intrinsic::x86_avx_vtestc_ps_256:
16323   case Intrinsic::x86_avx_vtestnzc_ps_256:
16324   case Intrinsic::x86_avx_vtestz_pd_256:
16325   case Intrinsic::x86_avx_vtestc_pd_256:
16326   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16327     bool IsTestPacked = false;
16328     unsigned X86CC;
16329     switch (IntNo) {
16330     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16331     case Intrinsic::x86_avx_vtestz_ps:
16332     case Intrinsic::x86_avx_vtestz_pd:
16333     case Intrinsic::x86_avx_vtestz_ps_256:
16334     case Intrinsic::x86_avx_vtestz_pd_256:
16335       IsTestPacked = true; // Fallthrough
16336     case Intrinsic::x86_sse41_ptestz:
16337     case Intrinsic::x86_avx_ptestz_256:
16338       // ZF = 1
16339       X86CC = X86::COND_E;
16340       break;
16341     case Intrinsic::x86_avx_vtestc_ps:
16342     case Intrinsic::x86_avx_vtestc_pd:
16343     case Intrinsic::x86_avx_vtestc_ps_256:
16344     case Intrinsic::x86_avx_vtestc_pd_256:
16345       IsTestPacked = true; // Fallthrough
16346     case Intrinsic::x86_sse41_ptestc:
16347     case Intrinsic::x86_avx_ptestc_256:
16348       // CF = 1
16349       X86CC = X86::COND_B;
16350       break;
16351     case Intrinsic::x86_avx_vtestnzc_ps:
16352     case Intrinsic::x86_avx_vtestnzc_pd:
16353     case Intrinsic::x86_avx_vtestnzc_ps_256:
16354     case Intrinsic::x86_avx_vtestnzc_pd_256:
16355       IsTestPacked = true; // Fallthrough
16356     case Intrinsic::x86_sse41_ptestnzc:
16357     case Intrinsic::x86_avx_ptestnzc_256:
16358       // ZF and CF = 0
16359       X86CC = X86::COND_A;
16360       break;
16361     }
16362
16363     SDValue LHS = Op.getOperand(1);
16364     SDValue RHS = Op.getOperand(2);
16365     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16366     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16367     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16368     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16369     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16370   }
16371   case Intrinsic::x86_avx512_kortestz_w:
16372   case Intrinsic::x86_avx512_kortestc_w: {
16373     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16374     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16375     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16376     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16377     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16378     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16379     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16380   }
16381
16382   case Intrinsic::x86_sse42_pcmpistria128:
16383   case Intrinsic::x86_sse42_pcmpestria128:
16384   case Intrinsic::x86_sse42_pcmpistric128:
16385   case Intrinsic::x86_sse42_pcmpestric128:
16386   case Intrinsic::x86_sse42_pcmpistrio128:
16387   case Intrinsic::x86_sse42_pcmpestrio128:
16388   case Intrinsic::x86_sse42_pcmpistris128:
16389   case Intrinsic::x86_sse42_pcmpestris128:
16390   case Intrinsic::x86_sse42_pcmpistriz128:
16391   case Intrinsic::x86_sse42_pcmpestriz128: {
16392     unsigned Opcode;
16393     unsigned X86CC;
16394     switch (IntNo) {
16395     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16396     case Intrinsic::x86_sse42_pcmpistria128:
16397       Opcode = X86ISD::PCMPISTRI;
16398       X86CC = X86::COND_A;
16399       break;
16400     case Intrinsic::x86_sse42_pcmpestria128:
16401       Opcode = X86ISD::PCMPESTRI;
16402       X86CC = X86::COND_A;
16403       break;
16404     case Intrinsic::x86_sse42_pcmpistric128:
16405       Opcode = X86ISD::PCMPISTRI;
16406       X86CC = X86::COND_B;
16407       break;
16408     case Intrinsic::x86_sse42_pcmpestric128:
16409       Opcode = X86ISD::PCMPESTRI;
16410       X86CC = X86::COND_B;
16411       break;
16412     case Intrinsic::x86_sse42_pcmpistrio128:
16413       Opcode = X86ISD::PCMPISTRI;
16414       X86CC = X86::COND_O;
16415       break;
16416     case Intrinsic::x86_sse42_pcmpestrio128:
16417       Opcode = X86ISD::PCMPESTRI;
16418       X86CC = X86::COND_O;
16419       break;
16420     case Intrinsic::x86_sse42_pcmpistris128:
16421       Opcode = X86ISD::PCMPISTRI;
16422       X86CC = X86::COND_S;
16423       break;
16424     case Intrinsic::x86_sse42_pcmpestris128:
16425       Opcode = X86ISD::PCMPESTRI;
16426       X86CC = X86::COND_S;
16427       break;
16428     case Intrinsic::x86_sse42_pcmpistriz128:
16429       Opcode = X86ISD::PCMPISTRI;
16430       X86CC = X86::COND_E;
16431       break;
16432     case Intrinsic::x86_sse42_pcmpestriz128:
16433       Opcode = X86ISD::PCMPESTRI;
16434       X86CC = X86::COND_E;
16435       break;
16436     }
16437     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16438     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16439     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16440     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16441                                 DAG.getConstant(X86CC, dl, MVT::i8),
16442                                 SDValue(PCMP.getNode(), 1));
16443     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16444   }
16445
16446   case Intrinsic::x86_sse42_pcmpistri128:
16447   case Intrinsic::x86_sse42_pcmpestri128: {
16448     unsigned Opcode;
16449     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16450       Opcode = X86ISD::PCMPISTRI;
16451     else
16452       Opcode = X86ISD::PCMPESTRI;
16453
16454     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16455     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16456     return DAG.getNode(Opcode, dl, VTs, NewOps);
16457   }
16458
16459   case Intrinsic::x86_seh_lsda: {
16460     // Compute the symbol for the LSDA. We know it'll get emitted later.
16461     MachineFunction &MF = DAG.getMachineFunction();
16462     SDValue Op1 = Op.getOperand(1);
16463     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16464     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16465         GlobalValue::getRealLinkageName(Fn->getName()));
16466
16467     // Generate a simple absolute symbol reference. This intrinsic is only
16468     // supported on 32-bit Windows, which isn't PIC.
16469     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16470     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16471   }
16472
16473   case Intrinsic::x86_seh_recoverfp: {
16474     SDValue FnOp = Op.getOperand(1);
16475     SDValue IncomingFPOp = Op.getOperand(2);
16476     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16477     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16478     if (!Fn)
16479       report_fatal_error(
16480           "llvm.x86.seh.recoverfp must take a function as the first argument");
16481     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16482   }
16483
16484   case Intrinsic::localaddress: {
16485     // Returns one of the stack, base, or frame pointer registers, depending on
16486     // which is used to reference local variables.
16487     MachineFunction &MF = DAG.getMachineFunction();
16488     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16489     unsigned Reg;
16490     if (RegInfo->hasBasePointer(MF))
16491       Reg = RegInfo->getBaseRegister();
16492     else // This function handles the SP or FP case.
16493       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16494     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16495   }
16496   }
16497 }
16498
16499 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16500                               SDValue Src, SDValue Mask, SDValue Base,
16501                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16502                               const X86Subtarget * Subtarget) {
16503   SDLoc dl(Op);
16504   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16505   if (!C)
16506     llvm_unreachable("Invalid scale type");
16507   unsigned ScaleVal = C->getZExtValue();
16508   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16509     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16510
16511   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16512   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16513                              Index.getSimpleValueType().getVectorNumElements());
16514   SDValue MaskInReg;
16515   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16516   if (MaskC)
16517     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16518   else {
16519     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16520                                      Mask.getValueType().getSizeInBits());
16521
16522     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16523     // are extracted by EXTRACT_SUBVECTOR.
16524     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16525                             DAG.getBitcast(BitcastVT, Mask),
16526                             DAG.getIntPtrConstant(0, dl));
16527   }
16528   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16529   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16530   SDValue Segment = DAG.getRegister(0, MVT::i32);
16531   if (Src.getOpcode() == ISD::UNDEF)
16532     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16533   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16534   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16535   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16536   return DAG.getMergeValues(RetOps, dl);
16537 }
16538
16539 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16540                                SDValue Src, SDValue Mask, SDValue Base,
16541                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16542   SDLoc dl(Op);
16543   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16544   if (!C)
16545     llvm_unreachable("Invalid scale type");
16546   unsigned ScaleVal = C->getZExtValue();
16547   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16548     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16549
16550   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16551   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16552   SDValue Segment = DAG.getRegister(0, MVT::i32);
16553   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16554                              Index.getSimpleValueType().getVectorNumElements());
16555   SDValue MaskInReg;
16556   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16557   if (MaskC)
16558     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16559   else {
16560     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16561                                      Mask.getValueType().getSizeInBits());
16562
16563     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16564     // are extracted by EXTRACT_SUBVECTOR.
16565     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16566                             DAG.getBitcast(BitcastVT, Mask),
16567                             DAG.getIntPtrConstant(0, dl));
16568   }
16569   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16570   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16571   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16572   return SDValue(Res, 1);
16573 }
16574
16575 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16576                                SDValue Mask, SDValue Base, SDValue Index,
16577                                SDValue ScaleOp, SDValue Chain) {
16578   SDLoc dl(Op);
16579   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16580   assert(C && "Invalid scale type");
16581   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16582   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16583   SDValue Segment = DAG.getRegister(0, MVT::i32);
16584   EVT MaskVT =
16585     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16586   SDValue MaskInReg;
16587   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16588   if (MaskC)
16589     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16590   else
16591     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16592   //SDVTList VTs = DAG.getVTList(MVT::Other);
16593   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16594   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16595   return SDValue(Res, 0);
16596 }
16597
16598 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16599 // read performance monitor counters (x86_rdpmc).
16600 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16601                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16602                               SmallVectorImpl<SDValue> &Results) {
16603   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16604   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16605   SDValue LO, HI;
16606
16607   // The ECX register is used to select the index of the performance counter
16608   // to read.
16609   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16610                                    N->getOperand(2));
16611   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16612
16613   // Reads the content of a 64-bit performance counter and returns it in the
16614   // registers EDX:EAX.
16615   if (Subtarget->is64Bit()) {
16616     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16617     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16618                             LO.getValue(2));
16619   } else {
16620     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16621     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16622                             LO.getValue(2));
16623   }
16624   Chain = HI.getValue(1);
16625
16626   if (Subtarget->is64Bit()) {
16627     // The EAX register is loaded with the low-order 32 bits. The EDX register
16628     // is loaded with the supported high-order bits of the counter.
16629     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16630                               DAG.getConstant(32, DL, MVT::i8));
16631     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16632     Results.push_back(Chain);
16633     return;
16634   }
16635
16636   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16637   SDValue Ops[] = { LO, HI };
16638   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16639   Results.push_back(Pair);
16640   Results.push_back(Chain);
16641 }
16642
16643 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16644 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16645 // also used to custom lower READCYCLECOUNTER nodes.
16646 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16647                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16648                               SmallVectorImpl<SDValue> &Results) {
16649   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16650   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16651   SDValue LO, HI;
16652
16653   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16654   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16655   // and the EAX register is loaded with the low-order 32 bits.
16656   if (Subtarget->is64Bit()) {
16657     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16658     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16659                             LO.getValue(2));
16660   } else {
16661     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16662     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16663                             LO.getValue(2));
16664   }
16665   SDValue Chain = HI.getValue(1);
16666
16667   if (Opcode == X86ISD::RDTSCP_DAG) {
16668     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16669
16670     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16671     // the ECX register. Add 'ecx' explicitly to the chain.
16672     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16673                                      HI.getValue(2));
16674     // Explicitly store the content of ECX at the location passed in input
16675     // to the 'rdtscp' intrinsic.
16676     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16677                          MachinePointerInfo(), false, false, 0);
16678   }
16679
16680   if (Subtarget->is64Bit()) {
16681     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16682     // the EAX register is loaded with the low-order 32 bits.
16683     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16684                               DAG.getConstant(32, DL, MVT::i8));
16685     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16686     Results.push_back(Chain);
16687     return;
16688   }
16689
16690   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16691   SDValue Ops[] = { LO, HI };
16692   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16693   Results.push_back(Pair);
16694   Results.push_back(Chain);
16695 }
16696
16697 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16698                                      SelectionDAG &DAG) {
16699   SmallVector<SDValue, 2> Results;
16700   SDLoc DL(Op);
16701   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16702                           Results);
16703   return DAG.getMergeValues(Results, DL);
16704 }
16705
16706 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16707                                     SelectionDAG &DAG) {
16708   MachineFunction &MF = DAG.getMachineFunction();
16709   const Function *Fn = MF.getFunction();
16710   SDLoc dl(Op);
16711   SDValue Chain = Op.getOperand(0);
16712
16713   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16714          "using llvm.x86.seh.restoreframe requires a frame pointer");
16715
16716   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16717   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16718
16719   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16720   unsigned FrameReg =
16721       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16722   unsigned SPReg = RegInfo->getStackRegister();
16723   unsigned SlotSize = RegInfo->getSlotSize();
16724
16725   // Get incoming EBP.
16726   SDValue IncomingEBP =
16727       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16728
16729   // SP is saved in the first field of every registration node, so load
16730   // [EBP-RegNodeSize] into SP.
16731   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16732   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16733                                DAG.getConstant(-RegNodeSize, dl, VT));
16734   SDValue NewSP =
16735       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16736                   false, VT.getScalarSizeInBits() / 8);
16737   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16738
16739   if (!RegInfo->needsStackRealignment(MF)) {
16740     // Adjust EBP to point back to the original frame position.
16741     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16742     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16743   } else {
16744     assert(RegInfo->hasBasePointer(MF) &&
16745            "functions with Win32 EH must use frame or base pointer register");
16746
16747     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16748     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16749     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16750
16751     // Reload the spilled EBP value, now that the stack and base pointers are
16752     // set up.
16753     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16754     X86FI->setHasSEHFramePtrSave(true);
16755     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16756     X86FI->setSEHFramePtrSaveIndex(FI);
16757     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16758                                 MachinePointerInfo(), false, false, false,
16759                                 VT.getScalarSizeInBits() / 8);
16760     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16761   }
16762
16763   return Chain;
16764 }
16765
16766 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16767 /// return truncate Store/MaskedStore Node
16768 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16769                                                SelectionDAG &DAG,
16770                                                MVT ElementType) {
16771   SDLoc dl(Op);
16772   SDValue Mask = Op.getOperand(4);
16773   SDValue DataToTruncate = Op.getOperand(3);
16774   SDValue Addr = Op.getOperand(2);
16775   SDValue Chain = Op.getOperand(0);
16776
16777   EVT VT  = DataToTruncate.getValueType();
16778   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16779                              ElementType, VT.getVectorNumElements());
16780
16781   if (isAllOnes(Mask)) // return just a truncate store
16782     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16783                              MachinePointerInfo(), SVT, false, false,
16784                              SVT.getScalarSizeInBits()/8);
16785
16786   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16787                                 MVT::i1, VT.getVectorNumElements());
16788   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16789                                    Mask.getValueType().getSizeInBits());
16790   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16791   // are extracted by EXTRACT_SUBVECTOR.
16792   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16793                               DAG.getBitcast(BitcastVT, Mask),
16794                               DAG.getIntPtrConstant(0, dl));
16795
16796   MachineMemOperand *MMO = DAG.getMachineFunction().
16797     getMachineMemOperand(MachinePointerInfo(),
16798                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16799                          SVT.getScalarSizeInBits()/8);
16800
16801   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16802                             VMask, SVT, MMO, true);
16803 }
16804
16805 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16806                                       SelectionDAG &DAG) {
16807   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16808
16809   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16810   if (!IntrData) {
16811     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16812       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16813     return SDValue();
16814   }
16815
16816   SDLoc dl(Op);
16817   switch(IntrData->Type) {
16818   default:
16819     llvm_unreachable("Unknown Intrinsic Type");
16820     break;
16821   case RDSEED:
16822   case RDRAND: {
16823     // Emit the node with the right value type.
16824     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16825     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16826
16827     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16828     // Otherwise return the value from Rand, which is always 0, casted to i32.
16829     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16830                       DAG.getConstant(1, dl, Op->getValueType(1)),
16831                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16832                       SDValue(Result.getNode(), 1) };
16833     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16834                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16835                                   Ops);
16836
16837     // Return { result, isValid, chain }.
16838     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16839                        SDValue(Result.getNode(), 2));
16840   }
16841   case GATHER: {
16842   //gather(v1, mask, index, base, scale);
16843     SDValue Chain = Op.getOperand(0);
16844     SDValue Src   = Op.getOperand(2);
16845     SDValue Base  = Op.getOperand(3);
16846     SDValue Index = Op.getOperand(4);
16847     SDValue Mask  = Op.getOperand(5);
16848     SDValue Scale = Op.getOperand(6);
16849     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16850                          Chain, Subtarget);
16851   }
16852   case SCATTER: {
16853   //scatter(base, mask, index, v1, scale);
16854     SDValue Chain = Op.getOperand(0);
16855     SDValue Base  = Op.getOperand(2);
16856     SDValue Mask  = Op.getOperand(3);
16857     SDValue Index = Op.getOperand(4);
16858     SDValue Src   = Op.getOperand(5);
16859     SDValue Scale = Op.getOperand(6);
16860     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16861                           Scale, Chain);
16862   }
16863   case PREFETCH: {
16864     SDValue Hint = Op.getOperand(6);
16865     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16866     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16867     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16868     SDValue Chain = Op.getOperand(0);
16869     SDValue Mask  = Op.getOperand(2);
16870     SDValue Index = Op.getOperand(3);
16871     SDValue Base  = Op.getOperand(4);
16872     SDValue Scale = Op.getOperand(5);
16873     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16874   }
16875   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16876   case RDTSC: {
16877     SmallVector<SDValue, 2> Results;
16878     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16879                             Results);
16880     return DAG.getMergeValues(Results, dl);
16881   }
16882   // Read Performance Monitoring Counters.
16883   case RDPMC: {
16884     SmallVector<SDValue, 2> Results;
16885     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16886     return DAG.getMergeValues(Results, dl);
16887   }
16888   // XTEST intrinsics.
16889   case XTEST: {
16890     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16891     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16892     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16893                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16894                                 InTrans);
16895     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16896     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16897                        Ret, SDValue(InTrans.getNode(), 1));
16898   }
16899   // ADC/ADCX/SBB
16900   case ADX: {
16901     SmallVector<SDValue, 2> Results;
16902     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16903     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16904     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16905                                 DAG.getConstant(-1, dl, MVT::i8));
16906     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16907                               Op.getOperand(4), GenCF.getValue(1));
16908     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16909                                  Op.getOperand(5), MachinePointerInfo(),
16910                                  false, false, 0);
16911     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16912                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16913                                 Res.getValue(1));
16914     Results.push_back(SetCC);
16915     Results.push_back(Store);
16916     return DAG.getMergeValues(Results, dl);
16917   }
16918   case COMPRESS_TO_MEM: {
16919     SDLoc dl(Op);
16920     SDValue Mask = Op.getOperand(4);
16921     SDValue DataToCompress = Op.getOperand(3);
16922     SDValue Addr = Op.getOperand(2);
16923     SDValue Chain = Op.getOperand(0);
16924
16925     EVT VT = DataToCompress.getValueType();
16926     if (isAllOnes(Mask)) // return just a store
16927       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16928                           MachinePointerInfo(), false, false,
16929                           VT.getScalarSizeInBits()/8);
16930
16931     SDValue Compressed =
16932       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16933                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16934     return DAG.getStore(Chain, dl, Compressed, Addr,
16935                         MachinePointerInfo(), false, false,
16936                         VT.getScalarSizeInBits()/8);
16937   }
16938   case TRUNCATE_TO_MEM_VI8:
16939     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16940   case TRUNCATE_TO_MEM_VI16:
16941     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16942   case TRUNCATE_TO_MEM_VI32:
16943     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16944   case EXPAND_FROM_MEM: {
16945     SDLoc dl(Op);
16946     SDValue Mask = Op.getOperand(4);
16947     SDValue PassThru = Op.getOperand(3);
16948     SDValue Addr = Op.getOperand(2);
16949     SDValue Chain = Op.getOperand(0);
16950     EVT VT = Op.getValueType();
16951
16952     if (isAllOnes(Mask)) // return just a load
16953       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16954                          false, VT.getScalarSizeInBits()/8);
16955
16956     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16957                                        false, false, false,
16958                                        VT.getScalarSizeInBits()/8);
16959
16960     SDValue Results[] = {
16961       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16962                            Mask, PassThru, Subtarget, DAG), Chain};
16963     return DAG.getMergeValues(Results, dl);
16964   }
16965   }
16966 }
16967
16968 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16969                                            SelectionDAG &DAG) const {
16970   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16971   MFI->setReturnAddressIsTaken(true);
16972
16973   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16974     return SDValue();
16975
16976   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16977   SDLoc dl(Op);
16978   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16979
16980   if (Depth > 0) {
16981     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16982     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16983     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16984     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16985                        DAG.getNode(ISD::ADD, dl, PtrVT,
16986                                    FrameAddr, Offset),
16987                        MachinePointerInfo(), false, false, false, 0);
16988   }
16989
16990   // Just load the return address.
16991   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16992   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16993                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16994 }
16995
16996 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16997   MachineFunction &MF = DAG.getMachineFunction();
16998   MachineFrameInfo *MFI = MF.getFrameInfo();
16999   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17000   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17001   EVT VT = Op.getValueType();
17002
17003   MFI->setFrameAddressIsTaken(true);
17004
17005   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17006     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
17007     // is not possible to crawl up the stack without looking at the unwind codes
17008     // simultaneously.
17009     int FrameAddrIndex = FuncInfo->getFAIndex();
17010     if (!FrameAddrIndex) {
17011       // Set up a frame object for the return address.
17012       unsigned SlotSize = RegInfo->getSlotSize();
17013       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17014           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17015       FuncInfo->setFAIndex(FrameAddrIndex);
17016     }
17017     return DAG.getFrameIndex(FrameAddrIndex, VT);
17018   }
17019
17020   unsigned FrameReg =
17021       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17022   SDLoc dl(Op);  // FIXME probably not meaningful
17023   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17024   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17025           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17026          "Invalid Frame Register!");
17027   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17028   while (Depth--)
17029     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17030                             MachinePointerInfo(),
17031                             false, false, false, 0);
17032   return FrameAddr;
17033 }
17034
17035 // FIXME? Maybe this could be a TableGen attribute on some registers and
17036 // this table could be generated automatically from RegInfo.
17037 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17038                                               SelectionDAG &DAG) const {
17039   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17040   const MachineFunction &MF = DAG.getMachineFunction();
17041
17042   unsigned Reg = StringSwitch<unsigned>(RegName)
17043                        .Case("esp", X86::ESP)
17044                        .Case("rsp", X86::RSP)
17045                        .Case("ebp", X86::EBP)
17046                        .Case("rbp", X86::RBP)
17047                        .Default(0);
17048
17049   if (Reg == X86::EBP || Reg == X86::RBP) {
17050     if (!TFI.hasFP(MF))
17051       report_fatal_error("register " + StringRef(RegName) +
17052                          " is allocatable: function has no frame pointer");
17053 #ifndef NDEBUG
17054     else {
17055       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17056       unsigned FrameReg =
17057           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17058       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17059              "Invalid Frame Register!");
17060     }
17061 #endif
17062   }
17063
17064   if (Reg)
17065     return Reg;
17066
17067   report_fatal_error("Invalid register name global variable");
17068 }
17069
17070 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17071                                                      SelectionDAG &DAG) const {
17072   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17073   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17074 }
17075
17076 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17077   SDValue Chain     = Op.getOperand(0);
17078   SDValue Offset    = Op.getOperand(1);
17079   SDValue Handler   = Op.getOperand(2);
17080   SDLoc dl      (Op);
17081
17082   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17083   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17084   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17085   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17086           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17087          "Invalid Frame Register!");
17088   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17089   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17090
17091   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17092                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17093                                                        dl));
17094   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17095   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17096                        false, false, 0);
17097   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17098
17099   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17100                      DAG.getRegister(StoreAddrReg, PtrVT));
17101 }
17102
17103 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17104                                                SelectionDAG &DAG) const {
17105   SDLoc DL(Op);
17106   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17107                      DAG.getVTList(MVT::i32, MVT::Other),
17108                      Op.getOperand(0), Op.getOperand(1));
17109 }
17110
17111 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17112                                                 SelectionDAG &DAG) const {
17113   SDLoc DL(Op);
17114   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17115                      Op.getOperand(0), Op.getOperand(1));
17116 }
17117
17118 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17119   return Op.getOperand(0);
17120 }
17121
17122 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17123                                                 SelectionDAG &DAG) const {
17124   SDValue Root = Op.getOperand(0);
17125   SDValue Trmp = Op.getOperand(1); // trampoline
17126   SDValue FPtr = Op.getOperand(2); // nested function
17127   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17128   SDLoc dl (Op);
17129
17130   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17131   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17132
17133   if (Subtarget->is64Bit()) {
17134     SDValue OutChains[6];
17135
17136     // Large code-model.
17137     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17138     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17139
17140     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17141     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17142
17143     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17144
17145     // Load the pointer to the nested function into R11.
17146     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17147     SDValue Addr = Trmp;
17148     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17149                                 Addr, MachinePointerInfo(TrmpAddr),
17150                                 false, false, 0);
17151
17152     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17153                        DAG.getConstant(2, dl, MVT::i64));
17154     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17155                                 MachinePointerInfo(TrmpAddr, 2),
17156                                 false, false, 2);
17157
17158     // Load the 'nest' parameter value into R10.
17159     // R10 is specified in X86CallingConv.td
17160     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17161     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17162                        DAG.getConstant(10, dl, MVT::i64));
17163     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17164                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17165                                 false, false, 0);
17166
17167     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17168                        DAG.getConstant(12, dl, MVT::i64));
17169     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17170                                 MachinePointerInfo(TrmpAddr, 12),
17171                                 false, false, 2);
17172
17173     // Jump to the nested function.
17174     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17175     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17176                        DAG.getConstant(20, dl, MVT::i64));
17177     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17178                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17179                                 false, false, 0);
17180
17181     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17182     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17183                        DAG.getConstant(22, dl, MVT::i64));
17184     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17185                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17186                                 false, false, 0);
17187
17188     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17189   } else {
17190     const Function *Func =
17191       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17192     CallingConv::ID CC = Func->getCallingConv();
17193     unsigned NestReg;
17194
17195     switch (CC) {
17196     default:
17197       llvm_unreachable("Unsupported calling convention");
17198     case CallingConv::C:
17199     case CallingConv::X86_StdCall: {
17200       // Pass 'nest' parameter in ECX.
17201       // Must be kept in sync with X86CallingConv.td
17202       NestReg = X86::ECX;
17203
17204       // Check that ECX wasn't needed by an 'inreg' parameter.
17205       FunctionType *FTy = Func->getFunctionType();
17206       const AttributeSet &Attrs = Func->getAttributes();
17207
17208       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17209         unsigned InRegCount = 0;
17210         unsigned Idx = 1;
17211
17212         for (FunctionType::param_iterator I = FTy->param_begin(),
17213              E = FTy->param_end(); I != E; ++I, ++Idx)
17214           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17215             auto &DL = DAG.getDataLayout();
17216             // FIXME: should only count parameters that are lowered to integers.
17217             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17218           }
17219
17220         if (InRegCount > 2) {
17221           report_fatal_error("Nest register in use - reduce number of inreg"
17222                              " parameters!");
17223         }
17224       }
17225       break;
17226     }
17227     case CallingConv::X86_FastCall:
17228     case CallingConv::X86_ThisCall:
17229     case CallingConv::Fast:
17230       // Pass 'nest' parameter in EAX.
17231       // Must be kept in sync with X86CallingConv.td
17232       NestReg = X86::EAX;
17233       break;
17234     }
17235
17236     SDValue OutChains[4];
17237     SDValue Addr, Disp;
17238
17239     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17240                        DAG.getConstant(10, dl, MVT::i32));
17241     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17242
17243     // This is storing the opcode for MOV32ri.
17244     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17245     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17246     OutChains[0] = DAG.getStore(Root, dl,
17247                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17248                                 Trmp, MachinePointerInfo(TrmpAddr),
17249                                 false, false, 0);
17250
17251     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17252                        DAG.getConstant(1, dl, MVT::i32));
17253     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17254                                 MachinePointerInfo(TrmpAddr, 1),
17255                                 false, false, 1);
17256
17257     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17258     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17259                        DAG.getConstant(5, dl, MVT::i32));
17260     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17261                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17262                                 false, false, 1);
17263
17264     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17265                        DAG.getConstant(6, dl, MVT::i32));
17266     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17267                                 MachinePointerInfo(TrmpAddr, 6),
17268                                 false, false, 1);
17269
17270     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17271   }
17272 }
17273
17274 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17275                                             SelectionDAG &DAG) const {
17276   /*
17277    The rounding mode is in bits 11:10 of FPSR, and has the following
17278    settings:
17279      00 Round to nearest
17280      01 Round to -inf
17281      10 Round to +inf
17282      11 Round to 0
17283
17284   FLT_ROUNDS, on the other hand, expects the following:
17285     -1 Undefined
17286      0 Round to 0
17287      1 Round to nearest
17288      2 Round to +inf
17289      3 Round to -inf
17290
17291   To perform the conversion, we do:
17292     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17293   */
17294
17295   MachineFunction &MF = DAG.getMachineFunction();
17296   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17297   unsigned StackAlignment = TFI.getStackAlignment();
17298   MVT VT = Op.getSimpleValueType();
17299   SDLoc DL(Op);
17300
17301   // Save FP Control Word to stack slot
17302   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17303   SDValue StackSlot =
17304       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17305
17306   MachineMemOperand *MMO =
17307       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17308                               MachineMemOperand::MOStore, 2, 2);
17309
17310   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17311   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17312                                           DAG.getVTList(MVT::Other),
17313                                           Ops, MVT::i16, MMO);
17314
17315   // Load FP Control Word from stack slot
17316   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17317                             MachinePointerInfo(), false, false, false, 0);
17318
17319   // Transform as necessary
17320   SDValue CWD1 =
17321     DAG.getNode(ISD::SRL, DL, MVT::i16,
17322                 DAG.getNode(ISD::AND, DL, MVT::i16,
17323                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17324                 DAG.getConstant(11, DL, MVT::i8));
17325   SDValue CWD2 =
17326     DAG.getNode(ISD::SRL, DL, MVT::i16,
17327                 DAG.getNode(ISD::AND, DL, MVT::i16,
17328                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17329                 DAG.getConstant(9, DL, MVT::i8));
17330
17331   SDValue RetVal =
17332     DAG.getNode(ISD::AND, DL, MVT::i16,
17333                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17334                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17335                             DAG.getConstant(1, DL, MVT::i16)),
17336                 DAG.getConstant(3, DL, MVT::i16));
17337
17338   return DAG.getNode((VT.getSizeInBits() < 16 ?
17339                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17340 }
17341
17342 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
17343   MVT VT = Op.getSimpleValueType();
17344   EVT OpVT = VT;
17345   unsigned NumBits = VT.getSizeInBits();
17346   SDLoc dl(Op);
17347
17348   Op = Op.getOperand(0);
17349   if (VT == MVT::i8) {
17350     // Zero extend to i32 since there is not an i8 bsr.
17351     OpVT = MVT::i32;
17352     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17353   }
17354
17355   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17356   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17357   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17358
17359   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17360   SDValue Ops[] = {
17361     Op,
17362     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17363     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17364     Op.getValue(1)
17365   };
17366   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17367
17368   // Finally xor with NumBits-1.
17369   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17370                    DAG.getConstant(NumBits - 1, dl, OpVT));
17371
17372   if (VT == MVT::i8)
17373     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17374   return Op;
17375 }
17376
17377 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17378   MVT VT = Op.getSimpleValueType();
17379   EVT OpVT = VT;
17380   unsigned NumBits = VT.getSizeInBits();
17381   SDLoc dl(Op);
17382
17383   Op = Op.getOperand(0);
17384   if (VT == MVT::i8) {
17385     // Zero extend to i32 since there is not an i8 bsr.
17386     OpVT = MVT::i32;
17387     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17388   }
17389
17390   // Issue a bsr (scan bits in reverse).
17391   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17392   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17393
17394   // And xor with NumBits-1.
17395   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17396                    DAG.getConstant(NumBits - 1, dl, OpVT));
17397
17398   if (VT == MVT::i8)
17399     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17400   return Op;
17401 }
17402
17403 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17404   MVT VT = Op.getSimpleValueType();
17405   unsigned NumBits = VT.getScalarSizeInBits();
17406   SDLoc dl(Op);
17407
17408   if (VT.isVector()) {
17409     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17410
17411     SDValue N0 = Op.getOperand(0);
17412     SDValue Zero = DAG.getConstant(0, dl, VT);
17413
17414     // lsb(x) = (x & -x)
17415     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
17416                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
17417
17418     // cttz_undef(x) = (width - 1) - ctlz(lsb)
17419     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
17420         TLI.isOperationLegal(ISD::CTLZ, VT)) {
17421       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
17422       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
17423                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
17424     }
17425
17426     // cttz(x) = ctpop(lsb - 1)
17427     SDValue One = DAG.getConstant(1, dl, VT);
17428     return DAG.getNode(ISD::CTPOP, dl, VT,
17429                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
17430   }
17431
17432   assert(Op.getOpcode() == ISD::CTTZ &&
17433          "Only scalar CTTZ requires custom lowering");
17434
17435   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17436   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17437   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
17438
17439   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17440   SDValue Ops[] = {
17441     Op,
17442     DAG.getConstant(NumBits, dl, VT),
17443     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17444     Op.getValue(1)
17445   };
17446   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17447 }
17448
17449 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17450 // ones, and then concatenate the result back.
17451 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17452   MVT VT = Op.getSimpleValueType();
17453
17454   assert(VT.is256BitVector() && VT.isInteger() &&
17455          "Unsupported value type for operation");
17456
17457   unsigned NumElems = VT.getVectorNumElements();
17458   SDLoc dl(Op);
17459
17460   // Extract the LHS vectors
17461   SDValue LHS = Op.getOperand(0);
17462   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17463   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17464
17465   // Extract the RHS vectors
17466   SDValue RHS = Op.getOperand(1);
17467   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17468   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17469
17470   MVT EltVT = VT.getVectorElementType();
17471   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17472
17473   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17474                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17475                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17476 }
17477
17478 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17479   if (Op.getValueType() == MVT::i1)
17480     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17481                        Op.getOperand(0), Op.getOperand(1));
17482   assert(Op.getSimpleValueType().is256BitVector() &&
17483          Op.getSimpleValueType().isInteger() &&
17484          "Only handle AVX 256-bit vector integer operation");
17485   return Lower256IntArith(Op, DAG);
17486 }
17487
17488 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17489   if (Op.getValueType() == MVT::i1)
17490     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17491                        Op.getOperand(0), Op.getOperand(1));
17492   assert(Op.getSimpleValueType().is256BitVector() &&
17493          Op.getSimpleValueType().isInteger() &&
17494          "Only handle AVX 256-bit vector integer operation");
17495   return Lower256IntArith(Op, DAG);
17496 }
17497
17498 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17499   assert(Op.getSimpleValueType().is256BitVector() &&
17500          Op.getSimpleValueType().isInteger() &&
17501          "Only handle AVX 256-bit vector integer operation");
17502   return Lower256IntArith(Op, DAG);
17503 }
17504
17505 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17506                         SelectionDAG &DAG) {
17507   SDLoc dl(Op);
17508   MVT VT = Op.getSimpleValueType();
17509
17510   if (VT == MVT::i1)
17511     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17512
17513   // Decompose 256-bit ops into smaller 128-bit ops.
17514   if (VT.is256BitVector() && !Subtarget->hasInt256())
17515     return Lower256IntArith(Op, DAG);
17516
17517   SDValue A = Op.getOperand(0);
17518   SDValue B = Op.getOperand(1);
17519
17520   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17521   // pairs, multiply and truncate.
17522   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17523     if (Subtarget->hasInt256()) {
17524       if (VT == MVT::v32i8) {
17525         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17526         SDValue Lo = DAG.getIntPtrConstant(0, dl);
17527         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17528         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17529         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17530         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17531         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17532         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17533                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17534                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17535       }
17536
17537       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17538       return DAG.getNode(
17539           ISD::TRUNCATE, dl, VT,
17540           DAG.getNode(ISD::MUL, dl, ExVT,
17541                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17542                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17543     }
17544
17545     assert(VT == MVT::v16i8 &&
17546            "Pre-AVX2 support only supports v16i8 multiplication");
17547     MVT ExVT = MVT::v8i16;
17548
17549     // Extract the lo parts and sign extend to i16
17550     SDValue ALo, BLo;
17551     if (Subtarget->hasSSE41()) {
17552       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17553       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17554     } else {
17555       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17556                               -1, 4, -1, 5, -1, 6, -1, 7};
17557       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17558       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17559       ALo = DAG.getBitcast(ExVT, ALo);
17560       BLo = DAG.getBitcast(ExVT, BLo);
17561       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17562       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17563     }
17564
17565     // Extract the hi parts and sign extend to i16
17566     SDValue AHi, BHi;
17567     if (Subtarget->hasSSE41()) {
17568       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17569                               -1, -1, -1, -1, -1, -1, -1, -1};
17570       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17571       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17572       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17573       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17574     } else {
17575       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17576                               -1, 12, -1, 13, -1, 14, -1, 15};
17577       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17578       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17579       AHi = DAG.getBitcast(ExVT, AHi);
17580       BHi = DAG.getBitcast(ExVT, BHi);
17581       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17582       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17583     }
17584
17585     // Multiply, mask the lower 8bits of the lo/hi results and pack
17586     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17587     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17588     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17589     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17590     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17591   }
17592
17593   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17594   if (VT == MVT::v4i32) {
17595     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17596            "Should not custom lower when pmuldq is available!");
17597
17598     // Extract the odd parts.
17599     static const int UnpackMask[] = { 1, -1, 3, -1 };
17600     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17601     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17602
17603     // Multiply the even parts.
17604     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17605     // Now multiply odd parts.
17606     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17607
17608     Evens = DAG.getBitcast(VT, Evens);
17609     Odds = DAG.getBitcast(VT, Odds);
17610
17611     // Merge the two vectors back together with a shuffle. This expands into 2
17612     // shuffles.
17613     static const int ShufMask[] = { 0, 4, 2, 6 };
17614     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17615   }
17616
17617   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17618          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17619
17620   //  Ahi = psrlqi(a, 32);
17621   //  Bhi = psrlqi(b, 32);
17622   //
17623   //  AloBlo = pmuludq(a, b);
17624   //  AloBhi = pmuludq(a, Bhi);
17625   //  AhiBlo = pmuludq(Ahi, b);
17626
17627   //  AloBhi = psllqi(AloBhi, 32);
17628   //  AhiBlo = psllqi(AhiBlo, 32);
17629   //  return AloBlo + AloBhi + AhiBlo;
17630
17631   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17632   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17633
17634   SDValue AhiBlo = Ahi;
17635   SDValue AloBhi = Bhi;
17636   // Bit cast to 32-bit vectors for MULUDQ
17637   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17638                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17639   A = DAG.getBitcast(MulVT, A);
17640   B = DAG.getBitcast(MulVT, B);
17641   Ahi = DAG.getBitcast(MulVT, Ahi);
17642   Bhi = DAG.getBitcast(MulVT, Bhi);
17643
17644   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17645   // After shifting right const values the result may be all-zero.
17646   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17647     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17648     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17649   }
17650   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17651     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17652     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17653   }
17654
17655   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17656   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17657 }
17658
17659 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17660   assert(Subtarget->isTargetWin64() && "Unexpected target");
17661   EVT VT = Op.getValueType();
17662   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17663          "Unexpected return type for lowering");
17664
17665   RTLIB::Libcall LC;
17666   bool isSigned;
17667   switch (Op->getOpcode()) {
17668   default: llvm_unreachable("Unexpected request for libcall!");
17669   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17670   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17671   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17672   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17673   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17674   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17675   }
17676
17677   SDLoc dl(Op);
17678   SDValue InChain = DAG.getEntryNode();
17679
17680   TargetLowering::ArgListTy Args;
17681   TargetLowering::ArgListEntry Entry;
17682   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17683     EVT ArgVT = Op->getOperand(i).getValueType();
17684     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17685            "Unexpected argument type for lowering");
17686     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17687     Entry.Node = StackPtr;
17688     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17689                            false, false, 16);
17690     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17691     Entry.Ty = PointerType::get(ArgTy,0);
17692     Entry.isSExt = false;
17693     Entry.isZExt = false;
17694     Args.push_back(Entry);
17695   }
17696
17697   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17698                                          getPointerTy(DAG.getDataLayout()));
17699
17700   TargetLowering::CallLoweringInfo CLI(DAG);
17701   CLI.setDebugLoc(dl).setChain(InChain)
17702     .setCallee(getLibcallCallingConv(LC),
17703                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17704                Callee, std::move(Args), 0)
17705     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17706
17707   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17708   return DAG.getBitcast(VT, CallInfo.first);
17709 }
17710
17711 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17712                              SelectionDAG &DAG) {
17713   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17714   EVT VT = Op0.getValueType();
17715   SDLoc dl(Op);
17716
17717   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17718          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17719
17720   // PMULxD operations multiply each even value (starting at 0) of LHS with
17721   // the related value of RHS and produce a widen result.
17722   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17723   // => <2 x i64> <ae|cg>
17724   //
17725   // In other word, to have all the results, we need to perform two PMULxD:
17726   // 1. one with the even values.
17727   // 2. one with the odd values.
17728   // To achieve #2, with need to place the odd values at an even position.
17729   //
17730   // Place the odd value at an even position (basically, shift all values 1
17731   // step to the left):
17732   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17733   // <a|b|c|d> => <b|undef|d|undef>
17734   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17735   // <e|f|g|h> => <f|undef|h|undef>
17736   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17737
17738   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17739   // ints.
17740   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17741   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17742   unsigned Opcode =
17743       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17744   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17745   // => <2 x i64> <ae|cg>
17746   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17747   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17748   // => <2 x i64> <bf|dh>
17749   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17750
17751   // Shuffle it back into the right order.
17752   SDValue Highs, Lows;
17753   if (VT == MVT::v8i32) {
17754     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17755     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17756     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17757     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17758   } else {
17759     const int HighMask[] = {1, 5, 3, 7};
17760     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17761     const int LowMask[] = {0, 4, 2, 6};
17762     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17763   }
17764
17765   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17766   // unsigned multiply.
17767   if (IsSigned && !Subtarget->hasSSE41()) {
17768     SDValue ShAmt = DAG.getConstant(
17769         31, dl,
17770         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17771     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17772                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17773     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17774                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17775
17776     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17777     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17778   }
17779
17780   // The first result of MUL_LOHI is actually the low value, followed by the
17781   // high value.
17782   SDValue Ops[] = {Lows, Highs};
17783   return DAG.getMergeValues(Ops, dl);
17784 }
17785
17786 // Return true if the required (according to Opcode) shift-imm form is natively
17787 // supported by the Subtarget
17788 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17789                                         unsigned Opcode) {
17790   if (VT.getScalarSizeInBits() < 16)
17791     return false;
17792
17793   if (VT.is512BitVector() &&
17794       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17795     return true;
17796
17797   bool LShift = VT.is128BitVector() ||
17798     (VT.is256BitVector() && Subtarget->hasInt256());
17799
17800   bool AShift = LShift && (Subtarget->hasVLX() ||
17801     (VT != MVT::v2i64 && VT != MVT::v4i64));
17802   return (Opcode == ISD::SRA) ? AShift : LShift;
17803 }
17804
17805 // The shift amount is a variable, but it is the same for all vector lanes.
17806 // These instructions are defined together with shift-immediate.
17807 static
17808 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17809                                       unsigned Opcode) {
17810   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17811 }
17812
17813 // Return true if the required (according to Opcode) variable-shift form is
17814 // natively supported by the Subtarget
17815 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17816                                     unsigned Opcode) {
17817
17818   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17819     return false;
17820
17821   // vXi16 supported only on AVX-512, BWI
17822   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17823     return false;
17824
17825   if (VT.is512BitVector() || Subtarget->hasVLX())
17826     return true;
17827
17828   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17829   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17830   return (Opcode == ISD::SRA) ? AShift : LShift;
17831 }
17832
17833 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17834                                          const X86Subtarget *Subtarget) {
17835   MVT VT = Op.getSimpleValueType();
17836   SDLoc dl(Op);
17837   SDValue R = Op.getOperand(0);
17838   SDValue Amt = Op.getOperand(1);
17839
17840   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17841     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17842
17843   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17844     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17845     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17846     SDValue Ex = DAG.getBitcast(ExVT, R);
17847
17848     if (ShiftAmt >= 32) {
17849       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17850       SDValue Upper =
17851           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17852       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17853                                                  ShiftAmt - 32, DAG);
17854       if (VT == MVT::v2i64)
17855         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17856       if (VT == MVT::v4i64)
17857         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17858                                   {9, 1, 11, 3, 13, 5, 15, 7});
17859     } else {
17860       // SRA upper i32, SHL whole i64 and select lower i32.
17861       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17862                                                  ShiftAmt, DAG);
17863       SDValue Lower =
17864           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17865       Lower = DAG.getBitcast(ExVT, Lower);
17866       if (VT == MVT::v2i64)
17867         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17868       if (VT == MVT::v4i64)
17869         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17870                                   {8, 1, 10, 3, 12, 5, 14, 7});
17871     }
17872     return DAG.getBitcast(VT, Ex);
17873   };
17874
17875   // Optimize shl/srl/sra with constant shift amount.
17876   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17877     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17878       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17879
17880       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17881         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17882
17883       // i64 SRA needs to be performed as partial shifts.
17884       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17885           Op.getOpcode() == ISD::SRA)
17886         return ArithmeticShiftRight64(ShiftAmt);
17887
17888       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17889         unsigned NumElts = VT.getVectorNumElements();
17890         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17891
17892         if (Op.getOpcode() == ISD::SHL) {
17893           // Simple i8 add case
17894           if (ShiftAmt == 1)
17895             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17896
17897           // Make a large shift.
17898           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17899                                                    R, ShiftAmt, DAG);
17900           SHL = DAG.getBitcast(VT, SHL);
17901           // Zero out the rightmost bits.
17902           SmallVector<SDValue, 32> V(
17903               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17904           return DAG.getNode(ISD::AND, dl, VT, SHL,
17905                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17906         }
17907         if (Op.getOpcode() == ISD::SRL) {
17908           // Make a large shift.
17909           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17910                                                    R, ShiftAmt, DAG);
17911           SRL = DAG.getBitcast(VT, SRL);
17912           // Zero out the leftmost bits.
17913           SmallVector<SDValue, 32> V(
17914               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17915           return DAG.getNode(ISD::AND, dl, VT, SRL,
17916                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17917         }
17918         if (Op.getOpcode() == ISD::SRA) {
17919           if (ShiftAmt == 7) {
17920             // ashr(R, 7)  === cmp_slt(R, 0)
17921             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17922             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17923           }
17924
17925           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17926           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17927           SmallVector<SDValue, 32> V(NumElts,
17928                                      DAG.getConstant(128 >> ShiftAmt, dl,
17929                                                      MVT::i8));
17930           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17931           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17932           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17933           return Res;
17934         }
17935         llvm_unreachable("Unknown shift opcode.");
17936       }
17937     }
17938   }
17939
17940   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17941   if (!Subtarget->is64Bit() &&
17942       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17943
17944     // Peek through any splat that was introduced for i64 shift vectorization.
17945     int SplatIndex = -1;
17946     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17947       if (SVN->isSplat()) {
17948         SplatIndex = SVN->getSplatIndex();
17949         Amt = Amt.getOperand(0);
17950         assert(SplatIndex < (int)VT.getVectorNumElements() &&
17951                "Splat shuffle referencing second operand");
17952       }
17953
17954     if (Amt.getOpcode() != ISD::BITCAST ||
17955         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17956       return SDValue();
17957
17958     Amt = Amt.getOperand(0);
17959     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17960                      VT.getVectorNumElements();
17961     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17962     uint64_t ShiftAmt = 0;
17963     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17964     for (unsigned i = 0; i != Ratio; ++i) {
17965       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17966       if (!C)
17967         return SDValue();
17968       // 6 == Log2(64)
17969       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17970     }
17971
17972     // Check remaining shift amounts (if not a splat).
17973     if (SplatIndex < 0) {
17974       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17975         uint64_t ShAmt = 0;
17976         for (unsigned j = 0; j != Ratio; ++j) {
17977           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17978           if (!C)
17979             return SDValue();
17980           // 6 == Log2(64)
17981           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17982         }
17983         if (ShAmt != ShiftAmt)
17984           return SDValue();
17985       }
17986     }
17987
17988     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17989       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17990
17991     if (Op.getOpcode() == ISD::SRA)
17992       return ArithmeticShiftRight64(ShiftAmt);
17993   }
17994
17995   return SDValue();
17996 }
17997
17998 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17999                                         const X86Subtarget* Subtarget) {
18000   MVT VT = Op.getSimpleValueType();
18001   SDLoc dl(Op);
18002   SDValue R = Op.getOperand(0);
18003   SDValue Amt = Op.getOperand(1);
18004
18005   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18006     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18007
18008   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18009     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18010
18011   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18012     SDValue BaseShAmt;
18013     EVT EltVT = VT.getVectorElementType();
18014
18015     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18016       // Check if this build_vector node is doing a splat.
18017       // If so, then set BaseShAmt equal to the splat value.
18018       BaseShAmt = BV->getSplatValue();
18019       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18020         BaseShAmt = SDValue();
18021     } else {
18022       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18023         Amt = Amt.getOperand(0);
18024
18025       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18026       if (SVN && SVN->isSplat()) {
18027         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18028         SDValue InVec = Amt.getOperand(0);
18029         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18030           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
18031                  "Unexpected shuffle index found!");
18032           BaseShAmt = InVec.getOperand(SplatIdx);
18033         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18034            if (ConstantSDNode *C =
18035                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18036              if (C->getZExtValue() == SplatIdx)
18037                BaseShAmt = InVec.getOperand(1);
18038            }
18039         }
18040
18041         if (!BaseShAmt)
18042           // Avoid introducing an extract element from a shuffle.
18043           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18044                                   DAG.getIntPtrConstant(SplatIdx, dl));
18045       }
18046     }
18047
18048     if (BaseShAmt.getNode()) {
18049       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18050       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18051         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18052       else if (EltVT.bitsLT(MVT::i32))
18053         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18054
18055       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18056     }
18057   }
18058
18059   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18060   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
18061       Amt.getOpcode() == ISD::BITCAST &&
18062       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18063     Amt = Amt.getOperand(0);
18064     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18065                      VT.getVectorNumElements();
18066     std::vector<SDValue> Vals(Ratio);
18067     for (unsigned i = 0; i != Ratio; ++i)
18068       Vals[i] = Amt.getOperand(i);
18069     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18070       for (unsigned j = 0; j != Ratio; ++j)
18071         if (Vals[j] != Amt.getOperand(i + j))
18072           return SDValue();
18073     }
18074
18075     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18076       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18077   }
18078   return SDValue();
18079 }
18080
18081 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18082                           SelectionDAG &DAG) {
18083   MVT VT = Op.getSimpleValueType();
18084   SDLoc dl(Op);
18085   SDValue R = Op.getOperand(0);
18086   SDValue Amt = Op.getOperand(1);
18087
18088   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18089   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18090
18091   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18092     return V;
18093
18094   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18095       return V;
18096
18097   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18098     return Op;
18099
18100   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18101   // shifts per-lane and then shuffle the partial results back together.
18102   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18103     // Splat the shift amounts so the scalar shifts above will catch it.
18104     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18105     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18106     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18107     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18108     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18109   }
18110
18111   // i64 vector arithmetic shift can be emulated with the transform:
18112   // M = lshr(SIGN_BIT, Amt)
18113   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18114   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18115       Op.getOpcode() == ISD::SRA) {
18116     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18117     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18118     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18119     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18120     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18121     return R;
18122   }
18123
18124   // If possible, lower this packed shift into a vector multiply instead of
18125   // expanding it into a sequence of scalar shifts.
18126   // Do this only if the vector shift count is a constant build_vector.
18127   if (Op.getOpcode() == ISD::SHL &&
18128       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18129        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18130       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18131     SmallVector<SDValue, 8> Elts;
18132     EVT SVT = VT.getScalarType();
18133     unsigned SVTBits = SVT.getSizeInBits();
18134     const APInt &One = APInt(SVTBits, 1);
18135     unsigned NumElems = VT.getVectorNumElements();
18136
18137     for (unsigned i=0; i !=NumElems; ++i) {
18138       SDValue Op = Amt->getOperand(i);
18139       if (Op->getOpcode() == ISD::UNDEF) {
18140         Elts.push_back(Op);
18141         continue;
18142       }
18143
18144       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18145       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
18146       uint64_t ShAmt = C.getZExtValue();
18147       if (ShAmt >= SVTBits) {
18148         Elts.push_back(DAG.getUNDEF(SVT));
18149         continue;
18150       }
18151       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18152     }
18153     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18154     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18155   }
18156
18157   // Lower SHL with variable shift amount.
18158   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18159     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18160
18161     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18162                      DAG.getConstant(0x3f800000U, dl, VT));
18163     Op = DAG.getBitcast(MVT::v4f32, Op);
18164     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18165     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18166   }
18167
18168   // If possible, lower this shift as a sequence of two shifts by
18169   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18170   // Example:
18171   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18172   //
18173   // Could be rewritten as:
18174   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18175   //
18176   // The advantage is that the two shifts from the example would be
18177   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18178   // the vector shift into four scalar shifts plus four pairs of vector
18179   // insert/extract.
18180   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18181       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18182     unsigned TargetOpcode = X86ISD::MOVSS;
18183     bool CanBeSimplified;
18184     // The splat value for the first packed shift (the 'X' from the example).
18185     SDValue Amt1 = Amt->getOperand(0);
18186     // The splat value for the second packed shift (the 'Y' from the example).
18187     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18188                                         Amt->getOperand(2);
18189
18190     // See if it is possible to replace this node with a sequence of
18191     // two shifts followed by a MOVSS/MOVSD
18192     if (VT == MVT::v4i32) {
18193       // Check if it is legal to use a MOVSS.
18194       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18195                         Amt2 == Amt->getOperand(3);
18196       if (!CanBeSimplified) {
18197         // Otherwise, check if we can still simplify this node using a MOVSD.
18198         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18199                           Amt->getOperand(2) == Amt->getOperand(3);
18200         TargetOpcode = X86ISD::MOVSD;
18201         Amt2 = Amt->getOperand(2);
18202       }
18203     } else {
18204       // Do similar checks for the case where the machine value type
18205       // is MVT::v8i16.
18206       CanBeSimplified = Amt1 == Amt->getOperand(1);
18207       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18208         CanBeSimplified = Amt2 == Amt->getOperand(i);
18209
18210       if (!CanBeSimplified) {
18211         TargetOpcode = X86ISD::MOVSD;
18212         CanBeSimplified = true;
18213         Amt2 = Amt->getOperand(4);
18214         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18215           CanBeSimplified = Amt1 == Amt->getOperand(i);
18216         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18217           CanBeSimplified = Amt2 == Amt->getOperand(j);
18218       }
18219     }
18220
18221     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18222         isa<ConstantSDNode>(Amt2)) {
18223       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18224       EVT CastVT = MVT::v4i32;
18225       SDValue Splat1 =
18226         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18227       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18228       SDValue Splat2 =
18229         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18230       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18231       if (TargetOpcode == X86ISD::MOVSD)
18232         CastVT = MVT::v2i64;
18233       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18234       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18235       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18236                                             BitCast1, DAG);
18237       return DAG.getBitcast(VT, Result);
18238     }
18239   }
18240
18241   // v4i32 Non Uniform Shifts.
18242   // If the shift amount is constant we can shift each lane using the SSE2
18243   // immediate shifts, else we need to zero-extend each lane to the lower i64
18244   // and shift using the SSE2 variable shifts.
18245   // The separate results can then be blended together.
18246   if (VT == MVT::v4i32) {
18247     unsigned Opc = Op.getOpcode();
18248     SDValue Amt0, Amt1, Amt2, Amt3;
18249     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18250       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18251       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18252       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18253       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18254     } else {
18255       // ISD::SHL is handled above but we include it here for completeness.
18256       switch (Opc) {
18257       default:
18258         llvm_unreachable("Unknown target vector shift node");
18259       case ISD::SHL:
18260         Opc = X86ISD::VSHL;
18261         break;
18262       case ISD::SRL:
18263         Opc = X86ISD::VSRL;
18264         break;
18265       case ISD::SRA:
18266         Opc = X86ISD::VSRA;
18267         break;
18268       }
18269       // The SSE2 shifts use the lower i64 as the same shift amount for
18270       // all lanes and the upper i64 is ignored. These shuffle masks
18271       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18272       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18273       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18274       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18275       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18276       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18277     }
18278
18279     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18280     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18281     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18282     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18283     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18284     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18285     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18286   }
18287
18288   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
18289     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18290     unsigned ShiftOpcode = Op->getOpcode();
18291
18292     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18293       // On SSE41 targets we make use of the fact that VSELECT lowers
18294       // to PBLENDVB which selects bytes based just on the sign bit.
18295       if (Subtarget->hasSSE41()) {
18296         V0 = DAG.getBitcast(VT, V0);
18297         V1 = DAG.getBitcast(VT, V1);
18298         Sel = DAG.getBitcast(VT, Sel);
18299         return DAG.getBitcast(SelVT,
18300                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18301       }
18302       // On pre-SSE41 targets we test for the sign bit by comparing to
18303       // zero - a negative value will set all bits of the lanes to true
18304       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18305       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18306       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18307       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18308     };
18309
18310     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18311     // We can safely do this using i16 shifts as we're only interested in
18312     // the 3 lower bits of each byte.
18313     Amt = DAG.getBitcast(ExtVT, Amt);
18314     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18315     Amt = DAG.getBitcast(VT, Amt);
18316
18317     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18318       // r = VSELECT(r, shift(r, 4), a);
18319       SDValue M =
18320           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18321       R = SignBitSelect(VT, Amt, M, R);
18322
18323       // a += a
18324       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18325
18326       // r = VSELECT(r, shift(r, 2), a);
18327       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18328       R = SignBitSelect(VT, Amt, M, R);
18329
18330       // a += a
18331       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18332
18333       // return VSELECT(r, shift(r, 1), a);
18334       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18335       R = SignBitSelect(VT, Amt, M, R);
18336       return R;
18337     }
18338
18339     if (Op->getOpcode() == ISD::SRA) {
18340       // For SRA we need to unpack each byte to the higher byte of a i16 vector
18341       // so we can correctly sign extend. We don't care what happens to the
18342       // lower byte.
18343       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18344       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18345       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18346       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18347       ALo = DAG.getBitcast(ExtVT, ALo);
18348       AHi = DAG.getBitcast(ExtVT, AHi);
18349       RLo = DAG.getBitcast(ExtVT, RLo);
18350       RHi = DAG.getBitcast(ExtVT, RHi);
18351
18352       // r = VSELECT(r, shift(r, 4), a);
18353       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18354                                 DAG.getConstant(4, dl, ExtVT));
18355       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18356                                 DAG.getConstant(4, dl, ExtVT));
18357       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18358       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18359
18360       // a += a
18361       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18362       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18363
18364       // r = VSELECT(r, shift(r, 2), a);
18365       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18366                         DAG.getConstant(2, dl, ExtVT));
18367       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18368                         DAG.getConstant(2, dl, ExtVT));
18369       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18370       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18371
18372       // a += a
18373       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18374       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18375
18376       // r = VSELECT(r, shift(r, 1), a);
18377       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18378                         DAG.getConstant(1, dl, ExtVT));
18379       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18380                         DAG.getConstant(1, dl, ExtVT));
18381       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18382       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18383
18384       // Logical shift the result back to the lower byte, leaving a zero upper
18385       // byte
18386       // meaning that we can safely pack with PACKUSWB.
18387       RLo =
18388           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18389       RHi =
18390           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18391       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18392     }
18393   }
18394
18395   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18396   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18397   // solution better.
18398   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18399     MVT ExtVT = MVT::v8i32;
18400     unsigned ExtOpc =
18401         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18402     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18403     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18404     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18405                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18406   }
18407
18408   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
18409     MVT ExtVT = MVT::v8i32;
18410     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18411     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18412     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18413     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18414     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18415     ALo = DAG.getBitcast(ExtVT, ALo);
18416     AHi = DAG.getBitcast(ExtVT, AHi);
18417     RLo = DAG.getBitcast(ExtVT, RLo);
18418     RHi = DAG.getBitcast(ExtVT, RHi);
18419     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18420     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18421     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18422     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18423     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18424   }
18425
18426   if (VT == MVT::v8i16) {
18427     unsigned ShiftOpcode = Op->getOpcode();
18428
18429     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18430       // On SSE41 targets we make use of the fact that VSELECT lowers
18431       // to PBLENDVB which selects bytes based just on the sign bit.
18432       if (Subtarget->hasSSE41()) {
18433         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18434         V0 = DAG.getBitcast(ExtVT, V0);
18435         V1 = DAG.getBitcast(ExtVT, V1);
18436         Sel = DAG.getBitcast(ExtVT, Sel);
18437         return DAG.getBitcast(
18438             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18439       }
18440       // On pre-SSE41 targets we splat the sign bit - a negative value will
18441       // set all bits of the lanes to true and VSELECT uses that in
18442       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18443       SDValue C =
18444           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18445       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18446     };
18447
18448     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18449     if (Subtarget->hasSSE41()) {
18450       // On SSE41 targets we need to replicate the shift mask in both
18451       // bytes for PBLENDVB.
18452       Amt = DAG.getNode(
18453           ISD::OR, dl, VT,
18454           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18455           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18456     } else {
18457       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18458     }
18459
18460     // r = VSELECT(r, shift(r, 8), a);
18461     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18462     R = SignBitSelect(Amt, M, R);
18463
18464     // a += a
18465     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18466
18467     // r = VSELECT(r, shift(r, 4), a);
18468     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18469     R = SignBitSelect(Amt, M, R);
18470
18471     // a += a
18472     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18473
18474     // r = VSELECT(r, shift(r, 2), a);
18475     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18476     R = SignBitSelect(Amt, M, R);
18477
18478     // a += a
18479     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18480
18481     // return VSELECT(r, shift(r, 1), a);
18482     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18483     R = SignBitSelect(Amt, M, R);
18484     return R;
18485   }
18486
18487   // Decompose 256-bit shifts into smaller 128-bit shifts.
18488   if (VT.is256BitVector()) {
18489     unsigned NumElems = VT.getVectorNumElements();
18490     MVT EltVT = VT.getVectorElementType();
18491     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18492
18493     // Extract the two vectors
18494     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18495     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18496
18497     // Recreate the shift amount vectors
18498     SDValue Amt1, Amt2;
18499     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18500       // Constant shift amount
18501       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18502       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18503       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18504
18505       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18506       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18507     } else {
18508       // Variable shift amount
18509       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18510       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18511     }
18512
18513     // Issue new vector shifts for the smaller types
18514     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18515     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18516
18517     // Concatenate the result back
18518     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18519   }
18520
18521   return SDValue();
18522 }
18523
18524 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18525   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18526   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18527   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18528   // has only one use.
18529   SDNode *N = Op.getNode();
18530   SDValue LHS = N->getOperand(0);
18531   SDValue RHS = N->getOperand(1);
18532   unsigned BaseOp = 0;
18533   unsigned Cond = 0;
18534   SDLoc DL(Op);
18535   switch (Op.getOpcode()) {
18536   default: llvm_unreachable("Unknown ovf instruction!");
18537   case ISD::SADDO:
18538     // A subtract of one will be selected as a INC. Note that INC doesn't
18539     // set CF, so we can't do this for UADDO.
18540     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18541       if (C->isOne()) {
18542         BaseOp = X86ISD::INC;
18543         Cond = X86::COND_O;
18544         break;
18545       }
18546     BaseOp = X86ISD::ADD;
18547     Cond = X86::COND_O;
18548     break;
18549   case ISD::UADDO:
18550     BaseOp = X86ISD::ADD;
18551     Cond = X86::COND_B;
18552     break;
18553   case ISD::SSUBO:
18554     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18555     // set CF, so we can't do this for USUBO.
18556     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18557       if (C->isOne()) {
18558         BaseOp = X86ISD::DEC;
18559         Cond = X86::COND_O;
18560         break;
18561       }
18562     BaseOp = X86ISD::SUB;
18563     Cond = X86::COND_O;
18564     break;
18565   case ISD::USUBO:
18566     BaseOp = X86ISD::SUB;
18567     Cond = X86::COND_B;
18568     break;
18569   case ISD::SMULO:
18570     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18571     Cond = X86::COND_O;
18572     break;
18573   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18574     if (N->getValueType(0) == MVT::i8) {
18575       BaseOp = X86ISD::UMUL8;
18576       Cond = X86::COND_O;
18577       break;
18578     }
18579     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18580                                  MVT::i32);
18581     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18582
18583     SDValue SetCC =
18584       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18585                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18586                   SDValue(Sum.getNode(), 2));
18587
18588     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18589   }
18590   }
18591
18592   // Also sets EFLAGS.
18593   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18594   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18595
18596   SDValue SetCC =
18597     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18598                 DAG.getConstant(Cond, DL, MVT::i32),
18599                 SDValue(Sum.getNode(), 1));
18600
18601   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18602 }
18603
18604 /// Returns true if the operand type is exactly twice the native width, and
18605 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18606 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18607 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18608 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18609   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18610
18611   if (OpWidth == 64)
18612     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18613   else if (OpWidth == 128)
18614     return Subtarget->hasCmpxchg16b();
18615   else
18616     return false;
18617 }
18618
18619 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18620   return needsCmpXchgNb(SI->getValueOperand()->getType());
18621 }
18622
18623 // Note: this turns large loads into lock cmpxchg8b/16b.
18624 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18625 TargetLowering::AtomicExpansionKind
18626 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18627   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18628   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
18629                                                : AtomicExpansionKind::None;
18630 }
18631
18632 TargetLowering::AtomicExpansionKind
18633 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18634   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18635   Type *MemType = AI->getType();
18636
18637   // If the operand is too big, we must see if cmpxchg8/16b is available
18638   // and default to library calls otherwise.
18639   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18640     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
18641                                    : AtomicExpansionKind::None;
18642   }
18643
18644   AtomicRMWInst::BinOp Op = AI->getOperation();
18645   switch (Op) {
18646   default:
18647     llvm_unreachable("Unknown atomic operation");
18648   case AtomicRMWInst::Xchg:
18649   case AtomicRMWInst::Add:
18650   case AtomicRMWInst::Sub:
18651     // It's better to use xadd, xsub or xchg for these in all cases.
18652     return AtomicExpansionKind::None;
18653   case AtomicRMWInst::Or:
18654   case AtomicRMWInst::And:
18655   case AtomicRMWInst::Xor:
18656     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18657     // prefix to a normal instruction for these operations.
18658     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
18659                             : AtomicExpansionKind::None;
18660   case AtomicRMWInst::Nand:
18661   case AtomicRMWInst::Max:
18662   case AtomicRMWInst::Min:
18663   case AtomicRMWInst::UMax:
18664   case AtomicRMWInst::UMin:
18665     // These always require a non-trivial set of data operations on x86. We must
18666     // use a cmpxchg loop.
18667     return AtomicExpansionKind::CmpXChg;
18668   }
18669 }
18670
18671 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18672   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18673   // no-sse2). There isn't any reason to disable it if the target processor
18674   // supports it.
18675   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18676 }
18677
18678 LoadInst *
18679 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18680   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18681   Type *MemType = AI->getType();
18682   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18683   // there is no benefit in turning such RMWs into loads, and it is actually
18684   // harmful as it introduces a mfence.
18685   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18686     return nullptr;
18687
18688   auto Builder = IRBuilder<>(AI);
18689   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18690   auto SynchScope = AI->getSynchScope();
18691   // We must restrict the ordering to avoid generating loads with Release or
18692   // ReleaseAcquire orderings.
18693   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18694   auto Ptr = AI->getPointerOperand();
18695
18696   // Before the load we need a fence. Here is an example lifted from
18697   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18698   // is required:
18699   // Thread 0:
18700   //   x.store(1, relaxed);
18701   //   r1 = y.fetch_add(0, release);
18702   // Thread 1:
18703   //   y.fetch_add(42, acquire);
18704   //   r2 = x.load(relaxed);
18705   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18706   // lowered to just a load without a fence. A mfence flushes the store buffer,
18707   // making the optimization clearly correct.
18708   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18709   // otherwise, we might be able to be more aggressive on relaxed idempotent
18710   // rmw. In practice, they do not look useful, so we don't try to be
18711   // especially clever.
18712   if (SynchScope == SingleThread)
18713     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18714     // the IR level, so we must wrap it in an intrinsic.
18715     return nullptr;
18716
18717   if (!hasMFENCE(*Subtarget))
18718     // FIXME: it might make sense to use a locked operation here but on a
18719     // different cache-line to prevent cache-line bouncing. In practice it
18720     // is probably a small win, and x86 processors without mfence are rare
18721     // enough that we do not bother.
18722     return nullptr;
18723
18724   Function *MFence =
18725       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18726   Builder.CreateCall(MFence, {});
18727
18728   // Finally we can emit the atomic load.
18729   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18730           AI->getType()->getPrimitiveSizeInBits());
18731   Loaded->setAtomic(Order, SynchScope);
18732   AI->replaceAllUsesWith(Loaded);
18733   AI->eraseFromParent();
18734   return Loaded;
18735 }
18736
18737 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18738                                  SelectionDAG &DAG) {
18739   SDLoc dl(Op);
18740   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18741     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18742   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18743     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18744
18745   // The only fence that needs an instruction is a sequentially-consistent
18746   // cross-thread fence.
18747   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18748     if (hasMFENCE(*Subtarget))
18749       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18750
18751     SDValue Chain = Op.getOperand(0);
18752     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18753     SDValue Ops[] = {
18754       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18755       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18756       DAG.getRegister(0, MVT::i32),            // Index
18757       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18758       DAG.getRegister(0, MVT::i32),            // Segment.
18759       Zero,
18760       Chain
18761     };
18762     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18763     return SDValue(Res, 0);
18764   }
18765
18766   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18767   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18768 }
18769
18770 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18771                              SelectionDAG &DAG) {
18772   MVT T = Op.getSimpleValueType();
18773   SDLoc DL(Op);
18774   unsigned Reg = 0;
18775   unsigned size = 0;
18776   switch(T.SimpleTy) {
18777   default: llvm_unreachable("Invalid value type!");
18778   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18779   case MVT::i16: Reg = X86::AX;  size = 2; break;
18780   case MVT::i32: Reg = X86::EAX; size = 4; break;
18781   case MVT::i64:
18782     assert(Subtarget->is64Bit() && "Node not type legal!");
18783     Reg = X86::RAX; size = 8;
18784     break;
18785   }
18786   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18787                                   Op.getOperand(2), SDValue());
18788   SDValue Ops[] = { cpIn.getValue(0),
18789                     Op.getOperand(1),
18790                     Op.getOperand(3),
18791                     DAG.getTargetConstant(size, DL, MVT::i8),
18792                     cpIn.getValue(1) };
18793   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18794   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18795   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18796                                            Ops, T, MMO);
18797
18798   SDValue cpOut =
18799     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18800   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18801                                       MVT::i32, cpOut.getValue(2));
18802   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18803                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18804                                 EFLAGS);
18805
18806   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18807   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18808   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18809   return SDValue();
18810 }
18811
18812 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18813                             SelectionDAG &DAG) {
18814   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18815   MVT DstVT = Op.getSimpleValueType();
18816
18817   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18818     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18819     if (DstVT != MVT::f64)
18820       // This conversion needs to be expanded.
18821       return SDValue();
18822
18823     SDValue InVec = Op->getOperand(0);
18824     SDLoc dl(Op);
18825     unsigned NumElts = SrcVT.getVectorNumElements();
18826     EVT SVT = SrcVT.getVectorElementType();
18827
18828     // Widen the vector in input in the case of MVT::v2i32.
18829     // Example: from MVT::v2i32 to MVT::v4i32.
18830     SmallVector<SDValue, 16> Elts;
18831     for (unsigned i = 0, e = NumElts; i != e; ++i)
18832       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18833                                  DAG.getIntPtrConstant(i, dl)));
18834
18835     // Explicitly mark the extra elements as Undef.
18836     Elts.append(NumElts, DAG.getUNDEF(SVT));
18837
18838     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18839     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18840     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18841     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18842                        DAG.getIntPtrConstant(0, dl));
18843   }
18844
18845   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18846          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18847   assert((DstVT == MVT::i64 ||
18848           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18849          "Unexpected custom BITCAST");
18850   // i64 <=> MMX conversions are Legal.
18851   if (SrcVT==MVT::i64 && DstVT.isVector())
18852     return Op;
18853   if (DstVT==MVT::i64 && SrcVT.isVector())
18854     return Op;
18855   // MMX <=> MMX conversions are Legal.
18856   if (SrcVT.isVector() && DstVT.isVector())
18857     return Op;
18858   // All other conversions need to be expanded.
18859   return SDValue();
18860 }
18861
18862 /// Compute the horizontal sum of bytes in V for the elements of VT.
18863 ///
18864 /// Requires V to be a byte vector and VT to be an integer vector type with
18865 /// wider elements than V's type. The width of the elements of VT determines
18866 /// how many bytes of V are summed horizontally to produce each element of the
18867 /// result.
18868 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18869                                       const X86Subtarget *Subtarget,
18870                                       SelectionDAG &DAG) {
18871   SDLoc DL(V);
18872   MVT ByteVecVT = V.getSimpleValueType();
18873   MVT EltVT = VT.getVectorElementType();
18874   int NumElts = VT.getVectorNumElements();
18875   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18876          "Expected value to have byte element type.");
18877   assert(EltVT != MVT::i8 &&
18878          "Horizontal byte sum only makes sense for wider elements!");
18879   unsigned VecSize = VT.getSizeInBits();
18880   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18881
18882   // PSADBW instruction horizontally add all bytes and leave the result in i64
18883   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18884   if (EltVT == MVT::i64) {
18885     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18886     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18887     return DAG.getBitcast(VT, V);
18888   }
18889
18890   if (EltVT == MVT::i32) {
18891     // We unpack the low half and high half into i32s interleaved with zeros so
18892     // that we can use PSADBW to horizontally sum them. The most useful part of
18893     // this is that it lines up the results of two PSADBW instructions to be
18894     // two v2i64 vectors which concatenated are the 4 population counts. We can
18895     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18896     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18897     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18898     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18899
18900     // Do the horizontal sums into two v2i64s.
18901     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18902     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18903                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18904     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18905                        DAG.getBitcast(ByteVecVT, High), Zeros);
18906
18907     // Merge them together.
18908     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18909     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18910                     DAG.getBitcast(ShortVecVT, Low),
18911                     DAG.getBitcast(ShortVecVT, High));
18912
18913     return DAG.getBitcast(VT, V);
18914   }
18915
18916   // The only element type left is i16.
18917   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18918
18919   // To obtain pop count for each i16 element starting from the pop count for
18920   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18921   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18922   // directly supported.
18923   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18924   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18925   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18926   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18927                   DAG.getBitcast(ByteVecVT, V));
18928   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18929 }
18930
18931 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18932                                         const X86Subtarget *Subtarget,
18933                                         SelectionDAG &DAG) {
18934   MVT VT = Op.getSimpleValueType();
18935   MVT EltVT = VT.getVectorElementType();
18936   unsigned VecSize = VT.getSizeInBits();
18937
18938   // Implement a lookup table in register by using an algorithm based on:
18939   // http://wm.ite.pl/articles/sse-popcount.html
18940   //
18941   // The general idea is that every lower byte nibble in the input vector is an
18942   // index into a in-register pre-computed pop count table. We then split up the
18943   // input vector in two new ones: (1) a vector with only the shifted-right
18944   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18945   // masked out higher ones) for each byte. PSHUB is used separately with both
18946   // to index the in-register table. Next, both are added and the result is a
18947   // i8 vector where each element contains the pop count for input byte.
18948   //
18949   // To obtain the pop count for elements != i8, we follow up with the same
18950   // approach and use additional tricks as described below.
18951   //
18952   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18953                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18954                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18955                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18956
18957   int NumByteElts = VecSize / 8;
18958   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18959   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18960   SmallVector<SDValue, 16> LUTVec;
18961   for (int i = 0; i < NumByteElts; ++i)
18962     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18963   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18964   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18965                                   DAG.getConstant(0x0F, DL, MVT::i8));
18966   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18967
18968   // High nibbles
18969   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18970   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18971   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18972
18973   // Low nibbles
18974   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18975
18976   // The input vector is used as the shuffle mask that index elements into the
18977   // LUT. After counting low and high nibbles, add the vector to obtain the
18978   // final pop count per i8 element.
18979   SDValue HighPopCnt =
18980       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18981   SDValue LowPopCnt =
18982       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18983   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18984
18985   if (EltVT == MVT::i8)
18986     return PopCnt;
18987
18988   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18989 }
18990
18991 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18992                                        const X86Subtarget *Subtarget,
18993                                        SelectionDAG &DAG) {
18994   MVT VT = Op.getSimpleValueType();
18995   assert(VT.is128BitVector() &&
18996          "Only 128-bit vector bitmath lowering supported.");
18997
18998   int VecSize = VT.getSizeInBits();
18999   MVT EltVT = VT.getVectorElementType();
19000   int Len = EltVT.getSizeInBits();
19001
19002   // This is the vectorized version of the "best" algorithm from
19003   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19004   // with a minor tweak to use a series of adds + shifts instead of vector
19005   // multiplications. Implemented for all integer vector types. We only use
19006   // this when we don't have SSSE3 which allows a LUT-based lowering that is
19007   // much faster, even faster than using native popcnt instructions.
19008
19009   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19010     MVT VT = V.getSimpleValueType();
19011     SmallVector<SDValue, 32> Shifters(
19012         VT.getVectorNumElements(),
19013         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19014     return DAG.getNode(OpCode, DL, VT, V,
19015                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19016   };
19017   auto GetMask = [&](SDValue V, APInt Mask) {
19018     MVT VT = V.getSimpleValueType();
19019     SmallVector<SDValue, 32> Masks(
19020         VT.getVectorNumElements(),
19021         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19022     return DAG.getNode(ISD::AND, DL, VT, V,
19023                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19024   };
19025
19026   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19027   // x86, so set the SRL type to have elements at least i16 wide. This is
19028   // correct because all of our SRLs are followed immediately by a mask anyways
19029   // that handles any bits that sneak into the high bits of the byte elements.
19030   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19031
19032   SDValue V = Op;
19033
19034   // v = v - ((v >> 1) & 0x55555555...)
19035   SDValue Srl =
19036       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19037   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19038   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19039
19040   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19041   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19042   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19043   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19044   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19045
19046   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19047   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19048   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19049   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19050
19051   // At this point, V contains the byte-wise population count, and we are
19052   // merely doing a horizontal sum if necessary to get the wider element
19053   // counts.
19054   if (EltVT == MVT::i8)
19055     return V;
19056
19057   return LowerHorizontalByteSum(
19058       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19059       DAG);
19060 }
19061
19062 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19063                                 SelectionDAG &DAG) {
19064   MVT VT = Op.getSimpleValueType();
19065   // FIXME: Need to add AVX-512 support here!
19066   assert((VT.is256BitVector() || VT.is128BitVector()) &&
19067          "Unknown CTPOP type to handle");
19068   SDLoc DL(Op.getNode());
19069   SDValue Op0 = Op.getOperand(0);
19070
19071   if (!Subtarget->hasSSSE3()) {
19072     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19073     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19074     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19075   }
19076
19077   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19078     unsigned NumElems = VT.getVectorNumElements();
19079
19080     // Extract each 128-bit vector, compute pop count and concat the result.
19081     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19082     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19083
19084     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19085                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19086                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19087   }
19088
19089   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19090 }
19091
19092 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19093                           SelectionDAG &DAG) {
19094   assert(Op.getValueType().isVector() &&
19095          "We only do custom lowering for vector population count.");
19096   return LowerVectorCTPOP(Op, Subtarget, DAG);
19097 }
19098
19099 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19100   SDNode *Node = Op.getNode();
19101   SDLoc dl(Node);
19102   EVT T = Node->getValueType(0);
19103   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19104                               DAG.getConstant(0, dl, T), Node->getOperand(2));
19105   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19106                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19107                        Node->getOperand(0),
19108                        Node->getOperand(1), negOp,
19109                        cast<AtomicSDNode>(Node)->getMemOperand(),
19110                        cast<AtomicSDNode>(Node)->getOrdering(),
19111                        cast<AtomicSDNode>(Node)->getSynchScope());
19112 }
19113
19114 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19115   SDNode *Node = Op.getNode();
19116   SDLoc dl(Node);
19117   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19118
19119   // Convert seq_cst store -> xchg
19120   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19121   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19122   //        (The only way to get a 16-byte store is cmpxchg16b)
19123   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19124   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19125       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19126     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19127                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19128                                  Node->getOperand(0),
19129                                  Node->getOperand(1), Node->getOperand(2),
19130                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19131                                  cast<AtomicSDNode>(Node)->getOrdering(),
19132                                  cast<AtomicSDNode>(Node)->getSynchScope());
19133     return Swap.getValue(1);
19134   }
19135   // Other atomic stores have a simple pattern.
19136   return Op;
19137 }
19138
19139 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19140   EVT VT = Op.getNode()->getSimpleValueType(0);
19141
19142   // Let legalize expand this if it isn't a legal type yet.
19143   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19144     return SDValue();
19145
19146   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19147
19148   unsigned Opc;
19149   bool ExtraOp = false;
19150   switch (Op.getOpcode()) {
19151   default: llvm_unreachable("Invalid code");
19152   case ISD::ADDC: Opc = X86ISD::ADD; break;
19153   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19154   case ISD::SUBC: Opc = X86ISD::SUB; break;
19155   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19156   }
19157
19158   if (!ExtraOp)
19159     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19160                        Op.getOperand(1));
19161   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19162                      Op.getOperand(1), Op.getOperand(2));
19163 }
19164
19165 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19166                             SelectionDAG &DAG) {
19167   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19168
19169   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19170   // which returns the values as { float, float } (in XMM0) or
19171   // { double, double } (which is returned in XMM0, XMM1).
19172   SDLoc dl(Op);
19173   SDValue Arg = Op.getOperand(0);
19174   EVT ArgVT = Arg.getValueType();
19175   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19176
19177   TargetLowering::ArgListTy Args;
19178   TargetLowering::ArgListEntry Entry;
19179
19180   Entry.Node = Arg;
19181   Entry.Ty = ArgTy;
19182   Entry.isSExt = false;
19183   Entry.isZExt = false;
19184   Args.push_back(Entry);
19185
19186   bool isF64 = ArgVT == MVT::f64;
19187   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19188   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19189   // the results are returned via SRet in memory.
19190   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19191   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19192   SDValue Callee =
19193       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19194
19195   Type *RetTy = isF64
19196     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19197     : (Type*)VectorType::get(ArgTy, 4);
19198
19199   TargetLowering::CallLoweringInfo CLI(DAG);
19200   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19201     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19202
19203   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19204
19205   if (isF64)
19206     // Returned in xmm0 and xmm1.
19207     return CallResult.first;
19208
19209   // Returned in bits 0:31 and 32:64 xmm0.
19210   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19211                                CallResult.first, DAG.getIntPtrConstant(0, dl));
19212   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19213                                CallResult.first, DAG.getIntPtrConstant(1, dl));
19214   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19215   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19216 }
19217
19218 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19219                              SelectionDAG &DAG) {
19220   assert(Subtarget->hasAVX512() &&
19221          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19222
19223   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19224   EVT VT = N->getValue().getValueType();
19225   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19226   SDLoc dl(Op);
19227
19228   // X86 scatter kills mask register, so its type should be added to
19229   // the list of return values
19230   if (N->getNumValues() == 1) {
19231     SDValue Index = N->getIndex();
19232     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19233         !Index.getValueType().is512BitVector())
19234       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19235
19236     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19237     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19238                       N->getOperand(3), Index };
19239
19240     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19241     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19242     return SDValue(NewScatter.getNode(), 0);
19243   }
19244   return Op;
19245 }
19246
19247 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19248                             SelectionDAG &DAG) {
19249   assert(Subtarget->hasAVX512() &&
19250          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19251
19252   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19253   EVT VT = Op.getValueType();
19254   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19255   SDLoc dl(Op);
19256
19257   SDValue Index = N->getIndex();
19258   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19259       !Index.getValueType().is512BitVector()) {
19260     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19261     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19262                       N->getOperand(3), Index };
19263     DAG.UpdateNodeOperands(N, Ops);
19264   }
19265   return Op;
19266 }
19267
19268 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19269                                                     SelectionDAG &DAG) const {
19270   // TODO: Eventually, the lowering of these nodes should be informed by or
19271   // deferred to the GC strategy for the function in which they appear. For
19272   // now, however, they must be lowered to something. Since they are logically
19273   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19274   // require special handling for these nodes), lower them as literal NOOPs for
19275   // the time being.
19276   SmallVector<SDValue, 2> Ops;
19277
19278   Ops.push_back(Op.getOperand(0));
19279   if (Op->getGluedNode())
19280     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19281
19282   SDLoc OpDL(Op);
19283   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19284   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19285
19286   return NOOP;
19287 }
19288
19289 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19290                                                   SelectionDAG &DAG) const {
19291   // TODO: Eventually, the lowering of these nodes should be informed by or
19292   // deferred to the GC strategy for the function in which they appear. For
19293   // now, however, they must be lowered to something. Since they are logically
19294   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19295   // require special handling for these nodes), lower them as literal NOOPs for
19296   // the time being.
19297   SmallVector<SDValue, 2> Ops;
19298
19299   Ops.push_back(Op.getOperand(0));
19300   if (Op->getGluedNode())
19301     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19302
19303   SDLoc OpDL(Op);
19304   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19305   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19306
19307   return NOOP;
19308 }
19309
19310 /// LowerOperation - Provide custom lowering hooks for some operations.
19311 ///
19312 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19313   switch (Op.getOpcode()) {
19314   default: llvm_unreachable("Should not custom lower this!");
19315   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19316   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19317     return LowerCMP_SWAP(Op, Subtarget, DAG);
19318   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
19319   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19320   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19321   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19322   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19323   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
19324   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19325   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19326   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19327   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19328   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19329   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19330   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19331   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19332   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19333   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19334   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19335   case ISD::SHL_PARTS:
19336   case ISD::SRA_PARTS:
19337   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19338   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19339   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19340   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19341   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19342   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19343   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19344   case ISD::SIGN_EXTEND_VECTOR_INREG:
19345     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19346   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19347   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19348   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19349   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19350   case ISD::FABS:
19351   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19352   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19353   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19354   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19355   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19356   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19357   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19358   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19359   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19360   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19361   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19362   case ISD::INTRINSIC_VOID:
19363   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19364   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19365   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19366   case ISD::FRAME_TO_ARGS_OFFSET:
19367                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19368   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19369   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19370   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19371   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19372   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19373   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19374   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19375   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
19376   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
19377   case ISD::CTTZ:
19378   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
19379   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19380   case ISD::UMUL_LOHI:
19381   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19382   case ISD::SRA:
19383   case ISD::SRL:
19384   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19385   case ISD::SADDO:
19386   case ISD::UADDO:
19387   case ISD::SSUBO:
19388   case ISD::USUBO:
19389   case ISD::SMULO:
19390   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19391   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19392   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19393   case ISD::ADDC:
19394   case ISD::ADDE:
19395   case ISD::SUBC:
19396   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19397   case ISD::ADD:                return LowerADD(Op, DAG);
19398   case ISD::SUB:                return LowerSUB(Op, DAG);
19399   case ISD::SMAX:
19400   case ISD::SMIN:
19401   case ISD::UMAX:
19402   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
19403   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19404   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
19405   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
19406   case ISD::GC_TRANSITION_START:
19407                                 return LowerGC_TRANSITION_START(Op, DAG);
19408   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
19409   }
19410 }
19411
19412 /// ReplaceNodeResults - Replace a node with an illegal result type
19413 /// with a new node built out of custom code.
19414 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19415                                            SmallVectorImpl<SDValue>&Results,
19416                                            SelectionDAG &DAG) const {
19417   SDLoc dl(N);
19418   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19419   switch (N->getOpcode()) {
19420   default:
19421     llvm_unreachable("Do not know how to custom type legalize this operation!");
19422   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19423   case X86ISD::FMINC:
19424   case X86ISD::FMIN:
19425   case X86ISD::FMAXC:
19426   case X86ISD::FMAX: {
19427     EVT VT = N->getValueType(0);
19428     if (VT != MVT::v2f32)
19429       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
19430     SDValue UNDEF = DAG.getUNDEF(VT);
19431     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19432                               N->getOperand(0), UNDEF);
19433     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19434                               N->getOperand(1), UNDEF);
19435     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19436     return;
19437   }
19438   case ISD::SIGN_EXTEND_INREG:
19439   case ISD::ADDC:
19440   case ISD::ADDE:
19441   case ISD::SUBC:
19442   case ISD::SUBE:
19443     // We don't want to expand or promote these.
19444     return;
19445   case ISD::SDIV:
19446   case ISD::UDIV:
19447   case ISD::SREM:
19448   case ISD::UREM:
19449   case ISD::SDIVREM:
19450   case ISD::UDIVREM: {
19451     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19452     Results.push_back(V);
19453     return;
19454   }
19455   case ISD::FP_TO_SINT:
19456   case ISD::FP_TO_UINT: {
19457     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19458
19459     std::pair<SDValue,SDValue> Vals =
19460         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19461     SDValue FIST = Vals.first, StackSlot = Vals.second;
19462     if (FIST.getNode()) {
19463       EVT VT = N->getValueType(0);
19464       // Return a load from the stack slot.
19465       if (StackSlot.getNode())
19466         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19467                                       MachinePointerInfo(),
19468                                       false, false, false, 0));
19469       else
19470         Results.push_back(FIST);
19471     }
19472     return;
19473   }
19474   case ISD::UINT_TO_FP: {
19475     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19476     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19477         N->getValueType(0) != MVT::v2f32)
19478       return;
19479     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19480                                  N->getOperand(0));
19481     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19482                                      MVT::f64);
19483     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19484     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19485                              DAG.getBitcast(MVT::v2i64, VBias));
19486     Or = DAG.getBitcast(MVT::v2f64, Or);
19487     // TODO: Are there any fast-math-flags to propagate here?
19488     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19489     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19490     return;
19491   }
19492   case ISD::FP_ROUND: {
19493     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19494         return;
19495     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19496     Results.push_back(V);
19497     return;
19498   }
19499   case ISD::FP_EXTEND: {
19500     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19501     // No other ValueType for FP_EXTEND should reach this point.
19502     assert(N->getValueType(0) == MVT::v2f32 &&
19503            "Do not know how to legalize this Node");
19504     return;
19505   }
19506   case ISD::INTRINSIC_W_CHAIN: {
19507     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19508     switch (IntNo) {
19509     default : llvm_unreachable("Do not know how to custom type "
19510                                "legalize this intrinsic operation!");
19511     case Intrinsic::x86_rdtsc:
19512       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19513                                      Results);
19514     case Intrinsic::x86_rdtscp:
19515       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19516                                      Results);
19517     case Intrinsic::x86_rdpmc:
19518       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19519     }
19520   }
19521   case ISD::READCYCLECOUNTER: {
19522     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19523                                    Results);
19524   }
19525   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19526     EVT T = N->getValueType(0);
19527     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19528     bool Regs64bit = T == MVT::i128;
19529     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19530     SDValue cpInL, cpInH;
19531     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19532                         DAG.getConstant(0, dl, HalfT));
19533     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19534                         DAG.getConstant(1, dl, HalfT));
19535     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19536                              Regs64bit ? X86::RAX : X86::EAX,
19537                              cpInL, SDValue());
19538     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19539                              Regs64bit ? X86::RDX : X86::EDX,
19540                              cpInH, cpInL.getValue(1));
19541     SDValue swapInL, swapInH;
19542     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19543                           DAG.getConstant(0, dl, HalfT));
19544     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19545                           DAG.getConstant(1, dl, HalfT));
19546     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19547                                Regs64bit ? X86::RBX : X86::EBX,
19548                                swapInL, cpInH.getValue(1));
19549     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19550                                Regs64bit ? X86::RCX : X86::ECX,
19551                                swapInH, swapInL.getValue(1));
19552     SDValue Ops[] = { swapInH.getValue(0),
19553                       N->getOperand(1),
19554                       swapInH.getValue(1) };
19555     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19556     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19557     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19558                                   X86ISD::LCMPXCHG8_DAG;
19559     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19560     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19561                                         Regs64bit ? X86::RAX : X86::EAX,
19562                                         HalfT, Result.getValue(1));
19563     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19564                                         Regs64bit ? X86::RDX : X86::EDX,
19565                                         HalfT, cpOutL.getValue(2));
19566     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19567
19568     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19569                                         MVT::i32, cpOutH.getValue(2));
19570     SDValue Success =
19571         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19572                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19573     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19574
19575     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19576     Results.push_back(Success);
19577     Results.push_back(EFLAGS.getValue(1));
19578     return;
19579   }
19580   case ISD::ATOMIC_SWAP:
19581   case ISD::ATOMIC_LOAD_ADD:
19582   case ISD::ATOMIC_LOAD_SUB:
19583   case ISD::ATOMIC_LOAD_AND:
19584   case ISD::ATOMIC_LOAD_OR:
19585   case ISD::ATOMIC_LOAD_XOR:
19586   case ISD::ATOMIC_LOAD_NAND:
19587   case ISD::ATOMIC_LOAD_MIN:
19588   case ISD::ATOMIC_LOAD_MAX:
19589   case ISD::ATOMIC_LOAD_UMIN:
19590   case ISD::ATOMIC_LOAD_UMAX:
19591   case ISD::ATOMIC_LOAD: {
19592     // Delegate to generic TypeLegalization. Situations we can really handle
19593     // should have already been dealt with by AtomicExpandPass.cpp.
19594     break;
19595   }
19596   case ISD::BITCAST: {
19597     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19598     EVT DstVT = N->getValueType(0);
19599     EVT SrcVT = N->getOperand(0)->getValueType(0);
19600
19601     if (SrcVT != MVT::f64 ||
19602         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19603       return;
19604
19605     unsigned NumElts = DstVT.getVectorNumElements();
19606     EVT SVT = DstVT.getVectorElementType();
19607     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19608     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19609                                    MVT::v2f64, N->getOperand(0));
19610     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19611
19612     if (ExperimentalVectorWideningLegalization) {
19613       // If we are legalizing vectors by widening, we already have the desired
19614       // legal vector type, just return it.
19615       Results.push_back(ToVecInt);
19616       return;
19617     }
19618
19619     SmallVector<SDValue, 8> Elts;
19620     for (unsigned i = 0, e = NumElts; i != e; ++i)
19621       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19622                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19623
19624     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19625   }
19626   }
19627 }
19628
19629 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19630   switch ((X86ISD::NodeType)Opcode) {
19631   case X86ISD::FIRST_NUMBER:       break;
19632   case X86ISD::BSF:                return "X86ISD::BSF";
19633   case X86ISD::BSR:                return "X86ISD::BSR";
19634   case X86ISD::SHLD:               return "X86ISD::SHLD";
19635   case X86ISD::SHRD:               return "X86ISD::SHRD";
19636   case X86ISD::FAND:               return "X86ISD::FAND";
19637   case X86ISD::FANDN:              return "X86ISD::FANDN";
19638   case X86ISD::FOR:                return "X86ISD::FOR";
19639   case X86ISD::FXOR:               return "X86ISD::FXOR";
19640   case X86ISD::FILD:               return "X86ISD::FILD";
19641   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19642   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19643   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19644   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19645   case X86ISD::FLD:                return "X86ISD::FLD";
19646   case X86ISD::FST:                return "X86ISD::FST";
19647   case X86ISD::CALL:               return "X86ISD::CALL";
19648   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19649   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19650   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19651   case X86ISD::BT:                 return "X86ISD::BT";
19652   case X86ISD::CMP:                return "X86ISD::CMP";
19653   case X86ISD::COMI:               return "X86ISD::COMI";
19654   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19655   case X86ISD::CMPM:               return "X86ISD::CMPM";
19656   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19657   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19658   case X86ISD::SETCC:              return "X86ISD::SETCC";
19659   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19660   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19661   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19662   case X86ISD::CMOV:               return "X86ISD::CMOV";
19663   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19664   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19665   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19666   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19667   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19668   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19669   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19670   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19671   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19672   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19673   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19674   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19675   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19676   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19677   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19678   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19679   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19680   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19681   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19682   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19683   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19684   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19685   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19686   case X86ISD::HADD:               return "X86ISD::HADD";
19687   case X86ISD::HSUB:               return "X86ISD::HSUB";
19688   case X86ISD::FHADD:              return "X86ISD::FHADD";
19689   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19690   case X86ISD::ABS:                return "X86ISD::ABS";
19691   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
19692   case X86ISD::FMAX:               return "X86ISD::FMAX";
19693   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19694   case X86ISD::FMIN:               return "X86ISD::FMIN";
19695   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19696   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19697   case X86ISD::FMINC:              return "X86ISD::FMINC";
19698   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19699   case X86ISD::FRCP:               return "X86ISD::FRCP";
19700   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19701   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19702   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19703   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19704   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19705   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19706   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19707   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19708   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19709   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19710   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19711   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19712   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19713   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19714   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19715   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19716   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19717   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19718   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19719   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19720   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19721   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19722   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19723   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19724   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19725   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19726   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19727   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19728   case X86ISD::VSHL:               return "X86ISD::VSHL";
19729   case X86ISD::VSRL:               return "X86ISD::VSRL";
19730   case X86ISD::VSRA:               return "X86ISD::VSRA";
19731   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19732   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19733   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19734   case X86ISD::CMPP:               return "X86ISD::CMPP";
19735   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19736   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19737   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19738   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19739   case X86ISD::ADD:                return "X86ISD::ADD";
19740   case X86ISD::SUB:                return "X86ISD::SUB";
19741   case X86ISD::ADC:                return "X86ISD::ADC";
19742   case X86ISD::SBB:                return "X86ISD::SBB";
19743   case X86ISD::SMUL:               return "X86ISD::SMUL";
19744   case X86ISD::UMUL:               return "X86ISD::UMUL";
19745   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19746   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19747   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19748   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19749   case X86ISD::INC:                return "X86ISD::INC";
19750   case X86ISD::DEC:                return "X86ISD::DEC";
19751   case X86ISD::OR:                 return "X86ISD::OR";
19752   case X86ISD::XOR:                return "X86ISD::XOR";
19753   case X86ISD::AND:                return "X86ISD::AND";
19754   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19755   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19756   case X86ISD::PTEST:              return "X86ISD::PTEST";
19757   case X86ISD::TESTP:              return "X86ISD::TESTP";
19758   case X86ISD::TESTM:              return "X86ISD::TESTM";
19759   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19760   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19761   case X86ISD::KTEST:              return "X86ISD::KTEST";
19762   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19763   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19764   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19765   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19766   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19767   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19768   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19769   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19770   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19771   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19772   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19773   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19774   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19775   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19776   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19777   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19778   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19779   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19780   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19781   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19782   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19783   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19784   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19785   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19786   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19787   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19788   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19789   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19790   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19791   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19792   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19793   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19794   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19795   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19796   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19797   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19798   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
19799   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19800   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19801   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19802   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19803   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19804   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19805   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19806   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19807   case X86ISD::SAHF:               return "X86ISD::SAHF";
19808   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19809   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19810   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19811   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19812   case X86ISD::FMADD:              return "X86ISD::FMADD";
19813   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19814   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19815   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19816   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19817   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19818   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19819   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19820   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19821   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19822   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19823   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19824   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19825   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19826   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
19827   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19828   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19829   case X86ISD::XTEST:              return "X86ISD::XTEST";
19830   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19831   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19832   case X86ISD::SELECT:             return "X86ISD::SELECT";
19833   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19834   case X86ISD::RCP28:              return "X86ISD::RCP28";
19835   case X86ISD::EXP2:               return "X86ISD::EXP2";
19836   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19837   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19838   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19839   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19840   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19841   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19842   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19843   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19844   case X86ISD::ADDS:               return "X86ISD::ADDS";
19845   case X86ISD::SUBS:               return "X86ISD::SUBS";
19846   case X86ISD::AVG:                return "X86ISD::AVG";
19847   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19848   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19849   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19850   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19851   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19852   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
19853   }
19854   return nullptr;
19855 }
19856
19857 // isLegalAddressingMode - Return true if the addressing mode represented
19858 // by AM is legal for this target, for a load/store of the specified type.
19859 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19860                                               const AddrMode &AM, Type *Ty,
19861                                               unsigned AS) const {
19862   // X86 supports extremely general addressing modes.
19863   CodeModel::Model M = getTargetMachine().getCodeModel();
19864   Reloc::Model R = getTargetMachine().getRelocationModel();
19865
19866   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19867   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19868     return false;
19869
19870   if (AM.BaseGV) {
19871     unsigned GVFlags =
19872       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19873
19874     // If a reference to this global requires an extra load, we can't fold it.
19875     if (isGlobalStubReference(GVFlags))
19876       return false;
19877
19878     // If BaseGV requires a register for the PIC base, we cannot also have a
19879     // BaseReg specified.
19880     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19881       return false;
19882
19883     // If lower 4G is not available, then we must use rip-relative addressing.
19884     if ((M != CodeModel::Small || R != Reloc::Static) &&
19885         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19886       return false;
19887   }
19888
19889   switch (AM.Scale) {
19890   case 0:
19891   case 1:
19892   case 2:
19893   case 4:
19894   case 8:
19895     // These scales always work.
19896     break;
19897   case 3:
19898   case 5:
19899   case 9:
19900     // These scales are formed with basereg+scalereg.  Only accept if there is
19901     // no basereg yet.
19902     if (AM.HasBaseReg)
19903       return false;
19904     break;
19905   default:  // Other stuff never works.
19906     return false;
19907   }
19908
19909   return true;
19910 }
19911
19912 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19913   unsigned Bits = Ty->getScalarSizeInBits();
19914
19915   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19916   // particularly cheaper than those without.
19917   if (Bits == 8)
19918     return false;
19919
19920   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19921   // variable shifts just as cheap as scalar ones.
19922   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19923     return false;
19924
19925   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19926   // fully general vector.
19927   return true;
19928 }
19929
19930 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19931   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19932     return false;
19933   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19934   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19935   return NumBits1 > NumBits2;
19936 }
19937
19938 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19939   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19940     return false;
19941
19942   if (!isTypeLegal(EVT::getEVT(Ty1)))
19943     return false;
19944
19945   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19946
19947   // Assuming the caller doesn't have a zeroext or signext return parameter,
19948   // truncation all the way down to i1 is valid.
19949   return true;
19950 }
19951
19952 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19953   return isInt<32>(Imm);
19954 }
19955
19956 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19957   // Can also use sub to handle negated immediates.
19958   return isInt<32>(Imm);
19959 }
19960
19961 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19962   if (!VT1.isInteger() || !VT2.isInteger())
19963     return false;
19964   unsigned NumBits1 = VT1.getSizeInBits();
19965   unsigned NumBits2 = VT2.getSizeInBits();
19966   return NumBits1 > NumBits2;
19967 }
19968
19969 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19970   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19971   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19972 }
19973
19974 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19975   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19976   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19977 }
19978
19979 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19980   EVT VT1 = Val.getValueType();
19981   if (isZExtFree(VT1, VT2))
19982     return true;
19983
19984   if (Val.getOpcode() != ISD::LOAD)
19985     return false;
19986
19987   if (!VT1.isSimple() || !VT1.isInteger() ||
19988       !VT2.isSimple() || !VT2.isInteger())
19989     return false;
19990
19991   switch (VT1.getSimpleVT().SimpleTy) {
19992   default: break;
19993   case MVT::i8:
19994   case MVT::i16:
19995   case MVT::i32:
19996     // X86 has 8, 16, and 32-bit zero-extending loads.
19997     return true;
19998   }
19999
20000   return false;
20001 }
20002
20003 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
20004
20005 bool
20006 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20007   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
20008     return false;
20009
20010   VT = VT.getScalarType();
20011
20012   if (!VT.isSimple())
20013     return false;
20014
20015   switch (VT.getSimpleVT().SimpleTy) {
20016   case MVT::f32:
20017   case MVT::f64:
20018     return true;
20019   default:
20020     break;
20021   }
20022
20023   return false;
20024 }
20025
20026 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20027   // i16 instructions are longer (0x66 prefix) and potentially slower.
20028   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20029 }
20030
20031 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20032 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20033 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20034 /// are assumed to be legal.
20035 bool
20036 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20037                                       EVT VT) const {
20038   if (!VT.isSimple())
20039     return false;
20040
20041   // Not for i1 vectors
20042   if (VT.getScalarType() == MVT::i1)
20043     return false;
20044
20045   // Very little shuffling can be done for 64-bit vectors right now.
20046   if (VT.getSizeInBits() == 64)
20047     return false;
20048
20049   // We only care that the types being shuffled are legal. The lowering can
20050   // handle any possible shuffle mask that results.
20051   return isTypeLegal(VT.getSimpleVT());
20052 }
20053
20054 bool
20055 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20056                                           EVT VT) const {
20057   // Just delegate to the generic legality, clear masks aren't special.
20058   return isShuffleMaskLegal(Mask, VT);
20059 }
20060
20061 //===----------------------------------------------------------------------===//
20062 //                           X86 Scheduler Hooks
20063 //===----------------------------------------------------------------------===//
20064
20065 /// Utility function to emit xbegin specifying the start of an RTM region.
20066 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20067                                      const TargetInstrInfo *TII) {
20068   DebugLoc DL = MI->getDebugLoc();
20069
20070   const BasicBlock *BB = MBB->getBasicBlock();
20071   MachineFunction::iterator I = MBB;
20072   ++I;
20073
20074   // For the v = xbegin(), we generate
20075   //
20076   // thisMBB:
20077   //  xbegin sinkMBB
20078   //
20079   // mainMBB:
20080   //  eax = -1
20081   //
20082   // sinkMBB:
20083   //  v = eax
20084
20085   MachineBasicBlock *thisMBB = MBB;
20086   MachineFunction *MF = MBB->getParent();
20087   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20088   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20089   MF->insert(I, mainMBB);
20090   MF->insert(I, sinkMBB);
20091
20092   // Transfer the remainder of BB and its successor edges to sinkMBB.
20093   sinkMBB->splice(sinkMBB->begin(), MBB,
20094                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20095   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20096
20097   // thisMBB:
20098   //  xbegin sinkMBB
20099   //  # fallthrough to mainMBB
20100   //  # abortion to sinkMBB
20101   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20102   thisMBB->addSuccessor(mainMBB);
20103   thisMBB->addSuccessor(sinkMBB);
20104
20105   // mainMBB:
20106   //  EAX = -1
20107   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20108   mainMBB->addSuccessor(sinkMBB);
20109
20110   // sinkMBB:
20111   // EAX is live into the sinkMBB
20112   sinkMBB->addLiveIn(X86::EAX);
20113   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20114           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20115     .addReg(X86::EAX);
20116
20117   MI->eraseFromParent();
20118   return sinkMBB;
20119 }
20120
20121 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20122 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20123 // in the .td file.
20124 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20125                                        const TargetInstrInfo *TII) {
20126   unsigned Opc;
20127   switch (MI->getOpcode()) {
20128   default: llvm_unreachable("illegal opcode!");
20129   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
20130   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20131   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
20132   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20133   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
20134   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20135   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
20136   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20137   }
20138
20139   DebugLoc dl = MI->getDebugLoc();
20140   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20141
20142   unsigned NumArgs = MI->getNumOperands();
20143   for (unsigned i = 1; i < NumArgs; ++i) {
20144     MachineOperand &Op = MI->getOperand(i);
20145     if (!(Op.isReg() && Op.isImplicit()))
20146       MIB.addOperand(Op);
20147   }
20148   if (MI->hasOneMemOperand())
20149     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20150
20151   BuildMI(*BB, MI, dl,
20152     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20153     .addReg(X86::XMM0);
20154
20155   MI->eraseFromParent();
20156   return BB;
20157 }
20158
20159 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20160 // defs in an instruction pattern
20161 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20162                                        const TargetInstrInfo *TII) {
20163   unsigned Opc;
20164   switch (MI->getOpcode()) {
20165   default: llvm_unreachable("illegal opcode!");
20166   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
20167   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20168   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
20169   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20170   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
20171   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20172   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
20173   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20174   }
20175
20176   DebugLoc dl = MI->getDebugLoc();
20177   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20178
20179   unsigned NumArgs = MI->getNumOperands(); // remove the results
20180   for (unsigned i = 1; i < NumArgs; ++i) {
20181     MachineOperand &Op = MI->getOperand(i);
20182     if (!(Op.isReg() && Op.isImplicit()))
20183       MIB.addOperand(Op);
20184   }
20185   if (MI->hasOneMemOperand())
20186     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20187
20188   BuildMI(*BB, MI, dl,
20189     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20190     .addReg(X86::ECX);
20191
20192   MI->eraseFromParent();
20193   return BB;
20194 }
20195
20196 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20197                                       const X86Subtarget *Subtarget) {
20198   DebugLoc dl = MI->getDebugLoc();
20199   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20200   // Address into RAX/EAX, other two args into ECX, EDX.
20201   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20202   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20203   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20204   for (int i = 0; i < X86::AddrNumOperands; ++i)
20205     MIB.addOperand(MI->getOperand(i));
20206
20207   unsigned ValOps = X86::AddrNumOperands;
20208   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20209     .addReg(MI->getOperand(ValOps).getReg());
20210   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20211     .addReg(MI->getOperand(ValOps+1).getReg());
20212
20213   // The instruction doesn't actually take any operands though.
20214   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20215
20216   MI->eraseFromParent(); // The pseudo is gone now.
20217   return BB;
20218 }
20219
20220 MachineBasicBlock *
20221 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20222                                                  MachineBasicBlock *MBB) const {
20223   // Emit va_arg instruction on X86-64.
20224
20225   // Operands to this pseudo-instruction:
20226   // 0  ) Output        : destination address (reg)
20227   // 1-5) Input         : va_list address (addr, i64mem)
20228   // 6  ) ArgSize       : Size (in bytes) of vararg type
20229   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20230   // 8  ) Align         : Alignment of type
20231   // 9  ) EFLAGS (implicit-def)
20232
20233   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20234   static_assert(X86::AddrNumOperands == 5,
20235                 "VAARG_64 assumes 5 address operands");
20236
20237   unsigned DestReg = MI->getOperand(0).getReg();
20238   MachineOperand &Base = MI->getOperand(1);
20239   MachineOperand &Scale = MI->getOperand(2);
20240   MachineOperand &Index = MI->getOperand(3);
20241   MachineOperand &Disp = MI->getOperand(4);
20242   MachineOperand &Segment = MI->getOperand(5);
20243   unsigned ArgSize = MI->getOperand(6).getImm();
20244   unsigned ArgMode = MI->getOperand(7).getImm();
20245   unsigned Align = MI->getOperand(8).getImm();
20246
20247   // Memory Reference
20248   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20249   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20250   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20251
20252   // Machine Information
20253   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20254   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20255   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20256   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20257   DebugLoc DL = MI->getDebugLoc();
20258
20259   // struct va_list {
20260   //   i32   gp_offset
20261   //   i32   fp_offset
20262   //   i64   overflow_area (address)
20263   //   i64   reg_save_area (address)
20264   // }
20265   // sizeof(va_list) = 24
20266   // alignment(va_list) = 8
20267
20268   unsigned TotalNumIntRegs = 6;
20269   unsigned TotalNumXMMRegs = 8;
20270   bool UseGPOffset = (ArgMode == 1);
20271   bool UseFPOffset = (ArgMode == 2);
20272   unsigned MaxOffset = TotalNumIntRegs * 8 +
20273                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20274
20275   /* Align ArgSize to a multiple of 8 */
20276   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20277   bool NeedsAlign = (Align > 8);
20278
20279   MachineBasicBlock *thisMBB = MBB;
20280   MachineBasicBlock *overflowMBB;
20281   MachineBasicBlock *offsetMBB;
20282   MachineBasicBlock *endMBB;
20283
20284   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20285   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20286   unsigned OffsetReg = 0;
20287
20288   if (!UseGPOffset && !UseFPOffset) {
20289     // If we only pull from the overflow region, we don't create a branch.
20290     // We don't need to alter control flow.
20291     OffsetDestReg = 0; // unused
20292     OverflowDestReg = DestReg;
20293
20294     offsetMBB = nullptr;
20295     overflowMBB = thisMBB;
20296     endMBB = thisMBB;
20297   } else {
20298     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20299     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20300     // If not, pull from overflow_area. (branch to overflowMBB)
20301     //
20302     //       thisMBB
20303     //         |     .
20304     //         |        .
20305     //     offsetMBB   overflowMBB
20306     //         |        .
20307     //         |     .
20308     //        endMBB
20309
20310     // Registers for the PHI in endMBB
20311     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20312     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20313
20314     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20315     MachineFunction *MF = MBB->getParent();
20316     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20317     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20318     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20319
20320     MachineFunction::iterator MBBIter = MBB;
20321     ++MBBIter;
20322
20323     // Insert the new basic blocks
20324     MF->insert(MBBIter, offsetMBB);
20325     MF->insert(MBBIter, overflowMBB);
20326     MF->insert(MBBIter, endMBB);
20327
20328     // Transfer the remainder of MBB and its successor edges to endMBB.
20329     endMBB->splice(endMBB->begin(), thisMBB,
20330                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20331     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20332
20333     // Make offsetMBB and overflowMBB successors of thisMBB
20334     thisMBB->addSuccessor(offsetMBB);
20335     thisMBB->addSuccessor(overflowMBB);
20336
20337     // endMBB is a successor of both offsetMBB and overflowMBB
20338     offsetMBB->addSuccessor(endMBB);
20339     overflowMBB->addSuccessor(endMBB);
20340
20341     // Load the offset value into a register
20342     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20343     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20344       .addOperand(Base)
20345       .addOperand(Scale)
20346       .addOperand(Index)
20347       .addDisp(Disp, UseFPOffset ? 4 : 0)
20348       .addOperand(Segment)
20349       .setMemRefs(MMOBegin, MMOEnd);
20350
20351     // Check if there is enough room left to pull this argument.
20352     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20353       .addReg(OffsetReg)
20354       .addImm(MaxOffset + 8 - ArgSizeA8);
20355
20356     // Branch to "overflowMBB" if offset >= max
20357     // Fall through to "offsetMBB" otherwise
20358     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20359       .addMBB(overflowMBB);
20360   }
20361
20362   // In offsetMBB, emit code to use the reg_save_area.
20363   if (offsetMBB) {
20364     assert(OffsetReg != 0);
20365
20366     // Read the reg_save_area address.
20367     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20368     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20369       .addOperand(Base)
20370       .addOperand(Scale)
20371       .addOperand(Index)
20372       .addDisp(Disp, 16)
20373       .addOperand(Segment)
20374       .setMemRefs(MMOBegin, MMOEnd);
20375
20376     // Zero-extend the offset
20377     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20378       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20379         .addImm(0)
20380         .addReg(OffsetReg)
20381         .addImm(X86::sub_32bit);
20382
20383     // Add the offset to the reg_save_area to get the final address.
20384     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20385       .addReg(OffsetReg64)
20386       .addReg(RegSaveReg);
20387
20388     // Compute the offset for the next argument
20389     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20390     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20391       .addReg(OffsetReg)
20392       .addImm(UseFPOffset ? 16 : 8);
20393
20394     // Store it back into the va_list.
20395     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20396       .addOperand(Base)
20397       .addOperand(Scale)
20398       .addOperand(Index)
20399       .addDisp(Disp, UseFPOffset ? 4 : 0)
20400       .addOperand(Segment)
20401       .addReg(NextOffsetReg)
20402       .setMemRefs(MMOBegin, MMOEnd);
20403
20404     // Jump to endMBB
20405     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20406       .addMBB(endMBB);
20407   }
20408
20409   //
20410   // Emit code to use overflow area
20411   //
20412
20413   // Load the overflow_area address into a register.
20414   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20415   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20416     .addOperand(Base)
20417     .addOperand(Scale)
20418     .addOperand(Index)
20419     .addDisp(Disp, 8)
20420     .addOperand(Segment)
20421     .setMemRefs(MMOBegin, MMOEnd);
20422
20423   // If we need to align it, do so. Otherwise, just copy the address
20424   // to OverflowDestReg.
20425   if (NeedsAlign) {
20426     // Align the overflow address
20427     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20428     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20429
20430     // aligned_addr = (addr + (align-1)) & ~(align-1)
20431     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20432       .addReg(OverflowAddrReg)
20433       .addImm(Align-1);
20434
20435     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20436       .addReg(TmpReg)
20437       .addImm(~(uint64_t)(Align-1));
20438   } else {
20439     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20440       .addReg(OverflowAddrReg);
20441   }
20442
20443   // Compute the next overflow address after this argument.
20444   // (the overflow address should be kept 8-byte aligned)
20445   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20446   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20447     .addReg(OverflowDestReg)
20448     .addImm(ArgSizeA8);
20449
20450   // Store the new overflow address.
20451   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20452     .addOperand(Base)
20453     .addOperand(Scale)
20454     .addOperand(Index)
20455     .addDisp(Disp, 8)
20456     .addOperand(Segment)
20457     .addReg(NextAddrReg)
20458     .setMemRefs(MMOBegin, MMOEnd);
20459
20460   // If we branched, emit the PHI to the front of endMBB.
20461   if (offsetMBB) {
20462     BuildMI(*endMBB, endMBB->begin(), DL,
20463             TII->get(X86::PHI), DestReg)
20464       .addReg(OffsetDestReg).addMBB(offsetMBB)
20465       .addReg(OverflowDestReg).addMBB(overflowMBB);
20466   }
20467
20468   // Erase the pseudo instruction
20469   MI->eraseFromParent();
20470
20471   return endMBB;
20472 }
20473
20474 MachineBasicBlock *
20475 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20476                                                  MachineInstr *MI,
20477                                                  MachineBasicBlock *MBB) const {
20478   // Emit code to save XMM registers to the stack. The ABI says that the
20479   // number of registers to save is given in %al, so it's theoretically
20480   // possible to do an indirect jump trick to avoid saving all of them,
20481   // however this code takes a simpler approach and just executes all
20482   // of the stores if %al is non-zero. It's less code, and it's probably
20483   // easier on the hardware branch predictor, and stores aren't all that
20484   // expensive anyway.
20485
20486   // Create the new basic blocks. One block contains all the XMM stores,
20487   // and one block is the final destination regardless of whether any
20488   // stores were performed.
20489   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20490   MachineFunction *F = MBB->getParent();
20491   MachineFunction::iterator MBBIter = MBB;
20492   ++MBBIter;
20493   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20494   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20495   F->insert(MBBIter, XMMSaveMBB);
20496   F->insert(MBBIter, EndMBB);
20497
20498   // Transfer the remainder of MBB and its successor edges to EndMBB.
20499   EndMBB->splice(EndMBB->begin(), MBB,
20500                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20501   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20502
20503   // The original block will now fall through to the XMM save block.
20504   MBB->addSuccessor(XMMSaveMBB);
20505   // The XMMSaveMBB will fall through to the end block.
20506   XMMSaveMBB->addSuccessor(EndMBB);
20507
20508   // Now add the instructions.
20509   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20510   DebugLoc DL = MI->getDebugLoc();
20511
20512   unsigned CountReg = MI->getOperand(0).getReg();
20513   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20514   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20515
20516   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20517     // If %al is 0, branch around the XMM save block.
20518     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20519     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20520     MBB->addSuccessor(EndMBB);
20521   }
20522
20523   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20524   // that was just emitted, but clearly shouldn't be "saved".
20525   assert((MI->getNumOperands() <= 3 ||
20526           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20527           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20528          && "Expected last argument to be EFLAGS");
20529   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20530   // In the XMM save block, save all the XMM argument registers.
20531   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20532     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20533     MachineMemOperand *MMO = F->getMachineMemOperand(
20534         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20535         MachineMemOperand::MOStore,
20536         /*Size=*/16, /*Align=*/16);
20537     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20538       .addFrameIndex(RegSaveFrameIndex)
20539       .addImm(/*Scale=*/1)
20540       .addReg(/*IndexReg=*/0)
20541       .addImm(/*Disp=*/Offset)
20542       .addReg(/*Segment=*/0)
20543       .addReg(MI->getOperand(i).getReg())
20544       .addMemOperand(MMO);
20545   }
20546
20547   MI->eraseFromParent();   // The pseudo instruction is gone now.
20548
20549   return EndMBB;
20550 }
20551
20552 // The EFLAGS operand of SelectItr might be missing a kill marker
20553 // because there were multiple uses of EFLAGS, and ISel didn't know
20554 // which to mark. Figure out whether SelectItr should have had a
20555 // kill marker, and set it if it should. Returns the correct kill
20556 // marker value.
20557 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20558                                      MachineBasicBlock* BB,
20559                                      const TargetRegisterInfo* TRI) {
20560   // Scan forward through BB for a use/def of EFLAGS.
20561   MachineBasicBlock::iterator miI(std::next(SelectItr));
20562   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20563     const MachineInstr& mi = *miI;
20564     if (mi.readsRegister(X86::EFLAGS))
20565       return false;
20566     if (mi.definesRegister(X86::EFLAGS))
20567       break; // Should have kill-flag - update below.
20568   }
20569
20570   // If we hit the end of the block, check whether EFLAGS is live into a
20571   // successor.
20572   if (miI == BB->end()) {
20573     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20574                                           sEnd = BB->succ_end();
20575          sItr != sEnd; ++sItr) {
20576       MachineBasicBlock* succ = *sItr;
20577       if (succ->isLiveIn(X86::EFLAGS))
20578         return false;
20579     }
20580   }
20581
20582   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20583   // out. SelectMI should have a kill flag on EFLAGS.
20584   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20585   return true;
20586 }
20587
20588 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20589 // together with other CMOV pseudo-opcodes into a single basic-block with
20590 // conditional jump around it.
20591 static bool isCMOVPseudo(MachineInstr *MI) {
20592   switch (MI->getOpcode()) {
20593   case X86::CMOV_FR32:
20594   case X86::CMOV_FR64:
20595   case X86::CMOV_GR8:
20596   case X86::CMOV_GR16:
20597   case X86::CMOV_GR32:
20598   case X86::CMOV_RFP32:
20599   case X86::CMOV_RFP64:
20600   case X86::CMOV_RFP80:
20601   case X86::CMOV_V2F64:
20602   case X86::CMOV_V2I64:
20603   case X86::CMOV_V4F32:
20604   case X86::CMOV_V4F64:
20605   case X86::CMOV_V4I64:
20606   case X86::CMOV_V16F32:
20607   case X86::CMOV_V8F32:
20608   case X86::CMOV_V8F64:
20609   case X86::CMOV_V8I64:
20610   case X86::CMOV_V8I1:
20611   case X86::CMOV_V16I1:
20612   case X86::CMOV_V32I1:
20613   case X86::CMOV_V64I1:
20614     return true;
20615
20616   default:
20617     return false;
20618   }
20619 }
20620
20621 MachineBasicBlock *
20622 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20623                                      MachineBasicBlock *BB) const {
20624   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20625   DebugLoc DL = MI->getDebugLoc();
20626
20627   // To "insert" a SELECT_CC instruction, we actually have to insert the
20628   // diamond control-flow pattern.  The incoming instruction knows the
20629   // destination vreg to set, the condition code register to branch on, the
20630   // true/false values to select between, and a branch opcode to use.
20631   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20632   MachineFunction::iterator It = BB;
20633   ++It;
20634
20635   //  thisMBB:
20636   //  ...
20637   //   TrueVal = ...
20638   //   cmpTY ccX, r1, r2
20639   //   bCC copy1MBB
20640   //   fallthrough --> copy0MBB
20641   MachineBasicBlock *thisMBB = BB;
20642   MachineFunction *F = BB->getParent();
20643
20644   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20645   // as described above, by inserting a BB, and then making a PHI at the join
20646   // point to select the true and false operands of the CMOV in the PHI.
20647   //
20648   // The code also handles two different cases of multiple CMOV opcodes
20649   // in a row.
20650   //
20651   // Case 1:
20652   // In this case, there are multiple CMOVs in a row, all which are based on
20653   // the same condition setting (or the exact opposite condition setting).
20654   // In this case we can lower all the CMOVs using a single inserted BB, and
20655   // then make a number of PHIs at the join point to model the CMOVs. The only
20656   // trickiness here, is that in a case like:
20657   //
20658   // t2 = CMOV cond1 t1, f1
20659   // t3 = CMOV cond1 t2, f2
20660   //
20661   // when rewriting this into PHIs, we have to perform some renaming on the
20662   // temps since you cannot have a PHI operand refer to a PHI result earlier
20663   // in the same block.  The "simple" but wrong lowering would be:
20664   //
20665   // t2 = PHI t1(BB1), f1(BB2)
20666   // t3 = PHI t2(BB1), f2(BB2)
20667   //
20668   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20669   // renaming is to note that on the path through BB1, t2 is really just a
20670   // copy of t1, and do that renaming, properly generating:
20671   //
20672   // t2 = PHI t1(BB1), f1(BB2)
20673   // t3 = PHI t1(BB1), f2(BB2)
20674   //
20675   // Case 2, we lower cascaded CMOVs such as
20676   //
20677   //   (CMOV (CMOV F, T, cc1), T, cc2)
20678   //
20679   // to two successives branches.  For that, we look for another CMOV as the
20680   // following instruction.
20681   //
20682   // Without this, we would add a PHI between the two jumps, which ends up
20683   // creating a few copies all around. For instance, for
20684   //
20685   //    (sitofp (zext (fcmp une)))
20686   //
20687   // we would generate:
20688   //
20689   //         ucomiss %xmm1, %xmm0
20690   //         movss  <1.0f>, %xmm0
20691   //         movaps  %xmm0, %xmm1
20692   //         jne     .LBB5_2
20693   //         xorps   %xmm1, %xmm1
20694   // .LBB5_2:
20695   //         jp      .LBB5_4
20696   //         movaps  %xmm1, %xmm0
20697   // .LBB5_4:
20698   //         retq
20699   //
20700   // because this custom-inserter would have generated:
20701   //
20702   //   A
20703   //   | \
20704   //   |  B
20705   //   | /
20706   //   C
20707   //   | \
20708   //   |  D
20709   //   | /
20710   //   E
20711   //
20712   // A: X = ...; Y = ...
20713   // B: empty
20714   // C: Z = PHI [X, A], [Y, B]
20715   // D: empty
20716   // E: PHI [X, C], [Z, D]
20717   //
20718   // If we lower both CMOVs in a single step, we can instead generate:
20719   //
20720   //   A
20721   //   | \
20722   //   |  C
20723   //   | /|
20724   //   |/ |
20725   //   |  |
20726   //   |  D
20727   //   | /
20728   //   E
20729   //
20730   // A: X = ...; Y = ...
20731   // D: empty
20732   // E: PHI [X, A], [X, C], [Y, D]
20733   //
20734   // Which, in our sitofp/fcmp example, gives us something like:
20735   //
20736   //         ucomiss %xmm1, %xmm0
20737   //         movss  <1.0f>, %xmm0
20738   //         jne     .LBB5_4
20739   //         jp      .LBB5_4
20740   //         xorps   %xmm0, %xmm0
20741   // .LBB5_4:
20742   //         retq
20743   //
20744   MachineInstr *CascadedCMOV = nullptr;
20745   MachineInstr *LastCMOV = MI;
20746   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20747   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20748   MachineBasicBlock::iterator NextMIIt =
20749       std::next(MachineBasicBlock::iterator(MI));
20750
20751   // Check for case 1, where there are multiple CMOVs with the same condition
20752   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
20753   // number of jumps the most.
20754
20755   if (isCMOVPseudo(MI)) {
20756     // See if we have a string of CMOVS with the same condition.
20757     while (NextMIIt != BB->end() &&
20758            isCMOVPseudo(NextMIIt) &&
20759            (NextMIIt->getOperand(3).getImm() == CC ||
20760             NextMIIt->getOperand(3).getImm() == OppCC)) {
20761       LastCMOV = &*NextMIIt;
20762       ++NextMIIt;
20763     }
20764   }
20765
20766   // This checks for case 2, but only do this if we didn't already find
20767   // case 1, as indicated by LastCMOV == MI.
20768   if (LastCMOV == MI &&
20769       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20770       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20771       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20772     CascadedCMOV = &*NextMIIt;
20773   }
20774
20775   MachineBasicBlock *jcc1MBB = nullptr;
20776
20777   // If we have a cascaded CMOV, we lower it to two successive branches to
20778   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20779   if (CascadedCMOV) {
20780     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20781     F->insert(It, jcc1MBB);
20782     jcc1MBB->addLiveIn(X86::EFLAGS);
20783   }
20784
20785   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20786   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20787   F->insert(It, copy0MBB);
20788   F->insert(It, sinkMBB);
20789
20790   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20791   // live into the sink and copy blocks.
20792   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20793
20794   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20795   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20796       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20797     copy0MBB->addLiveIn(X86::EFLAGS);
20798     sinkMBB->addLiveIn(X86::EFLAGS);
20799   }
20800
20801   // Transfer the remainder of BB and its successor edges to sinkMBB.
20802   sinkMBB->splice(sinkMBB->begin(), BB,
20803                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20804   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20805
20806   // Add the true and fallthrough blocks as its successors.
20807   if (CascadedCMOV) {
20808     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20809     BB->addSuccessor(jcc1MBB);
20810
20811     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20812     // jump to the sinkMBB.
20813     jcc1MBB->addSuccessor(copy0MBB);
20814     jcc1MBB->addSuccessor(sinkMBB);
20815   } else {
20816     BB->addSuccessor(copy0MBB);
20817   }
20818
20819   // The true block target of the first (or only) branch is always sinkMBB.
20820   BB->addSuccessor(sinkMBB);
20821
20822   // Create the conditional branch instruction.
20823   unsigned Opc = X86::GetCondBranchFromCond(CC);
20824   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20825
20826   if (CascadedCMOV) {
20827     unsigned Opc2 = X86::GetCondBranchFromCond(
20828         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20829     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20830   }
20831
20832   //  copy0MBB:
20833   //   %FalseValue = ...
20834   //   # fallthrough to sinkMBB
20835   copy0MBB->addSuccessor(sinkMBB);
20836
20837   //  sinkMBB:
20838   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20839   //  ...
20840   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20841   MachineBasicBlock::iterator MIItEnd =
20842     std::next(MachineBasicBlock::iterator(LastCMOV));
20843   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20844   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20845   MachineInstrBuilder MIB;
20846
20847   // As we are creating the PHIs, we have to be careful if there is more than
20848   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
20849   // PHIs have to reference the individual true/false inputs from earlier PHIs.
20850   // That also means that PHI construction must work forward from earlier to
20851   // later, and that the code must maintain a mapping from earlier PHI's
20852   // destination registers, and the registers that went into the PHI.
20853
20854   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20855     unsigned DestReg = MIIt->getOperand(0).getReg();
20856     unsigned Op1Reg = MIIt->getOperand(1).getReg();
20857     unsigned Op2Reg = MIIt->getOperand(2).getReg();
20858
20859     // If this CMOV we are generating is the opposite condition from
20860     // the jump we generated, then we have to swap the operands for the
20861     // PHI that is going to be generated.
20862     if (MIIt->getOperand(3).getImm() == OppCC)
20863         std::swap(Op1Reg, Op2Reg);
20864
20865     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20866       Op1Reg = RegRewriteTable[Op1Reg].first;
20867
20868     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20869       Op2Reg = RegRewriteTable[Op2Reg].second;
20870
20871     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20872                   TII->get(X86::PHI), DestReg)
20873           .addReg(Op1Reg).addMBB(copy0MBB)
20874           .addReg(Op2Reg).addMBB(thisMBB);
20875
20876     // Add this PHI to the rewrite table.
20877     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20878   }
20879
20880   // If we have a cascaded CMOV, the second Jcc provides the same incoming
20881   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20882   if (CascadedCMOV) {
20883     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20884     // Copy the PHI result to the register defined by the second CMOV.
20885     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20886             DL, TII->get(TargetOpcode::COPY),
20887             CascadedCMOV->getOperand(0).getReg())
20888         .addReg(MI->getOperand(0).getReg());
20889     CascadedCMOV->eraseFromParent();
20890   }
20891
20892   // Now remove the CMOV(s).
20893   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20894     (MIIt++)->eraseFromParent();
20895
20896   return sinkMBB;
20897 }
20898
20899 MachineBasicBlock *
20900 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20901                                        MachineBasicBlock *BB) const {
20902   // Combine the following atomic floating-point modification pattern:
20903   //   a.store(reg OP a.load(acquire), release)
20904   // Transform them into:
20905   //   OPss (%gpr), %xmm
20906   //   movss %xmm, (%gpr)
20907   // Or sd equivalent for 64-bit operations.
20908   unsigned MOp, FOp;
20909   switch (MI->getOpcode()) {
20910   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20911   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20912   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20913   }
20914   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20915   DebugLoc DL = MI->getDebugLoc();
20916   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20917   unsigned MSrc = MI->getOperand(0).getReg();
20918   unsigned VSrc = MI->getOperand(5).getReg();
20919   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20920                                 .addReg(/*Base=*/MSrc)
20921                                 .addImm(/*Scale=*/1)
20922                                 .addReg(/*Index=*/0)
20923                                 .addImm(0)
20924                                 .addReg(0);
20925   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20926                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20927                           .addReg(VSrc)
20928                           .addReg(/*Base=*/MSrc)
20929                           .addImm(/*Scale=*/1)
20930                           .addReg(/*Index=*/0)
20931                           .addImm(/*Disp=*/0)
20932                           .addReg(/*Segment=*/0);
20933   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20934   MI->eraseFromParent(); // The pseudo instruction is gone now.
20935   return BB;
20936 }
20937
20938 MachineBasicBlock *
20939 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20940                                         MachineBasicBlock *BB) const {
20941   MachineFunction *MF = BB->getParent();
20942   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20943   DebugLoc DL = MI->getDebugLoc();
20944   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20945
20946   assert(MF->shouldSplitStack());
20947
20948   const bool Is64Bit = Subtarget->is64Bit();
20949   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20950
20951   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20952   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20953
20954   // BB:
20955   //  ... [Till the alloca]
20956   // If stacklet is not large enough, jump to mallocMBB
20957   //
20958   // bumpMBB:
20959   //  Allocate by subtracting from RSP
20960   //  Jump to continueMBB
20961   //
20962   // mallocMBB:
20963   //  Allocate by call to runtime
20964   //
20965   // continueMBB:
20966   //  ...
20967   //  [rest of original BB]
20968   //
20969
20970   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20971   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20972   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20973
20974   MachineRegisterInfo &MRI = MF->getRegInfo();
20975   const TargetRegisterClass *AddrRegClass =
20976       getRegClassFor(getPointerTy(MF->getDataLayout()));
20977
20978   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20979     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20980     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20981     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20982     sizeVReg = MI->getOperand(1).getReg(),
20983     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20984
20985   MachineFunction::iterator MBBIter = BB;
20986   ++MBBIter;
20987
20988   MF->insert(MBBIter, bumpMBB);
20989   MF->insert(MBBIter, mallocMBB);
20990   MF->insert(MBBIter, continueMBB);
20991
20992   continueMBB->splice(continueMBB->begin(), BB,
20993                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20994   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20995
20996   // Add code to the main basic block to check if the stack limit has been hit,
20997   // and if so, jump to mallocMBB otherwise to bumpMBB.
20998   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20999   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
21000     .addReg(tmpSPVReg).addReg(sizeVReg);
21001   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
21002     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
21003     .addReg(SPLimitVReg);
21004   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
21005
21006   // bumpMBB simply decreases the stack pointer, since we know the current
21007   // stacklet has enough space.
21008   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
21009     .addReg(SPLimitVReg);
21010   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
21011     .addReg(SPLimitVReg);
21012   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21013
21014   // Calls into a routine in libgcc to allocate more space from the heap.
21015   const uint32_t *RegMask =
21016       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
21017   if (IsLP64) {
21018     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
21019       .addReg(sizeVReg);
21020     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21021       .addExternalSymbol("__morestack_allocate_stack_space")
21022       .addRegMask(RegMask)
21023       .addReg(X86::RDI, RegState::Implicit)
21024       .addReg(X86::RAX, RegState::ImplicitDefine);
21025   } else if (Is64Bit) {
21026     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
21027       .addReg(sizeVReg);
21028     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21029       .addExternalSymbol("__morestack_allocate_stack_space")
21030       .addRegMask(RegMask)
21031       .addReg(X86::EDI, RegState::Implicit)
21032       .addReg(X86::EAX, RegState::ImplicitDefine);
21033   } else {
21034     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
21035       .addImm(12);
21036     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
21037     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
21038       .addExternalSymbol("__morestack_allocate_stack_space")
21039       .addRegMask(RegMask)
21040       .addReg(X86::EAX, RegState::ImplicitDefine);
21041   }
21042
21043   if (!Is64Bit)
21044     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
21045       .addImm(16);
21046
21047   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
21048     .addReg(IsLP64 ? X86::RAX : X86::EAX);
21049   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21050
21051   // Set up the CFG correctly.
21052   BB->addSuccessor(bumpMBB);
21053   BB->addSuccessor(mallocMBB);
21054   mallocMBB->addSuccessor(continueMBB);
21055   bumpMBB->addSuccessor(continueMBB);
21056
21057   // Take care of the PHI nodes.
21058   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
21059           MI->getOperand(0).getReg())
21060     .addReg(mallocPtrVReg).addMBB(mallocMBB)
21061     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
21062
21063   // Delete the original pseudo instruction.
21064   MI->eraseFromParent();
21065
21066   // And we're done.
21067   return continueMBB;
21068 }
21069
21070 MachineBasicBlock *
21071 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
21072                                         MachineBasicBlock *BB) const {
21073   DebugLoc DL = MI->getDebugLoc();
21074
21075   assert(!Subtarget->isTargetMachO());
21076
21077   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
21078                                                     DL);
21079
21080   MI->eraseFromParent();   // The pseudo instruction is gone now.
21081   return BB;
21082 }
21083
21084 MachineBasicBlock *
21085 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
21086                                       MachineBasicBlock *BB) const {
21087   // This is pretty easy.  We're taking the value that we received from
21088   // our load from the relocation, sticking it in either RDI (x86-64)
21089   // or EAX and doing an indirect call.  The return value will then
21090   // be in the normal return register.
21091   MachineFunction *F = BB->getParent();
21092   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21093   DebugLoc DL = MI->getDebugLoc();
21094
21095   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
21096   assert(MI->getOperand(3).isGlobal() && "This should be a global");
21097
21098   // Get a register mask for the lowered call.
21099   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
21100   // proper register mask.
21101   const uint32_t *RegMask =
21102       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
21103   if (Subtarget->is64Bit()) {
21104     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21105                                       TII->get(X86::MOV64rm), X86::RDI)
21106     .addReg(X86::RIP)
21107     .addImm(0).addReg(0)
21108     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21109                       MI->getOperand(3).getTargetFlags())
21110     .addReg(0);
21111     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
21112     addDirectMem(MIB, X86::RDI);
21113     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
21114   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
21115     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21116                                       TII->get(X86::MOV32rm), X86::EAX)
21117     .addReg(0)
21118     .addImm(0).addReg(0)
21119     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21120                       MI->getOperand(3).getTargetFlags())
21121     .addReg(0);
21122     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21123     addDirectMem(MIB, X86::EAX);
21124     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21125   } else {
21126     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21127                                       TII->get(X86::MOV32rm), X86::EAX)
21128     .addReg(TII->getGlobalBaseReg(F))
21129     .addImm(0).addReg(0)
21130     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21131                       MI->getOperand(3).getTargetFlags())
21132     .addReg(0);
21133     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21134     addDirectMem(MIB, X86::EAX);
21135     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21136   }
21137
21138   MI->eraseFromParent(); // The pseudo instruction is gone now.
21139   return BB;
21140 }
21141
21142 MachineBasicBlock *
21143 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21144                                     MachineBasicBlock *MBB) const {
21145   DebugLoc DL = MI->getDebugLoc();
21146   MachineFunction *MF = MBB->getParent();
21147   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21148   MachineRegisterInfo &MRI = MF->getRegInfo();
21149
21150   const BasicBlock *BB = MBB->getBasicBlock();
21151   MachineFunction::iterator I = MBB;
21152   ++I;
21153
21154   // Memory Reference
21155   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21156   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21157
21158   unsigned DstReg;
21159   unsigned MemOpndSlot = 0;
21160
21161   unsigned CurOp = 0;
21162
21163   DstReg = MI->getOperand(CurOp++).getReg();
21164   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21165   assert(RC->hasType(MVT::i32) && "Invalid destination!");
21166   unsigned mainDstReg = MRI.createVirtualRegister(RC);
21167   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21168
21169   MemOpndSlot = CurOp;
21170
21171   MVT PVT = getPointerTy(MF->getDataLayout());
21172   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21173          "Invalid Pointer Size!");
21174
21175   // For v = setjmp(buf), we generate
21176   //
21177   // thisMBB:
21178   //  buf[LabelOffset] = restoreMBB
21179   //  SjLjSetup restoreMBB
21180   //
21181   // mainMBB:
21182   //  v_main = 0
21183   //
21184   // sinkMBB:
21185   //  v = phi(main, restore)
21186   //
21187   // restoreMBB:
21188   //  if base pointer being used, load it from frame
21189   //  v_restore = 1
21190
21191   MachineBasicBlock *thisMBB = MBB;
21192   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21193   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21194   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21195   MF->insert(I, mainMBB);
21196   MF->insert(I, sinkMBB);
21197   MF->push_back(restoreMBB);
21198
21199   MachineInstrBuilder MIB;
21200
21201   // Transfer the remainder of BB and its successor edges to sinkMBB.
21202   sinkMBB->splice(sinkMBB->begin(), MBB,
21203                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21204   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21205
21206   // thisMBB:
21207   unsigned PtrStoreOpc = 0;
21208   unsigned LabelReg = 0;
21209   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21210   Reloc::Model RM = MF->getTarget().getRelocationModel();
21211   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21212                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21213
21214   // Prepare IP either in reg or imm.
21215   if (!UseImmLabel) {
21216     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21217     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21218     LabelReg = MRI.createVirtualRegister(PtrRC);
21219     if (Subtarget->is64Bit()) {
21220       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21221               .addReg(X86::RIP)
21222               .addImm(0)
21223               .addReg(0)
21224               .addMBB(restoreMBB)
21225               .addReg(0);
21226     } else {
21227       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21228       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21229               .addReg(XII->getGlobalBaseReg(MF))
21230               .addImm(0)
21231               .addReg(0)
21232               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21233               .addReg(0);
21234     }
21235   } else
21236     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21237   // Store IP
21238   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21239   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21240     if (i == X86::AddrDisp)
21241       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21242     else
21243       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21244   }
21245   if (!UseImmLabel)
21246     MIB.addReg(LabelReg);
21247   else
21248     MIB.addMBB(restoreMBB);
21249   MIB.setMemRefs(MMOBegin, MMOEnd);
21250   // Setup
21251   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21252           .addMBB(restoreMBB);
21253
21254   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21255   MIB.addRegMask(RegInfo->getNoPreservedMask());
21256   thisMBB->addSuccessor(mainMBB);
21257   thisMBB->addSuccessor(restoreMBB);
21258
21259   // mainMBB:
21260   //  EAX = 0
21261   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21262   mainMBB->addSuccessor(sinkMBB);
21263
21264   // sinkMBB:
21265   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21266           TII->get(X86::PHI), DstReg)
21267     .addReg(mainDstReg).addMBB(mainMBB)
21268     .addReg(restoreDstReg).addMBB(restoreMBB);
21269
21270   // restoreMBB:
21271   if (RegInfo->hasBasePointer(*MF)) {
21272     const bool Uses64BitFramePtr =
21273         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21274     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21275     X86FI->setRestoreBasePointer(MF);
21276     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21277     unsigned BasePtr = RegInfo->getBaseRegister();
21278     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21279     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21280                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
21281       .setMIFlag(MachineInstr::FrameSetup);
21282   }
21283   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21284   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21285   restoreMBB->addSuccessor(sinkMBB);
21286
21287   MI->eraseFromParent();
21288   return sinkMBB;
21289 }
21290
21291 MachineBasicBlock *
21292 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21293                                      MachineBasicBlock *MBB) const {
21294   DebugLoc DL = MI->getDebugLoc();
21295   MachineFunction *MF = MBB->getParent();
21296   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21297   MachineRegisterInfo &MRI = MF->getRegInfo();
21298
21299   // Memory Reference
21300   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21301   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21302
21303   MVT PVT = getPointerTy(MF->getDataLayout());
21304   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21305          "Invalid Pointer Size!");
21306
21307   const TargetRegisterClass *RC =
21308     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21309   unsigned Tmp = MRI.createVirtualRegister(RC);
21310   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21311   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21312   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21313   unsigned SP = RegInfo->getStackRegister();
21314
21315   MachineInstrBuilder MIB;
21316
21317   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21318   const int64_t SPOffset = 2 * PVT.getStoreSize();
21319
21320   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21321   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21322
21323   // Reload FP
21324   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21325   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21326     MIB.addOperand(MI->getOperand(i));
21327   MIB.setMemRefs(MMOBegin, MMOEnd);
21328   // Reload IP
21329   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21330   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21331     if (i == X86::AddrDisp)
21332       MIB.addDisp(MI->getOperand(i), LabelOffset);
21333     else
21334       MIB.addOperand(MI->getOperand(i));
21335   }
21336   MIB.setMemRefs(MMOBegin, MMOEnd);
21337   // Reload SP
21338   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21339   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21340     if (i == X86::AddrDisp)
21341       MIB.addDisp(MI->getOperand(i), SPOffset);
21342     else
21343       MIB.addOperand(MI->getOperand(i));
21344   }
21345   MIB.setMemRefs(MMOBegin, MMOEnd);
21346   // Jump
21347   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21348
21349   MI->eraseFromParent();
21350   return MBB;
21351 }
21352
21353 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21354 // accumulator loops. Writing back to the accumulator allows the coalescer
21355 // to remove extra copies in the loop.
21356 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
21357 MachineBasicBlock *
21358 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21359                                  MachineBasicBlock *MBB) const {
21360   MachineOperand &AddendOp = MI->getOperand(3);
21361
21362   // Bail out early if the addend isn't a register - we can't switch these.
21363   if (!AddendOp.isReg())
21364     return MBB;
21365
21366   MachineFunction &MF = *MBB->getParent();
21367   MachineRegisterInfo &MRI = MF.getRegInfo();
21368
21369   // Check whether the addend is defined by a PHI:
21370   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21371   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21372   if (!AddendDef.isPHI())
21373     return MBB;
21374
21375   // Look for the following pattern:
21376   // loop:
21377   //   %addend = phi [%entry, 0], [%loop, %result]
21378   //   ...
21379   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21380
21381   // Replace with:
21382   //   loop:
21383   //   %addend = phi [%entry, 0], [%loop, %result]
21384   //   ...
21385   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21386
21387   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21388     assert(AddendDef.getOperand(i).isReg());
21389     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21390     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21391     if (&PHISrcInst == MI) {
21392       // Found a matching instruction.
21393       unsigned NewFMAOpc = 0;
21394       switch (MI->getOpcode()) {
21395         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21396         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21397         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21398         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21399         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21400         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21401         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21402         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21403         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21404         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21405         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21406         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21407         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21408         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21409         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21410         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21411         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21412         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21413         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21414         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21415
21416         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21417         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21418         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21419         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21420         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21421         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21422         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21423         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21424         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21425         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21426         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21427         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21428         default: llvm_unreachable("Unrecognized FMA variant.");
21429       }
21430
21431       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21432       MachineInstrBuilder MIB =
21433         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21434         .addOperand(MI->getOperand(0))
21435         .addOperand(MI->getOperand(3))
21436         .addOperand(MI->getOperand(2))
21437         .addOperand(MI->getOperand(1));
21438       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21439       MI->eraseFromParent();
21440     }
21441   }
21442
21443   return MBB;
21444 }
21445
21446 MachineBasicBlock *
21447 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21448                                                MachineBasicBlock *BB) const {
21449   switch (MI->getOpcode()) {
21450   default: llvm_unreachable("Unexpected instr type to insert");
21451   case X86::TAILJMPd64:
21452   case X86::TAILJMPr64:
21453   case X86::TAILJMPm64:
21454   case X86::TAILJMPd64_REX:
21455   case X86::TAILJMPr64_REX:
21456   case X86::TAILJMPm64_REX:
21457     llvm_unreachable("TAILJMP64 would not be touched here.");
21458   case X86::TCRETURNdi64:
21459   case X86::TCRETURNri64:
21460   case X86::TCRETURNmi64:
21461     return BB;
21462   case X86::WIN_ALLOCA:
21463     return EmitLoweredWinAlloca(MI, BB);
21464   case X86::SEG_ALLOCA_32:
21465   case X86::SEG_ALLOCA_64:
21466     return EmitLoweredSegAlloca(MI, BB);
21467   case X86::TLSCall_32:
21468   case X86::TLSCall_64:
21469     return EmitLoweredTLSCall(MI, BB);
21470   case X86::CMOV_FR32:
21471   case X86::CMOV_FR64:
21472   case X86::CMOV_GR8:
21473   case X86::CMOV_GR16:
21474   case X86::CMOV_GR32:
21475   case X86::CMOV_RFP32:
21476   case X86::CMOV_RFP64:
21477   case X86::CMOV_RFP80:
21478   case X86::CMOV_V2F64:
21479   case X86::CMOV_V2I64:
21480   case X86::CMOV_V4F32:
21481   case X86::CMOV_V4F64:
21482   case X86::CMOV_V4I64:
21483   case X86::CMOV_V16F32:
21484   case X86::CMOV_V8F32:
21485   case X86::CMOV_V8F64:
21486   case X86::CMOV_V8I64:
21487   case X86::CMOV_V8I1:
21488   case X86::CMOV_V16I1:
21489   case X86::CMOV_V32I1:
21490   case X86::CMOV_V64I1:
21491     return EmitLoweredSelect(MI, BB);
21492
21493   case X86::RELEASE_FADD32mr:
21494   case X86::RELEASE_FADD64mr:
21495     return EmitLoweredAtomicFP(MI, BB);
21496
21497   case X86::FP32_TO_INT16_IN_MEM:
21498   case X86::FP32_TO_INT32_IN_MEM:
21499   case X86::FP32_TO_INT64_IN_MEM:
21500   case X86::FP64_TO_INT16_IN_MEM:
21501   case X86::FP64_TO_INT32_IN_MEM:
21502   case X86::FP64_TO_INT64_IN_MEM:
21503   case X86::FP80_TO_INT16_IN_MEM:
21504   case X86::FP80_TO_INT32_IN_MEM:
21505   case X86::FP80_TO_INT64_IN_MEM: {
21506     MachineFunction *F = BB->getParent();
21507     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21508     DebugLoc DL = MI->getDebugLoc();
21509
21510     // Change the floating point control register to use "round towards zero"
21511     // mode when truncating to an integer value.
21512     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21513     addFrameReference(BuildMI(*BB, MI, DL,
21514                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21515
21516     // Load the old value of the high byte of the control word...
21517     unsigned OldCW =
21518       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21519     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21520                       CWFrameIdx);
21521
21522     // Set the high part to be round to zero...
21523     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21524       .addImm(0xC7F);
21525
21526     // Reload the modified control word now...
21527     addFrameReference(BuildMI(*BB, MI, DL,
21528                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21529
21530     // Restore the memory image of control word to original value
21531     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21532       .addReg(OldCW);
21533
21534     // Get the X86 opcode to use.
21535     unsigned Opc;
21536     switch (MI->getOpcode()) {
21537     default: llvm_unreachable("illegal opcode!");
21538     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21539     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21540     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21541     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21542     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21543     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21544     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21545     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21546     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21547     }
21548
21549     X86AddressMode AM;
21550     MachineOperand &Op = MI->getOperand(0);
21551     if (Op.isReg()) {
21552       AM.BaseType = X86AddressMode::RegBase;
21553       AM.Base.Reg = Op.getReg();
21554     } else {
21555       AM.BaseType = X86AddressMode::FrameIndexBase;
21556       AM.Base.FrameIndex = Op.getIndex();
21557     }
21558     Op = MI->getOperand(1);
21559     if (Op.isImm())
21560       AM.Scale = Op.getImm();
21561     Op = MI->getOperand(2);
21562     if (Op.isImm())
21563       AM.IndexReg = Op.getImm();
21564     Op = MI->getOperand(3);
21565     if (Op.isGlobal()) {
21566       AM.GV = Op.getGlobal();
21567     } else {
21568       AM.Disp = Op.getImm();
21569     }
21570     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21571                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21572
21573     // Reload the original control word now.
21574     addFrameReference(BuildMI(*BB, MI, DL,
21575                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21576
21577     MI->eraseFromParent();   // The pseudo instruction is gone now.
21578     return BB;
21579   }
21580     // String/text processing lowering.
21581   case X86::PCMPISTRM128REG:
21582   case X86::VPCMPISTRM128REG:
21583   case X86::PCMPISTRM128MEM:
21584   case X86::VPCMPISTRM128MEM:
21585   case X86::PCMPESTRM128REG:
21586   case X86::VPCMPESTRM128REG:
21587   case X86::PCMPESTRM128MEM:
21588   case X86::VPCMPESTRM128MEM:
21589     assert(Subtarget->hasSSE42() &&
21590            "Target must have SSE4.2 or AVX features enabled");
21591     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21592
21593   // String/text processing lowering.
21594   case X86::PCMPISTRIREG:
21595   case X86::VPCMPISTRIREG:
21596   case X86::PCMPISTRIMEM:
21597   case X86::VPCMPISTRIMEM:
21598   case X86::PCMPESTRIREG:
21599   case X86::VPCMPESTRIREG:
21600   case X86::PCMPESTRIMEM:
21601   case X86::VPCMPESTRIMEM:
21602     assert(Subtarget->hasSSE42() &&
21603            "Target must have SSE4.2 or AVX features enabled");
21604     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21605
21606   // Thread synchronization.
21607   case X86::MONITOR:
21608     return EmitMonitor(MI, BB, Subtarget);
21609
21610   // xbegin
21611   case X86::XBEGIN:
21612     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21613
21614   case X86::VASTART_SAVE_XMM_REGS:
21615     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21616
21617   case X86::VAARG_64:
21618     return EmitVAARG64WithCustomInserter(MI, BB);
21619
21620   case X86::EH_SjLj_SetJmp32:
21621   case X86::EH_SjLj_SetJmp64:
21622     return emitEHSjLjSetJmp(MI, BB);
21623
21624   case X86::EH_SjLj_LongJmp32:
21625   case X86::EH_SjLj_LongJmp64:
21626     return emitEHSjLjLongJmp(MI, BB);
21627
21628   case TargetOpcode::STATEPOINT:
21629     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21630     // this point in the process.  We diverge later.
21631     return emitPatchPoint(MI, BB);
21632
21633   case TargetOpcode::STACKMAP:
21634   case TargetOpcode::PATCHPOINT:
21635     return emitPatchPoint(MI, BB);
21636
21637   case X86::VFMADDPDr213r:
21638   case X86::VFMADDPSr213r:
21639   case X86::VFMADDSDr213r:
21640   case X86::VFMADDSSr213r:
21641   case X86::VFMSUBPDr213r:
21642   case X86::VFMSUBPSr213r:
21643   case X86::VFMSUBSDr213r:
21644   case X86::VFMSUBSSr213r:
21645   case X86::VFNMADDPDr213r:
21646   case X86::VFNMADDPSr213r:
21647   case X86::VFNMADDSDr213r:
21648   case X86::VFNMADDSSr213r:
21649   case X86::VFNMSUBPDr213r:
21650   case X86::VFNMSUBPSr213r:
21651   case X86::VFNMSUBSDr213r:
21652   case X86::VFNMSUBSSr213r:
21653   case X86::VFMADDSUBPDr213r:
21654   case X86::VFMADDSUBPSr213r:
21655   case X86::VFMSUBADDPDr213r:
21656   case X86::VFMSUBADDPSr213r:
21657   case X86::VFMADDPDr213rY:
21658   case X86::VFMADDPSr213rY:
21659   case X86::VFMSUBPDr213rY:
21660   case X86::VFMSUBPSr213rY:
21661   case X86::VFNMADDPDr213rY:
21662   case X86::VFNMADDPSr213rY:
21663   case X86::VFNMSUBPDr213rY:
21664   case X86::VFNMSUBPSr213rY:
21665   case X86::VFMADDSUBPDr213rY:
21666   case X86::VFMADDSUBPSr213rY:
21667   case X86::VFMSUBADDPDr213rY:
21668   case X86::VFMSUBADDPSr213rY:
21669     return emitFMA3Instr(MI, BB);
21670   }
21671 }
21672
21673 //===----------------------------------------------------------------------===//
21674 //                           X86 Optimization Hooks
21675 //===----------------------------------------------------------------------===//
21676
21677 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21678                                                       APInt &KnownZero,
21679                                                       APInt &KnownOne,
21680                                                       const SelectionDAG &DAG,
21681                                                       unsigned Depth) const {
21682   unsigned BitWidth = KnownZero.getBitWidth();
21683   unsigned Opc = Op.getOpcode();
21684   assert((Opc >= ISD::BUILTIN_OP_END ||
21685           Opc == ISD::INTRINSIC_WO_CHAIN ||
21686           Opc == ISD::INTRINSIC_W_CHAIN ||
21687           Opc == ISD::INTRINSIC_VOID) &&
21688          "Should use MaskedValueIsZero if you don't know whether Op"
21689          " is a target node!");
21690
21691   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21692   switch (Opc) {
21693   default: break;
21694   case X86ISD::ADD:
21695   case X86ISD::SUB:
21696   case X86ISD::ADC:
21697   case X86ISD::SBB:
21698   case X86ISD::SMUL:
21699   case X86ISD::UMUL:
21700   case X86ISD::INC:
21701   case X86ISD::DEC:
21702   case X86ISD::OR:
21703   case X86ISD::XOR:
21704   case X86ISD::AND:
21705     // These nodes' second result is a boolean.
21706     if (Op.getResNo() == 0)
21707       break;
21708     // Fallthrough
21709   case X86ISD::SETCC:
21710     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21711     break;
21712   case ISD::INTRINSIC_WO_CHAIN: {
21713     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21714     unsigned NumLoBits = 0;
21715     switch (IntId) {
21716     default: break;
21717     case Intrinsic::x86_sse_movmsk_ps:
21718     case Intrinsic::x86_avx_movmsk_ps_256:
21719     case Intrinsic::x86_sse2_movmsk_pd:
21720     case Intrinsic::x86_avx_movmsk_pd_256:
21721     case Intrinsic::x86_mmx_pmovmskb:
21722     case Intrinsic::x86_sse2_pmovmskb_128:
21723     case Intrinsic::x86_avx2_pmovmskb: {
21724       // High bits of movmskp{s|d}, pmovmskb are known zero.
21725       switch (IntId) {
21726         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21727         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21728         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21729         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21730         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21731         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21732         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21733         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21734       }
21735       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21736       break;
21737     }
21738     }
21739     break;
21740   }
21741   }
21742 }
21743
21744 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21745   SDValue Op,
21746   const SelectionDAG &,
21747   unsigned Depth) const {
21748   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21749   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21750     return Op.getValueType().getScalarType().getSizeInBits();
21751
21752   // Fallback case.
21753   return 1;
21754 }
21755
21756 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21757 /// node is a GlobalAddress + offset.
21758 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21759                                        const GlobalValue* &GA,
21760                                        int64_t &Offset) const {
21761   if (N->getOpcode() == X86ISD::Wrapper) {
21762     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21763       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21764       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21765       return true;
21766     }
21767   }
21768   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21769 }
21770
21771 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21772 /// same as extracting the high 128-bit part of 256-bit vector and then
21773 /// inserting the result into the low part of a new 256-bit vector
21774 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21775   EVT VT = SVOp->getValueType(0);
21776   unsigned NumElems = VT.getVectorNumElements();
21777
21778   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21779   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21780     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21781         SVOp->getMaskElt(j) >= 0)
21782       return false;
21783
21784   return true;
21785 }
21786
21787 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21788 /// same as extracting the low 128-bit part of 256-bit vector and then
21789 /// inserting the result into the high part of a new 256-bit vector
21790 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21791   EVT VT = SVOp->getValueType(0);
21792   unsigned NumElems = VT.getVectorNumElements();
21793
21794   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21795   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21796     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21797         SVOp->getMaskElt(j) >= 0)
21798       return false;
21799
21800   return true;
21801 }
21802
21803 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21804 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21805                                         TargetLowering::DAGCombinerInfo &DCI,
21806                                         const X86Subtarget* Subtarget) {
21807   SDLoc dl(N);
21808   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21809   SDValue V1 = SVOp->getOperand(0);
21810   SDValue V2 = SVOp->getOperand(1);
21811   EVT VT = SVOp->getValueType(0);
21812   unsigned NumElems = VT.getVectorNumElements();
21813
21814   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21815       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21816     //
21817     //                   0,0,0,...
21818     //                      |
21819     //    V      UNDEF    BUILD_VECTOR    UNDEF
21820     //     \      /           \           /
21821     //  CONCAT_VECTOR         CONCAT_VECTOR
21822     //         \                  /
21823     //          \                /
21824     //          RESULT: V + zero extended
21825     //
21826     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21827         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21828         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21829       return SDValue();
21830
21831     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21832       return SDValue();
21833
21834     // To match the shuffle mask, the first half of the mask should
21835     // be exactly the first vector, and all the rest a splat with the
21836     // first element of the second one.
21837     for (unsigned i = 0; i != NumElems/2; ++i)
21838       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21839           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21840         return SDValue();
21841
21842     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21843     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21844       if (Ld->hasNUsesOfValue(1, 0)) {
21845         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21846         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21847         SDValue ResNode =
21848           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21849                                   Ld->getMemoryVT(),
21850                                   Ld->getPointerInfo(),
21851                                   Ld->getAlignment(),
21852                                   false/*isVolatile*/, true/*ReadMem*/,
21853                                   false/*WriteMem*/);
21854
21855         // Make sure the newly-created LOAD is in the same position as Ld in
21856         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21857         // and update uses of Ld's output chain to use the TokenFactor.
21858         if (Ld->hasAnyUseOfValue(1)) {
21859           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21860                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21861           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21862           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21863                                  SDValue(ResNode.getNode(), 1));
21864         }
21865
21866         return DAG.getBitcast(VT, ResNode);
21867       }
21868     }
21869
21870     // Emit a zeroed vector and insert the desired subvector on its
21871     // first half.
21872     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21873     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21874     return DCI.CombineTo(N, InsV);
21875   }
21876
21877   //===--------------------------------------------------------------------===//
21878   // Combine some shuffles into subvector extracts and inserts:
21879   //
21880
21881   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21882   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21883     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21884     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21885     return DCI.CombineTo(N, InsV);
21886   }
21887
21888   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21889   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21890     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21891     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21892     return DCI.CombineTo(N, InsV);
21893   }
21894
21895   return SDValue();
21896 }
21897
21898 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21899 /// possible.
21900 ///
21901 /// This is the leaf of the recursive combinine below. When we have found some
21902 /// chain of single-use x86 shuffle instructions and accumulated the combined
21903 /// shuffle mask represented by them, this will try to pattern match that mask
21904 /// into either a single instruction if there is a special purpose instruction
21905 /// for this operation, or into a PSHUFB instruction which is a fully general
21906 /// instruction but should only be used to replace chains over a certain depth.
21907 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21908                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21909                                    TargetLowering::DAGCombinerInfo &DCI,
21910                                    const X86Subtarget *Subtarget) {
21911   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21912
21913   // Find the operand that enters the chain. Note that multiple uses are OK
21914   // here, we're not going to remove the operand we find.
21915   SDValue Input = Op.getOperand(0);
21916   while (Input.getOpcode() == ISD::BITCAST)
21917     Input = Input.getOperand(0);
21918
21919   MVT VT = Input.getSimpleValueType();
21920   MVT RootVT = Root.getSimpleValueType();
21921   SDLoc DL(Root);
21922
21923   // Just remove no-op shuffle masks.
21924   if (Mask.size() == 1) {
21925     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21926                   /*AddTo*/ true);
21927     return true;
21928   }
21929
21930   // Use the float domain if the operand type is a floating point type.
21931   bool FloatDomain = VT.isFloatingPoint();
21932
21933   // For floating point shuffles, we don't have free copies in the shuffle
21934   // instructions or the ability to load as part of the instruction, so
21935   // canonicalize their shuffles to UNPCK or MOV variants.
21936   //
21937   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21938   // vectors because it can have a load folded into it that UNPCK cannot. This
21939   // doesn't preclude something switching to the shorter encoding post-RA.
21940   //
21941   // FIXME: Should teach these routines about AVX vector widths.
21942   if (FloatDomain && VT.getSizeInBits() == 128) {
21943     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21944       bool Lo = Mask.equals({0, 0});
21945       unsigned Shuffle;
21946       MVT ShuffleVT;
21947       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21948       // is no slower than UNPCKLPD but has the option to fold the input operand
21949       // into even an unaligned memory load.
21950       if (Lo && Subtarget->hasSSE3()) {
21951         Shuffle = X86ISD::MOVDDUP;
21952         ShuffleVT = MVT::v2f64;
21953       } else {
21954         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21955         // than the UNPCK variants.
21956         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21957         ShuffleVT = MVT::v4f32;
21958       }
21959       if (Depth == 1 && Root->getOpcode() == Shuffle)
21960         return false; // Nothing to do!
21961       Op = DAG.getBitcast(ShuffleVT, Input);
21962       DCI.AddToWorklist(Op.getNode());
21963       if (Shuffle == X86ISD::MOVDDUP)
21964         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21965       else
21966         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21967       DCI.AddToWorklist(Op.getNode());
21968       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21969                     /*AddTo*/ true);
21970       return true;
21971     }
21972     if (Subtarget->hasSSE3() &&
21973         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21974       bool Lo = Mask.equals({0, 0, 2, 2});
21975       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21976       MVT ShuffleVT = MVT::v4f32;
21977       if (Depth == 1 && Root->getOpcode() == Shuffle)
21978         return false; // Nothing to do!
21979       Op = DAG.getBitcast(ShuffleVT, Input);
21980       DCI.AddToWorklist(Op.getNode());
21981       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21982       DCI.AddToWorklist(Op.getNode());
21983       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21984                     /*AddTo*/ true);
21985       return true;
21986     }
21987     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21988       bool Lo = Mask.equals({0, 0, 1, 1});
21989       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21990       MVT ShuffleVT = MVT::v4f32;
21991       if (Depth == 1 && Root->getOpcode() == Shuffle)
21992         return false; // Nothing to do!
21993       Op = DAG.getBitcast(ShuffleVT, Input);
21994       DCI.AddToWorklist(Op.getNode());
21995       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21996       DCI.AddToWorklist(Op.getNode());
21997       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21998                     /*AddTo*/ true);
21999       return true;
22000     }
22001   }
22002
22003   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
22004   // variants as none of these have single-instruction variants that are
22005   // superior to the UNPCK formulation.
22006   if (!FloatDomain && VT.getSizeInBits() == 128 &&
22007       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22008        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
22009        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
22010        Mask.equals(
22011            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
22012     bool Lo = Mask[0] == 0;
22013     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22014     if (Depth == 1 && Root->getOpcode() == Shuffle)
22015       return false; // Nothing to do!
22016     MVT ShuffleVT;
22017     switch (Mask.size()) {
22018     case 8:
22019       ShuffleVT = MVT::v8i16;
22020       break;
22021     case 16:
22022       ShuffleVT = MVT::v16i8;
22023       break;
22024     default:
22025       llvm_unreachable("Impossible mask size!");
22026     };
22027     Op = DAG.getBitcast(ShuffleVT, Input);
22028     DCI.AddToWorklist(Op.getNode());
22029     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22030     DCI.AddToWorklist(Op.getNode());
22031     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22032                   /*AddTo*/ true);
22033     return true;
22034   }
22035
22036   // Don't try to re-form single instruction chains under any circumstances now
22037   // that we've done encoding canonicalization for them.
22038   if (Depth < 2)
22039     return false;
22040
22041   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
22042   // can replace them with a single PSHUFB instruction profitably. Intel's
22043   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
22044   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
22045   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
22046     SmallVector<SDValue, 16> PSHUFBMask;
22047     int NumBytes = VT.getSizeInBits() / 8;
22048     int Ratio = NumBytes / Mask.size();
22049     for (int i = 0; i < NumBytes; ++i) {
22050       if (Mask[i / Ratio] == SM_SentinelUndef) {
22051         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
22052         continue;
22053       }
22054       int M = Mask[i / Ratio] != SM_SentinelZero
22055                   ? Ratio * Mask[i / Ratio] + i % Ratio
22056                   : 255;
22057       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
22058     }
22059     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
22060     Op = DAG.getBitcast(ByteVT, Input);
22061     DCI.AddToWorklist(Op.getNode());
22062     SDValue PSHUFBMaskOp =
22063         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
22064     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
22065     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
22066     DCI.AddToWorklist(Op.getNode());
22067     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22068                   /*AddTo*/ true);
22069     return true;
22070   }
22071
22072   // Failed to find any combines.
22073   return false;
22074 }
22075
22076 /// \brief Fully generic combining of x86 shuffle instructions.
22077 ///
22078 /// This should be the last combine run over the x86 shuffle instructions. Once
22079 /// they have been fully optimized, this will recursively consider all chains
22080 /// of single-use shuffle instructions, build a generic model of the cumulative
22081 /// shuffle operation, and check for simpler instructions which implement this
22082 /// operation. We use this primarily for two purposes:
22083 ///
22084 /// 1) Collapse generic shuffles to specialized single instructions when
22085 ///    equivalent. In most cases, this is just an encoding size win, but
22086 ///    sometimes we will collapse multiple generic shuffles into a single
22087 ///    special-purpose shuffle.
22088 /// 2) Look for sequences of shuffle instructions with 3 or more total
22089 ///    instructions, and replace them with the slightly more expensive SSSE3
22090 ///    PSHUFB instruction if available. We do this as the last combining step
22091 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
22092 ///    a suitable short sequence of other instructions. The PHUFB will either
22093 ///    use a register or have to read from memory and so is slightly (but only
22094 ///    slightly) more expensive than the other shuffle instructions.
22095 ///
22096 /// Because this is inherently a quadratic operation (for each shuffle in
22097 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
22098 /// This should never be an issue in practice as the shuffle lowering doesn't
22099 /// produce sequences of more than 8 instructions.
22100 ///
22101 /// FIXME: We will currently miss some cases where the redundant shuffling
22102 /// would simplify under the threshold for PSHUFB formation because of
22103 /// combine-ordering. To fix this, we should do the redundant instruction
22104 /// combining in this recursive walk.
22105 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
22106                                           ArrayRef<int> RootMask,
22107                                           int Depth, bool HasPSHUFB,
22108                                           SelectionDAG &DAG,
22109                                           TargetLowering::DAGCombinerInfo &DCI,
22110                                           const X86Subtarget *Subtarget) {
22111   // Bound the depth of our recursive combine because this is ultimately
22112   // quadratic in nature.
22113   if (Depth > 8)
22114     return false;
22115
22116   // Directly rip through bitcasts to find the underlying operand.
22117   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
22118     Op = Op.getOperand(0);
22119
22120   MVT VT = Op.getSimpleValueType();
22121   if (!VT.isVector())
22122     return false; // Bail if we hit a non-vector.
22123
22124   assert(Root.getSimpleValueType().isVector() &&
22125          "Shuffles operate on vector types!");
22126   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
22127          "Can only combine shuffles of the same vector register size.");
22128
22129   if (!isTargetShuffle(Op.getOpcode()))
22130     return false;
22131   SmallVector<int, 16> OpMask;
22132   bool IsUnary;
22133   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
22134   // We only can combine unary shuffles which we can decode the mask for.
22135   if (!HaveMask || !IsUnary)
22136     return false;
22137
22138   assert(VT.getVectorNumElements() == OpMask.size() &&
22139          "Different mask size from vector size!");
22140   assert(((RootMask.size() > OpMask.size() &&
22141            RootMask.size() % OpMask.size() == 0) ||
22142           (OpMask.size() > RootMask.size() &&
22143            OpMask.size() % RootMask.size() == 0) ||
22144           OpMask.size() == RootMask.size()) &&
22145          "The smaller number of elements must divide the larger.");
22146   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22147   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22148   assert(((RootRatio == 1 && OpRatio == 1) ||
22149           (RootRatio == 1) != (OpRatio == 1)) &&
22150          "Must not have a ratio for both incoming and op masks!");
22151
22152   SmallVector<int, 16> Mask;
22153   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22154
22155   // Merge this shuffle operation's mask into our accumulated mask. Note that
22156   // this shuffle's mask will be the first applied to the input, followed by the
22157   // root mask to get us all the way to the root value arrangement. The reason
22158   // for this order is that we are recursing up the operation chain.
22159   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22160     int RootIdx = i / RootRatio;
22161     if (RootMask[RootIdx] < 0) {
22162       // This is a zero or undef lane, we're done.
22163       Mask.push_back(RootMask[RootIdx]);
22164       continue;
22165     }
22166
22167     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22168     int OpIdx = RootMaskedIdx / OpRatio;
22169     if (OpMask[OpIdx] < 0) {
22170       // The incoming lanes are zero or undef, it doesn't matter which ones we
22171       // are using.
22172       Mask.push_back(OpMask[OpIdx]);
22173       continue;
22174     }
22175
22176     // Ok, we have non-zero lanes, map them through.
22177     Mask.push_back(OpMask[OpIdx] * OpRatio +
22178                    RootMaskedIdx % OpRatio);
22179   }
22180
22181   // See if we can recurse into the operand to combine more things.
22182   switch (Op.getOpcode()) {
22183     case X86ISD::PSHUFB:
22184       HasPSHUFB = true;
22185     case X86ISD::PSHUFD:
22186     case X86ISD::PSHUFHW:
22187     case X86ISD::PSHUFLW:
22188       if (Op.getOperand(0).hasOneUse() &&
22189           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22190                                         HasPSHUFB, DAG, DCI, Subtarget))
22191         return true;
22192       break;
22193
22194     case X86ISD::UNPCKL:
22195     case X86ISD::UNPCKH:
22196       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
22197       // We can't check for single use, we have to check that this shuffle is the only user.
22198       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22199           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22200                                         HasPSHUFB, DAG, DCI, Subtarget))
22201           return true;
22202       break;
22203   }
22204
22205   // Minor canonicalization of the accumulated shuffle mask to make it easier
22206   // to match below. All this does is detect masks with squential pairs of
22207   // elements, and shrink them to the half-width mask. It does this in a loop
22208   // so it will reduce the size of the mask to the minimal width mask which
22209   // performs an equivalent shuffle.
22210   SmallVector<int, 16> WidenedMask;
22211   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22212     Mask = std::move(WidenedMask);
22213     WidenedMask.clear();
22214   }
22215
22216   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22217                                 Subtarget);
22218 }
22219
22220 /// \brief Get the PSHUF-style mask from PSHUF node.
22221 ///
22222 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22223 /// PSHUF-style masks that can be reused with such instructions.
22224 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22225   MVT VT = N.getSimpleValueType();
22226   SmallVector<int, 4> Mask;
22227   bool IsUnary;
22228   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22229   (void)HaveMask;
22230   assert(HaveMask);
22231
22232   // If we have more than 128-bits, only the low 128-bits of shuffle mask
22233   // matter. Check that the upper masks are repeats and remove them.
22234   if (VT.getSizeInBits() > 128) {
22235     int LaneElts = 128 / VT.getScalarSizeInBits();
22236 #ifndef NDEBUG
22237     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22238       for (int j = 0; j < LaneElts; ++j)
22239         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22240                "Mask doesn't repeat in high 128-bit lanes!");
22241 #endif
22242     Mask.resize(LaneElts);
22243   }
22244
22245   switch (N.getOpcode()) {
22246   case X86ISD::PSHUFD:
22247     return Mask;
22248   case X86ISD::PSHUFLW:
22249     Mask.resize(4);
22250     return Mask;
22251   case X86ISD::PSHUFHW:
22252     Mask.erase(Mask.begin(), Mask.begin() + 4);
22253     for (int &M : Mask)
22254       M -= 4;
22255     return Mask;
22256   default:
22257     llvm_unreachable("No valid shuffle instruction found!");
22258   }
22259 }
22260
22261 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22262 ///
22263 /// We walk up the chain and look for a combinable shuffle, skipping over
22264 /// shuffles that we could hoist this shuffle's transformation past without
22265 /// altering anything.
22266 static SDValue
22267 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22268                              SelectionDAG &DAG,
22269                              TargetLowering::DAGCombinerInfo &DCI) {
22270   assert(N.getOpcode() == X86ISD::PSHUFD &&
22271          "Called with something other than an x86 128-bit half shuffle!");
22272   SDLoc DL(N);
22273
22274   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22275   // of the shuffles in the chain so that we can form a fresh chain to replace
22276   // this one.
22277   SmallVector<SDValue, 8> Chain;
22278   SDValue V = N.getOperand(0);
22279   for (; V.hasOneUse(); V = V.getOperand(0)) {
22280     switch (V.getOpcode()) {
22281     default:
22282       return SDValue(); // Nothing combined!
22283
22284     case ISD::BITCAST:
22285       // Skip bitcasts as we always know the type for the target specific
22286       // instructions.
22287       continue;
22288
22289     case X86ISD::PSHUFD:
22290       // Found another dword shuffle.
22291       break;
22292
22293     case X86ISD::PSHUFLW:
22294       // Check that the low words (being shuffled) are the identity in the
22295       // dword shuffle, and the high words are self-contained.
22296       if (Mask[0] != 0 || Mask[1] != 1 ||
22297           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22298         return SDValue();
22299
22300       Chain.push_back(V);
22301       continue;
22302
22303     case X86ISD::PSHUFHW:
22304       // Check that the high words (being shuffled) are the identity in the
22305       // dword shuffle, and the low words are self-contained.
22306       if (Mask[2] != 2 || Mask[3] != 3 ||
22307           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22308         return SDValue();
22309
22310       Chain.push_back(V);
22311       continue;
22312
22313     case X86ISD::UNPCKL:
22314     case X86ISD::UNPCKH:
22315       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22316       // shuffle into a preceding word shuffle.
22317       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
22318           V.getSimpleValueType().getScalarType() != MVT::i16)
22319         return SDValue();
22320
22321       // Search for a half-shuffle which we can combine with.
22322       unsigned CombineOp =
22323           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22324       if (V.getOperand(0) != V.getOperand(1) ||
22325           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22326         return SDValue();
22327       Chain.push_back(V);
22328       V = V.getOperand(0);
22329       do {
22330         switch (V.getOpcode()) {
22331         default:
22332           return SDValue(); // Nothing to combine.
22333
22334         case X86ISD::PSHUFLW:
22335         case X86ISD::PSHUFHW:
22336           if (V.getOpcode() == CombineOp)
22337             break;
22338
22339           Chain.push_back(V);
22340
22341           // Fallthrough!
22342         case ISD::BITCAST:
22343           V = V.getOperand(0);
22344           continue;
22345         }
22346         break;
22347       } while (V.hasOneUse());
22348       break;
22349     }
22350     // Break out of the loop if we break out of the switch.
22351     break;
22352   }
22353
22354   if (!V.hasOneUse())
22355     // We fell out of the loop without finding a viable combining instruction.
22356     return SDValue();
22357
22358   // Merge this node's mask and our incoming mask.
22359   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22360   for (int &M : Mask)
22361     M = VMask[M];
22362   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22363                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22364
22365   // Rebuild the chain around this new shuffle.
22366   while (!Chain.empty()) {
22367     SDValue W = Chain.pop_back_val();
22368
22369     if (V.getValueType() != W.getOperand(0).getValueType())
22370       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
22371
22372     switch (W.getOpcode()) {
22373     default:
22374       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22375
22376     case X86ISD::UNPCKL:
22377     case X86ISD::UNPCKH:
22378       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22379       break;
22380
22381     case X86ISD::PSHUFD:
22382     case X86ISD::PSHUFLW:
22383     case X86ISD::PSHUFHW:
22384       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22385       break;
22386     }
22387   }
22388   if (V.getValueType() != N.getValueType())
22389     V = DAG.getBitcast(N.getValueType(), V);
22390
22391   // Return the new chain to replace N.
22392   return V;
22393 }
22394
22395 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
22396 ///
22397 /// We walk up the chain, skipping shuffles of the other half and looking
22398 /// through shuffles which switch halves trying to find a shuffle of the same
22399 /// pair of dwords.
22400 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22401                                         SelectionDAG &DAG,
22402                                         TargetLowering::DAGCombinerInfo &DCI) {
22403   assert(
22404       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22405       "Called with something other than an x86 128-bit half shuffle!");
22406   SDLoc DL(N);
22407   unsigned CombineOpcode = N.getOpcode();
22408
22409   // Walk up a single-use chain looking for a combinable shuffle.
22410   SDValue V = N.getOperand(0);
22411   for (; V.hasOneUse(); V = V.getOperand(0)) {
22412     switch (V.getOpcode()) {
22413     default:
22414       return false; // Nothing combined!
22415
22416     case ISD::BITCAST:
22417       // Skip bitcasts as we always know the type for the target specific
22418       // instructions.
22419       continue;
22420
22421     case X86ISD::PSHUFLW:
22422     case X86ISD::PSHUFHW:
22423       if (V.getOpcode() == CombineOpcode)
22424         break;
22425
22426       // Other-half shuffles are no-ops.
22427       continue;
22428     }
22429     // Break out of the loop if we break out of the switch.
22430     break;
22431   }
22432
22433   if (!V.hasOneUse())
22434     // We fell out of the loop without finding a viable combining instruction.
22435     return false;
22436
22437   // Combine away the bottom node as its shuffle will be accumulated into
22438   // a preceding shuffle.
22439   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22440
22441   // Record the old value.
22442   SDValue Old = V;
22443
22444   // Merge this node's mask and our incoming mask (adjusted to account for all
22445   // the pshufd instructions encountered).
22446   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22447   for (int &M : Mask)
22448     M = VMask[M];
22449   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22450                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22451
22452   // Check that the shuffles didn't cancel each other out. If not, we need to
22453   // combine to the new one.
22454   if (Old != V)
22455     // Replace the combinable shuffle with the combined one, updating all users
22456     // so that we re-evaluate the chain here.
22457     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22458
22459   return true;
22460 }
22461
22462 /// \brief Try to combine x86 target specific shuffles.
22463 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22464                                            TargetLowering::DAGCombinerInfo &DCI,
22465                                            const X86Subtarget *Subtarget) {
22466   SDLoc DL(N);
22467   MVT VT = N.getSimpleValueType();
22468   SmallVector<int, 4> Mask;
22469
22470   switch (N.getOpcode()) {
22471   case X86ISD::PSHUFD:
22472   case X86ISD::PSHUFLW:
22473   case X86ISD::PSHUFHW:
22474     Mask = getPSHUFShuffleMask(N);
22475     assert(Mask.size() == 4);
22476     break;
22477   default:
22478     return SDValue();
22479   }
22480
22481   // Nuke no-op shuffles that show up after combining.
22482   if (isNoopShuffleMask(Mask))
22483     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22484
22485   // Look for simplifications involving one or two shuffle instructions.
22486   SDValue V = N.getOperand(0);
22487   switch (N.getOpcode()) {
22488   default:
22489     break;
22490   case X86ISD::PSHUFLW:
22491   case X86ISD::PSHUFHW:
22492     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22493
22494     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22495       return SDValue(); // We combined away this shuffle, so we're done.
22496
22497     // See if this reduces to a PSHUFD which is no more expensive and can
22498     // combine with more operations. Note that it has to at least flip the
22499     // dwords as otherwise it would have been removed as a no-op.
22500     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22501       int DMask[] = {0, 1, 2, 3};
22502       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22503       DMask[DOffset + 0] = DOffset + 1;
22504       DMask[DOffset + 1] = DOffset + 0;
22505       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22506       V = DAG.getBitcast(DVT, V);
22507       DCI.AddToWorklist(V.getNode());
22508       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22509                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22510       DCI.AddToWorklist(V.getNode());
22511       return DAG.getBitcast(VT, V);
22512     }
22513
22514     // Look for shuffle patterns which can be implemented as a single unpack.
22515     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22516     // only works when we have a PSHUFD followed by two half-shuffles.
22517     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22518         (V.getOpcode() == X86ISD::PSHUFLW ||
22519          V.getOpcode() == X86ISD::PSHUFHW) &&
22520         V.getOpcode() != N.getOpcode() &&
22521         V.hasOneUse()) {
22522       SDValue D = V.getOperand(0);
22523       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22524         D = D.getOperand(0);
22525       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22526         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22527         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22528         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22529         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22530         int WordMask[8];
22531         for (int i = 0; i < 4; ++i) {
22532           WordMask[i + NOffset] = Mask[i] + NOffset;
22533           WordMask[i + VOffset] = VMask[i] + VOffset;
22534         }
22535         // Map the word mask through the DWord mask.
22536         int MappedMask[8];
22537         for (int i = 0; i < 8; ++i)
22538           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22539         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22540             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22541           // We can replace all three shuffles with an unpack.
22542           V = DAG.getBitcast(VT, D.getOperand(0));
22543           DCI.AddToWorklist(V.getNode());
22544           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22545                                                 : X86ISD::UNPCKH,
22546                              DL, VT, V, V);
22547         }
22548       }
22549     }
22550
22551     break;
22552
22553   case X86ISD::PSHUFD:
22554     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22555       return NewN;
22556
22557     break;
22558   }
22559
22560   return SDValue();
22561 }
22562
22563 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22564 ///
22565 /// We combine this directly on the abstract vector shuffle nodes so it is
22566 /// easier to generically match. We also insert dummy vector shuffle nodes for
22567 /// the operands which explicitly discard the lanes which are unused by this
22568 /// operation to try to flow through the rest of the combiner the fact that
22569 /// they're unused.
22570 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22571   SDLoc DL(N);
22572   EVT VT = N->getValueType(0);
22573
22574   // We only handle target-independent shuffles.
22575   // FIXME: It would be easy and harmless to use the target shuffle mask
22576   // extraction tool to support more.
22577   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22578     return SDValue();
22579
22580   auto *SVN = cast<ShuffleVectorSDNode>(N);
22581   ArrayRef<int> Mask = SVN->getMask();
22582   SDValue V1 = N->getOperand(0);
22583   SDValue V2 = N->getOperand(1);
22584
22585   // We require the first shuffle operand to be the SUB node, and the second to
22586   // be the ADD node.
22587   // FIXME: We should support the commuted patterns.
22588   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22589     return SDValue();
22590
22591   // If there are other uses of these operations we can't fold them.
22592   if (!V1->hasOneUse() || !V2->hasOneUse())
22593     return SDValue();
22594
22595   // Ensure that both operations have the same operands. Note that we can
22596   // commute the FADD operands.
22597   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22598   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22599       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22600     return SDValue();
22601
22602   // We're looking for blends between FADD and FSUB nodes. We insist on these
22603   // nodes being lined up in a specific expected pattern.
22604   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22605         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22606         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22607     return SDValue();
22608
22609   // Only specific types are legal at this point, assert so we notice if and
22610   // when these change.
22611   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22612           VT == MVT::v4f64) &&
22613          "Unknown vector type encountered!");
22614
22615   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22616 }
22617
22618 /// PerformShuffleCombine - Performs several different shuffle combines.
22619 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22620                                      TargetLowering::DAGCombinerInfo &DCI,
22621                                      const X86Subtarget *Subtarget) {
22622   SDLoc dl(N);
22623   SDValue N0 = N->getOperand(0);
22624   SDValue N1 = N->getOperand(1);
22625   EVT VT = N->getValueType(0);
22626
22627   // Don't create instructions with illegal types after legalize types has run.
22628   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22629   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22630     return SDValue();
22631
22632   // If we have legalized the vector types, look for blends of FADD and FSUB
22633   // nodes that we can fuse into an ADDSUB node.
22634   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22635     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22636       return AddSub;
22637
22638   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22639   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22640       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22641     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22642
22643   // During Type Legalization, when promoting illegal vector types,
22644   // the backend might introduce new shuffle dag nodes and bitcasts.
22645   //
22646   // This code performs the following transformation:
22647   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22648   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22649   //
22650   // We do this only if both the bitcast and the BINOP dag nodes have
22651   // one use. Also, perform this transformation only if the new binary
22652   // operation is legal. This is to avoid introducing dag nodes that
22653   // potentially need to be further expanded (or custom lowered) into a
22654   // less optimal sequence of dag nodes.
22655   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22656       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22657       N0.getOpcode() == ISD::BITCAST) {
22658     SDValue BC0 = N0.getOperand(0);
22659     EVT SVT = BC0.getValueType();
22660     unsigned Opcode = BC0.getOpcode();
22661     unsigned NumElts = VT.getVectorNumElements();
22662
22663     if (BC0.hasOneUse() && SVT.isVector() &&
22664         SVT.getVectorNumElements() * 2 == NumElts &&
22665         TLI.isOperationLegal(Opcode, VT)) {
22666       bool CanFold = false;
22667       switch (Opcode) {
22668       default : break;
22669       case ISD::ADD :
22670       case ISD::FADD :
22671       case ISD::SUB :
22672       case ISD::FSUB :
22673       case ISD::MUL :
22674       case ISD::FMUL :
22675         CanFold = true;
22676       }
22677
22678       unsigned SVTNumElts = SVT.getVectorNumElements();
22679       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22680       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22681         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22682       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22683         CanFold = SVOp->getMaskElt(i) < 0;
22684
22685       if (CanFold) {
22686         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22687         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22688         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22689         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22690       }
22691     }
22692   }
22693
22694   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22695   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22696   // consecutive, non-overlapping, and in the right order.
22697   SmallVector<SDValue, 16> Elts;
22698   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22699     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22700
22701   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22702     return LD;
22703
22704   if (isTargetShuffle(N->getOpcode())) {
22705     SDValue Shuffle =
22706         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22707     if (Shuffle.getNode())
22708       return Shuffle;
22709
22710     // Try recursively combining arbitrary sequences of x86 shuffle
22711     // instructions into higher-order shuffles. We do this after combining
22712     // specific PSHUF instruction sequences into their minimal form so that we
22713     // can evaluate how many specialized shuffle instructions are involved in
22714     // a particular chain.
22715     SmallVector<int, 1> NonceMask; // Just a placeholder.
22716     NonceMask.push_back(0);
22717     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22718                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22719                                       DCI, Subtarget))
22720       return SDValue(); // This routine will use CombineTo to replace N.
22721   }
22722
22723   return SDValue();
22724 }
22725
22726 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22727 /// specific shuffle of a load can be folded into a single element load.
22728 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22729 /// shuffles have been custom lowered so we need to handle those here.
22730 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22731                                          TargetLowering::DAGCombinerInfo &DCI) {
22732   if (DCI.isBeforeLegalizeOps())
22733     return SDValue();
22734
22735   SDValue InVec = N->getOperand(0);
22736   SDValue EltNo = N->getOperand(1);
22737
22738   if (!isa<ConstantSDNode>(EltNo))
22739     return SDValue();
22740
22741   EVT OriginalVT = InVec.getValueType();
22742
22743   if (InVec.getOpcode() == ISD::BITCAST) {
22744     // Don't duplicate a load with other uses.
22745     if (!InVec.hasOneUse())
22746       return SDValue();
22747     EVT BCVT = InVec.getOperand(0).getValueType();
22748     if (!BCVT.isVector() ||
22749         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22750       return SDValue();
22751     InVec = InVec.getOperand(0);
22752   }
22753
22754   EVT CurrentVT = InVec.getValueType();
22755
22756   if (!isTargetShuffle(InVec.getOpcode()))
22757     return SDValue();
22758
22759   // Don't duplicate a load with other uses.
22760   if (!InVec.hasOneUse())
22761     return SDValue();
22762
22763   SmallVector<int, 16> ShuffleMask;
22764   bool UnaryShuffle;
22765   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22766                             ShuffleMask, UnaryShuffle))
22767     return SDValue();
22768
22769   // Select the input vector, guarding against out of range extract vector.
22770   unsigned NumElems = CurrentVT.getVectorNumElements();
22771   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22772   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22773   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22774                                          : InVec.getOperand(1);
22775
22776   // If inputs to shuffle are the same for both ops, then allow 2 uses
22777   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22778                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22779
22780   if (LdNode.getOpcode() == ISD::BITCAST) {
22781     // Don't duplicate a load with other uses.
22782     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22783       return SDValue();
22784
22785     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22786     LdNode = LdNode.getOperand(0);
22787   }
22788
22789   if (!ISD::isNormalLoad(LdNode.getNode()))
22790     return SDValue();
22791
22792   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22793
22794   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22795     return SDValue();
22796
22797   EVT EltVT = N->getValueType(0);
22798   // If there's a bitcast before the shuffle, check if the load type and
22799   // alignment is valid.
22800   unsigned Align = LN0->getAlignment();
22801   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22802   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22803       EltVT.getTypeForEVT(*DAG.getContext()));
22804
22805   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22806     return SDValue();
22807
22808   // All checks match so transform back to vector_shuffle so that DAG combiner
22809   // can finish the job
22810   SDLoc dl(N);
22811
22812   // Create shuffle node taking into account the case that its a unary shuffle
22813   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22814                                    : InVec.getOperand(1);
22815   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22816                                  InVec.getOperand(0), Shuffle,
22817                                  &ShuffleMask[0]);
22818   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22819   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22820                      EltNo);
22821 }
22822
22823 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22824 /// special and don't usually play with other vector types, it's better to
22825 /// handle them early to be sure we emit efficient code by avoiding
22826 /// store-load conversions.
22827 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22828   if (N->getValueType(0) != MVT::x86mmx ||
22829       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22830       N->getOperand(0)->getValueType(0) != MVT::v2i32)
22831     return SDValue();
22832
22833   SDValue V = N->getOperand(0);
22834   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22835   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22836     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22837                        N->getValueType(0), V.getOperand(0));
22838
22839   return SDValue();
22840 }
22841
22842 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22843 /// generation and convert it from being a bunch of shuffles and extracts
22844 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22845 /// storing the value and loading scalars back, while for x64 we should
22846 /// use 64-bit extracts and shifts.
22847 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22848                                          TargetLowering::DAGCombinerInfo &DCI) {
22849   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22850     return NewOp;
22851
22852   SDValue InputVector = N->getOperand(0);
22853   SDLoc dl(InputVector);
22854   // Detect mmx to i32 conversion through a v2i32 elt extract.
22855   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22856       N->getValueType(0) == MVT::i32 &&
22857       InputVector.getValueType() == MVT::v2i32) {
22858
22859     // The bitcast source is a direct mmx result.
22860     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22861     if (MMXSrc.getValueType() == MVT::x86mmx)
22862       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22863                          N->getValueType(0),
22864                          InputVector.getNode()->getOperand(0));
22865
22866     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22867     SDValue MMXSrcOp = MMXSrc.getOperand(0);
22868     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22869         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22870         MMXSrcOp.getOpcode() == ISD::BITCAST &&
22871         MMXSrcOp.getValueType() == MVT::v1i64 &&
22872         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22873       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22874                          N->getValueType(0),
22875                          MMXSrcOp.getOperand(0));
22876   }
22877
22878   EVT VT = N->getValueType(0);
22879
22880   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22881       InputVector.getOpcode() == ISD::BITCAST &&
22882       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22883     uint64_t ExtractedElt =
22884           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22885     uint64_t InputValue =
22886           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22887     uint64_t Res = (InputValue >> ExtractedElt) & 1;
22888     return DAG.getConstant(Res, dl, MVT::i1);
22889   }
22890   // Only operate on vectors of 4 elements, where the alternative shuffling
22891   // gets to be more expensive.
22892   if (InputVector.getValueType() != MVT::v4i32)
22893     return SDValue();
22894
22895   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22896   // single use which is a sign-extend or zero-extend, and all elements are
22897   // used.
22898   SmallVector<SDNode *, 4> Uses;
22899   unsigned ExtractedElements = 0;
22900   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22901        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22902     if (UI.getUse().getResNo() != InputVector.getResNo())
22903       return SDValue();
22904
22905     SDNode *Extract = *UI;
22906     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22907       return SDValue();
22908
22909     if (Extract->getValueType(0) != MVT::i32)
22910       return SDValue();
22911     if (!Extract->hasOneUse())
22912       return SDValue();
22913     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22914         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22915       return SDValue();
22916     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22917       return SDValue();
22918
22919     // Record which element was extracted.
22920     ExtractedElements |=
22921       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22922
22923     Uses.push_back(Extract);
22924   }
22925
22926   // If not all the elements were used, this may not be worthwhile.
22927   if (ExtractedElements != 15)
22928     return SDValue();
22929
22930   // Ok, we've now decided to do the transformation.
22931   // If 64-bit shifts are legal, use the extract-shift sequence,
22932   // otherwise bounce the vector off the cache.
22933   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22934   SDValue Vals[4];
22935
22936   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22937     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22938     auto &DL = DAG.getDataLayout();
22939     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22940     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22941       DAG.getConstant(0, dl, VecIdxTy));
22942     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22943       DAG.getConstant(1, dl, VecIdxTy));
22944
22945     SDValue ShAmt = DAG.getConstant(
22946         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22947     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22948     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22949       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22950     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22951     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22952       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22953   } else {
22954     // Store the value to a temporary stack slot.
22955     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22956     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22957       MachinePointerInfo(), false, false, 0);
22958
22959     EVT ElementType = InputVector.getValueType().getVectorElementType();
22960     unsigned EltSize = ElementType.getSizeInBits() / 8;
22961
22962     // Replace each use (extract) with a load of the appropriate element.
22963     for (unsigned i = 0; i < 4; ++i) {
22964       uint64_t Offset = EltSize * i;
22965       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22966       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22967
22968       SDValue ScalarAddr =
22969           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22970
22971       // Load the scalar.
22972       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22973                             ScalarAddr, MachinePointerInfo(),
22974                             false, false, false, 0);
22975
22976     }
22977   }
22978
22979   // Replace the extracts
22980   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22981     UE = Uses.end(); UI != UE; ++UI) {
22982     SDNode *Extract = *UI;
22983
22984     SDValue Idx = Extract->getOperand(1);
22985     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22986     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22987   }
22988
22989   // The replacement was made in place; don't return anything.
22990   return SDValue();
22991 }
22992
22993 static SDValue
22994 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22995                                       const X86Subtarget *Subtarget) {
22996   SDLoc dl(N);
22997   SDValue Cond = N->getOperand(0);
22998   SDValue LHS = N->getOperand(1);
22999   SDValue RHS = N->getOperand(2);
23000
23001   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
23002     SDValue CondSrc = Cond->getOperand(0);
23003     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
23004       Cond = CondSrc->getOperand(0);
23005   }
23006
23007   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
23008     return SDValue();
23009
23010   // A vselect where all conditions and data are constants can be optimized into
23011   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
23012   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
23013       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
23014     return SDValue();
23015
23016   unsigned MaskValue = 0;
23017   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
23018     return SDValue();
23019
23020   MVT VT = N->getSimpleValueType(0);
23021   unsigned NumElems = VT.getVectorNumElements();
23022   SmallVector<int, 8> ShuffleMask(NumElems, -1);
23023   for (unsigned i = 0; i < NumElems; ++i) {
23024     // Be sure we emit undef where we can.
23025     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
23026       ShuffleMask[i] = -1;
23027     else
23028       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
23029   }
23030
23031   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23032   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
23033     return SDValue();
23034   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
23035 }
23036
23037 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
23038 /// nodes.
23039 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
23040                                     TargetLowering::DAGCombinerInfo &DCI,
23041                                     const X86Subtarget *Subtarget) {
23042   SDLoc DL(N);
23043   SDValue Cond = N->getOperand(0);
23044   // Get the LHS/RHS of the select.
23045   SDValue LHS = N->getOperand(1);
23046   SDValue RHS = N->getOperand(2);
23047   EVT VT = LHS.getValueType();
23048   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23049
23050   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
23051   // instructions match the semantics of the common C idiom x<y?x:y but not
23052   // x<=y?x:y, because of how they handle negative zero (which can be
23053   // ignored in unsafe-math mode).
23054   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
23055   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
23056       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
23057       (Subtarget->hasSSE2() ||
23058        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
23059     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23060
23061     unsigned Opcode = 0;
23062     // Check for x CC y ? x : y.
23063     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23064         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23065       switch (CC) {
23066       default: break;
23067       case ISD::SETULT:
23068         // Converting this to a min would handle NaNs incorrectly, and swapping
23069         // the operands would cause it to handle comparisons between positive
23070         // and negative zero incorrectly.
23071         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23072           if (!DAG.getTarget().Options.UnsafeFPMath &&
23073               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23074             break;
23075           std::swap(LHS, RHS);
23076         }
23077         Opcode = X86ISD::FMIN;
23078         break;
23079       case ISD::SETOLE:
23080         // Converting this to a min would handle comparisons between positive
23081         // and negative zero incorrectly.
23082         if (!DAG.getTarget().Options.UnsafeFPMath &&
23083             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23084           break;
23085         Opcode = X86ISD::FMIN;
23086         break;
23087       case ISD::SETULE:
23088         // Converting this to a min would handle both negative zeros and NaNs
23089         // incorrectly, but we can swap the operands to fix both.
23090         std::swap(LHS, RHS);
23091       case ISD::SETOLT:
23092       case ISD::SETLT:
23093       case ISD::SETLE:
23094         Opcode = X86ISD::FMIN;
23095         break;
23096
23097       case ISD::SETOGE:
23098         // Converting this to a max would handle comparisons between positive
23099         // and negative zero incorrectly.
23100         if (!DAG.getTarget().Options.UnsafeFPMath &&
23101             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23102           break;
23103         Opcode = X86ISD::FMAX;
23104         break;
23105       case ISD::SETUGT:
23106         // Converting this to a max would handle NaNs incorrectly, and swapping
23107         // the operands would cause it to handle comparisons between positive
23108         // and negative zero incorrectly.
23109         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23110           if (!DAG.getTarget().Options.UnsafeFPMath &&
23111               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23112             break;
23113           std::swap(LHS, RHS);
23114         }
23115         Opcode = X86ISD::FMAX;
23116         break;
23117       case ISD::SETUGE:
23118         // Converting this to a max would handle both negative zeros and NaNs
23119         // incorrectly, but we can swap the operands to fix both.
23120         std::swap(LHS, RHS);
23121       case ISD::SETOGT:
23122       case ISD::SETGT:
23123       case ISD::SETGE:
23124         Opcode = X86ISD::FMAX;
23125         break;
23126       }
23127     // Check for x CC y ? y : x -- a min/max with reversed arms.
23128     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
23129                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
23130       switch (CC) {
23131       default: break;
23132       case ISD::SETOGE:
23133         // Converting this to a min would handle comparisons between positive
23134         // and negative zero incorrectly, and swapping the operands would
23135         // cause it to handle NaNs incorrectly.
23136         if (!DAG.getTarget().Options.UnsafeFPMath &&
23137             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
23138           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23139             break;
23140           std::swap(LHS, RHS);
23141         }
23142         Opcode = X86ISD::FMIN;
23143         break;
23144       case ISD::SETUGT:
23145         // Converting this to a min would handle NaNs incorrectly.
23146         if (!DAG.getTarget().Options.UnsafeFPMath &&
23147             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23148           break;
23149         Opcode = X86ISD::FMIN;
23150         break;
23151       case ISD::SETUGE:
23152         // Converting this to a min would handle both negative zeros and NaNs
23153         // incorrectly, but we can swap the operands to fix both.
23154         std::swap(LHS, RHS);
23155       case ISD::SETOGT:
23156       case ISD::SETGT:
23157       case ISD::SETGE:
23158         Opcode = X86ISD::FMIN;
23159         break;
23160
23161       case ISD::SETULT:
23162         // Converting this to a max would handle NaNs incorrectly.
23163         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23164           break;
23165         Opcode = X86ISD::FMAX;
23166         break;
23167       case ISD::SETOLE:
23168         // Converting this to a max would handle comparisons between positive
23169         // and negative zero incorrectly, and swapping the operands would
23170         // cause it to handle NaNs incorrectly.
23171         if (!DAG.getTarget().Options.UnsafeFPMath &&
23172             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23173           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23174             break;
23175           std::swap(LHS, RHS);
23176         }
23177         Opcode = X86ISD::FMAX;
23178         break;
23179       case ISD::SETULE:
23180         // Converting this to a max would handle both negative zeros and NaNs
23181         // incorrectly, but we can swap the operands to fix both.
23182         std::swap(LHS, RHS);
23183       case ISD::SETOLT:
23184       case ISD::SETLT:
23185       case ISD::SETLE:
23186         Opcode = X86ISD::FMAX;
23187         break;
23188       }
23189     }
23190
23191     if (Opcode)
23192       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23193   }
23194
23195   EVT CondVT = Cond.getValueType();
23196   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23197       CondVT.getVectorElementType() == MVT::i1) {
23198     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23199     // lowering on KNL. In this case we convert it to
23200     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23201     // The same situation for all 128 and 256-bit vectors of i8 and i16.
23202     // Since SKX these selects have a proper lowering.
23203     EVT OpVT = LHS.getValueType();
23204     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23205         (OpVT.getVectorElementType() == MVT::i8 ||
23206          OpVT.getVectorElementType() == MVT::i16) &&
23207         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23208       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23209       DCI.AddToWorklist(Cond.getNode());
23210       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23211     }
23212   }
23213   // If this is a select between two integer constants, try to do some
23214   // optimizations.
23215   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23216     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23217       // Don't do this for crazy integer types.
23218       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23219         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23220         // so that TrueC (the true value) is larger than FalseC.
23221         bool NeedsCondInvert = false;
23222
23223         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23224             // Efficiently invertible.
23225             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
23226              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
23227               isa<ConstantSDNode>(Cond.getOperand(1))))) {
23228           NeedsCondInvert = true;
23229           std::swap(TrueC, FalseC);
23230         }
23231
23232         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
23233         if (FalseC->getAPIntValue() == 0 &&
23234             TrueC->getAPIntValue().isPowerOf2()) {
23235           if (NeedsCondInvert) // Invert the condition if needed.
23236             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23237                                DAG.getConstant(1, DL, Cond.getValueType()));
23238
23239           // Zero extend the condition if needed.
23240           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23241
23242           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23243           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23244                              DAG.getConstant(ShAmt, DL, MVT::i8));
23245         }
23246
23247         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23248         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23249           if (NeedsCondInvert) // Invert the condition if needed.
23250             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23251                                DAG.getConstant(1, DL, Cond.getValueType()));
23252
23253           // Zero extend the condition if needed.
23254           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23255                              FalseC->getValueType(0), Cond);
23256           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23257                              SDValue(FalseC, 0));
23258         }
23259
23260         // Optimize cases that will turn into an LEA instruction.  This requires
23261         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23262         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23263           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23264           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23265
23266           bool isFastMultiplier = false;
23267           if (Diff < 10) {
23268             switch ((unsigned char)Diff) {
23269               default: break;
23270               case 1:  // result = add base, cond
23271               case 2:  // result = lea base(    , cond*2)
23272               case 3:  // result = lea base(cond, cond*2)
23273               case 4:  // result = lea base(    , cond*4)
23274               case 5:  // result = lea base(cond, cond*4)
23275               case 8:  // result = lea base(    , cond*8)
23276               case 9:  // result = lea base(cond, cond*8)
23277                 isFastMultiplier = true;
23278                 break;
23279             }
23280           }
23281
23282           if (isFastMultiplier) {
23283             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23284             if (NeedsCondInvert) // Invert the condition if needed.
23285               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23286                                  DAG.getConstant(1, DL, Cond.getValueType()));
23287
23288             // Zero extend the condition if needed.
23289             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23290                                Cond);
23291             // Scale the condition by the difference.
23292             if (Diff != 1)
23293               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23294                                  DAG.getConstant(Diff, DL,
23295                                                  Cond.getValueType()));
23296
23297             // Add the base if non-zero.
23298             if (FalseC->getAPIntValue() != 0)
23299               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23300                                  SDValue(FalseC, 0));
23301             return Cond;
23302           }
23303         }
23304       }
23305   }
23306
23307   // Canonicalize max and min:
23308   // (x > y) ? x : y -> (x >= y) ? x : y
23309   // (x < y) ? x : y -> (x <= y) ? x : y
23310   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23311   // the need for an extra compare
23312   // against zero. e.g.
23313   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23314   // subl   %esi, %edi
23315   // testl  %edi, %edi
23316   // movl   $0, %eax
23317   // cmovgl %edi, %eax
23318   // =>
23319   // xorl   %eax, %eax
23320   // subl   %esi, $edi
23321   // cmovsl %eax, %edi
23322   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23323       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23324       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23325     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23326     switch (CC) {
23327     default: break;
23328     case ISD::SETLT:
23329     case ISD::SETGT: {
23330       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23331       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23332                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23333       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23334     }
23335     }
23336   }
23337
23338   // Early exit check
23339   if (!TLI.isTypeLegal(VT))
23340     return SDValue();
23341
23342   // Match VSELECTs into subs with unsigned saturation.
23343   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23344       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23345       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23346        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23347     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23348
23349     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23350     // left side invert the predicate to simplify logic below.
23351     SDValue Other;
23352     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23353       Other = RHS;
23354       CC = ISD::getSetCCInverse(CC, true);
23355     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23356       Other = LHS;
23357     }
23358
23359     if (Other.getNode() && Other->getNumOperands() == 2 &&
23360         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23361       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23362       SDValue CondRHS = Cond->getOperand(1);
23363
23364       // Look for a general sub with unsigned saturation first.
23365       // x >= y ? x-y : 0 --> subus x, y
23366       // x >  y ? x-y : 0 --> subus x, y
23367       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23368           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23369         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23370
23371       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23372         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23373           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23374             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23375               // If the RHS is a constant we have to reverse the const
23376               // canonicalization.
23377               // x > C-1 ? x+-C : 0 --> subus x, C
23378               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23379                   CondRHSConst->getAPIntValue() ==
23380                       (-OpRHSConst->getAPIntValue() - 1))
23381                 return DAG.getNode(
23382                     X86ISD::SUBUS, DL, VT, OpLHS,
23383                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
23384
23385           // Another special case: If C was a sign bit, the sub has been
23386           // canonicalized into a xor.
23387           // FIXME: Would it be better to use computeKnownBits to determine
23388           //        whether it's safe to decanonicalize the xor?
23389           // x s< 0 ? x^C : 0 --> subus x, C
23390           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23391               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23392               OpRHSConst->getAPIntValue().isSignBit())
23393             // Note that we have to rebuild the RHS constant here to ensure we
23394             // don't rely on particular values of undef lanes.
23395             return DAG.getNode(
23396                 X86ISD::SUBUS, DL, VT, OpLHS,
23397                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
23398         }
23399     }
23400   }
23401
23402   // Simplify vector selection if condition value type matches vselect
23403   // operand type
23404   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23405     assert(Cond.getValueType().isVector() &&
23406            "vector select expects a vector selector!");
23407
23408     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23409     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23410
23411     // Try invert the condition if true value is not all 1s and false value
23412     // is not all 0s.
23413     if (!TValIsAllOnes && !FValIsAllZeros &&
23414         // Check if the selector will be produced by CMPP*/PCMP*
23415         Cond.getOpcode() == ISD::SETCC &&
23416         // Check if SETCC has already been promoted
23417         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23418             CondVT) {
23419       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23420       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23421
23422       if (TValIsAllZeros || FValIsAllOnes) {
23423         SDValue CC = Cond.getOperand(2);
23424         ISD::CondCode NewCC =
23425           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23426                                Cond.getOperand(0).getValueType().isInteger());
23427         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23428         std::swap(LHS, RHS);
23429         TValIsAllOnes = FValIsAllOnes;
23430         FValIsAllZeros = TValIsAllZeros;
23431       }
23432     }
23433
23434     if (TValIsAllOnes || FValIsAllZeros) {
23435       SDValue Ret;
23436
23437       if (TValIsAllOnes && FValIsAllZeros)
23438         Ret = Cond;
23439       else if (TValIsAllOnes)
23440         Ret =
23441             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23442       else if (FValIsAllZeros)
23443         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23444                           DAG.getBitcast(CondVT, LHS));
23445
23446       return DAG.getBitcast(VT, Ret);
23447     }
23448   }
23449
23450   // We should generate an X86ISD::BLENDI from a vselect if its argument
23451   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23452   // constants. This specific pattern gets generated when we split a
23453   // selector for a 512 bit vector in a machine without AVX512 (but with
23454   // 256-bit vectors), during legalization:
23455   //
23456   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23457   //
23458   // Iff we find this pattern and the build_vectors are built from
23459   // constants, we translate the vselect into a shuffle_vector that we
23460   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23461   if ((N->getOpcode() == ISD::VSELECT ||
23462        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23463       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23464     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23465     if (Shuffle.getNode())
23466       return Shuffle;
23467   }
23468
23469   // If this is a *dynamic* select (non-constant condition) and we can match
23470   // this node with one of the variable blend instructions, restructure the
23471   // condition so that the blends can use the high bit of each element and use
23472   // SimplifyDemandedBits to simplify the condition operand.
23473   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23474       !DCI.isBeforeLegalize() &&
23475       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23476     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23477
23478     // Don't optimize vector selects that map to mask-registers.
23479     if (BitWidth == 1)
23480       return SDValue();
23481
23482     // We can only handle the cases where VSELECT is directly legal on the
23483     // subtarget. We custom lower VSELECT nodes with constant conditions and
23484     // this makes it hard to see whether a dynamic VSELECT will correctly
23485     // lower, so we both check the operation's status and explicitly handle the
23486     // cases where a *dynamic* blend will fail even though a constant-condition
23487     // blend could be custom lowered.
23488     // FIXME: We should find a better way to handle this class of problems.
23489     // Potentially, we should combine constant-condition vselect nodes
23490     // pre-legalization into shuffles and not mark as many types as custom
23491     // lowered.
23492     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23493       return SDValue();
23494     // FIXME: We don't support i16-element blends currently. We could and
23495     // should support them by making *all* the bits in the condition be set
23496     // rather than just the high bit and using an i8-element blend.
23497     if (VT.getScalarType() == MVT::i16)
23498       return SDValue();
23499     // Dynamic blending was only available from SSE4.1 onward.
23500     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23501       return SDValue();
23502     // Byte blends are only available in AVX2
23503     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23504         !Subtarget->hasAVX2())
23505       return SDValue();
23506
23507     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23508     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23509
23510     APInt KnownZero, KnownOne;
23511     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23512                                           DCI.isBeforeLegalizeOps());
23513     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23514         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23515                                  TLO)) {
23516       // If we changed the computation somewhere in the DAG, this change
23517       // will affect all users of Cond.
23518       // Make sure it is fine and update all the nodes so that we do not
23519       // use the generic VSELECT anymore. Otherwise, we may perform
23520       // wrong optimizations as we messed up with the actual expectation
23521       // for the vector boolean values.
23522       if (Cond != TLO.Old) {
23523         // Check all uses of that condition operand to check whether it will be
23524         // consumed by non-BLEND instructions, which may depend on all bits are
23525         // set properly.
23526         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23527              I != E; ++I)
23528           if (I->getOpcode() != ISD::VSELECT)
23529             // TODO: Add other opcodes eventually lowered into BLEND.
23530             return SDValue();
23531
23532         // Update all the users of the condition, before committing the change,
23533         // so that the VSELECT optimizations that expect the correct vector
23534         // boolean value will not be triggered.
23535         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23536              I != E; ++I)
23537           DAG.ReplaceAllUsesOfValueWith(
23538               SDValue(*I, 0),
23539               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23540                           Cond, I->getOperand(1), I->getOperand(2)));
23541         DCI.CommitTargetLoweringOpt(TLO);
23542         return SDValue();
23543       }
23544       // At this point, only Cond is changed. Change the condition
23545       // just for N to keep the opportunity to optimize all other
23546       // users their own way.
23547       DAG.ReplaceAllUsesOfValueWith(
23548           SDValue(N, 0),
23549           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23550                       TLO.New, N->getOperand(1), N->getOperand(2)));
23551       return SDValue();
23552     }
23553   }
23554
23555   return SDValue();
23556 }
23557
23558 // Check whether a boolean test is testing a boolean value generated by
23559 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23560 // code.
23561 //
23562 // Simplify the following patterns:
23563 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23564 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23565 // to (Op EFLAGS Cond)
23566 //
23567 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23568 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23569 // to (Op EFLAGS !Cond)
23570 //
23571 // where Op could be BRCOND or CMOV.
23572 //
23573 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23574   // Quit if not CMP and SUB with its value result used.
23575   if (Cmp.getOpcode() != X86ISD::CMP &&
23576       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23577       return SDValue();
23578
23579   // Quit if not used as a boolean value.
23580   if (CC != X86::COND_E && CC != X86::COND_NE)
23581     return SDValue();
23582
23583   // Check CMP operands. One of them should be 0 or 1 and the other should be
23584   // an SetCC or extended from it.
23585   SDValue Op1 = Cmp.getOperand(0);
23586   SDValue Op2 = Cmp.getOperand(1);
23587
23588   SDValue SetCC;
23589   const ConstantSDNode* C = nullptr;
23590   bool needOppositeCond = (CC == X86::COND_E);
23591   bool checkAgainstTrue = false; // Is it a comparison against 1?
23592
23593   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23594     SetCC = Op2;
23595   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23596     SetCC = Op1;
23597   else // Quit if all operands are not constants.
23598     return SDValue();
23599
23600   if (C->getZExtValue() == 1) {
23601     needOppositeCond = !needOppositeCond;
23602     checkAgainstTrue = true;
23603   } else if (C->getZExtValue() != 0)
23604     // Quit if the constant is neither 0 or 1.
23605     return SDValue();
23606
23607   bool truncatedToBoolWithAnd = false;
23608   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23609   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23610          SetCC.getOpcode() == ISD::TRUNCATE ||
23611          SetCC.getOpcode() == ISD::AND) {
23612     if (SetCC.getOpcode() == ISD::AND) {
23613       int OpIdx = -1;
23614       ConstantSDNode *CS;
23615       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23616           CS->getZExtValue() == 1)
23617         OpIdx = 1;
23618       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23619           CS->getZExtValue() == 1)
23620         OpIdx = 0;
23621       if (OpIdx == -1)
23622         break;
23623       SetCC = SetCC.getOperand(OpIdx);
23624       truncatedToBoolWithAnd = true;
23625     } else
23626       SetCC = SetCC.getOperand(0);
23627   }
23628
23629   switch (SetCC.getOpcode()) {
23630   case X86ISD::SETCC_CARRY:
23631     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23632     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23633     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23634     // truncated to i1 using 'and'.
23635     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23636       break;
23637     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23638            "Invalid use of SETCC_CARRY!");
23639     // FALL THROUGH
23640   case X86ISD::SETCC:
23641     // Set the condition code or opposite one if necessary.
23642     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23643     if (needOppositeCond)
23644       CC = X86::GetOppositeBranchCondition(CC);
23645     return SetCC.getOperand(1);
23646   case X86ISD::CMOV: {
23647     // Check whether false/true value has canonical one, i.e. 0 or 1.
23648     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23649     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23650     // Quit if true value is not a constant.
23651     if (!TVal)
23652       return SDValue();
23653     // Quit if false value is not a constant.
23654     if (!FVal) {
23655       SDValue Op = SetCC.getOperand(0);
23656       // Skip 'zext' or 'trunc' node.
23657       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23658           Op.getOpcode() == ISD::TRUNCATE)
23659         Op = Op.getOperand(0);
23660       // A special case for rdrand/rdseed, where 0 is set if false cond is
23661       // found.
23662       if ((Op.getOpcode() != X86ISD::RDRAND &&
23663            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23664         return SDValue();
23665     }
23666     // Quit if false value is not the constant 0 or 1.
23667     bool FValIsFalse = true;
23668     if (FVal && FVal->getZExtValue() != 0) {
23669       if (FVal->getZExtValue() != 1)
23670         return SDValue();
23671       // If FVal is 1, opposite cond is needed.
23672       needOppositeCond = !needOppositeCond;
23673       FValIsFalse = false;
23674     }
23675     // Quit if TVal is not the constant opposite of FVal.
23676     if (FValIsFalse && TVal->getZExtValue() != 1)
23677       return SDValue();
23678     if (!FValIsFalse && TVal->getZExtValue() != 0)
23679       return SDValue();
23680     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23681     if (needOppositeCond)
23682       CC = X86::GetOppositeBranchCondition(CC);
23683     return SetCC.getOperand(3);
23684   }
23685   }
23686
23687   return SDValue();
23688 }
23689
23690 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23691 /// Match:
23692 ///   (X86or (X86setcc) (X86setcc))
23693 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
23694 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23695                                            X86::CondCode &CC1, SDValue &Flags,
23696                                            bool &isAnd) {
23697   if (Cond->getOpcode() == X86ISD::CMP) {
23698     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23699     if (!CondOp1C || !CondOp1C->isNullValue())
23700       return false;
23701
23702     Cond = Cond->getOperand(0);
23703   }
23704
23705   isAnd = false;
23706
23707   SDValue SetCC0, SetCC1;
23708   switch (Cond->getOpcode()) {
23709   default: return false;
23710   case ISD::AND:
23711   case X86ISD::AND:
23712     isAnd = true;
23713     // fallthru
23714   case ISD::OR:
23715   case X86ISD::OR:
23716     SetCC0 = Cond->getOperand(0);
23717     SetCC1 = Cond->getOperand(1);
23718     break;
23719   };
23720
23721   // Make sure we have SETCC nodes, using the same flags value.
23722   if (SetCC0.getOpcode() != X86ISD::SETCC ||
23723       SetCC1.getOpcode() != X86ISD::SETCC ||
23724       SetCC0->getOperand(1) != SetCC1->getOperand(1))
23725     return false;
23726
23727   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23728   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23729   Flags = SetCC0->getOperand(1);
23730   return true;
23731 }
23732
23733 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23734 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23735                                   TargetLowering::DAGCombinerInfo &DCI,
23736                                   const X86Subtarget *Subtarget) {
23737   SDLoc DL(N);
23738
23739   // If the flag operand isn't dead, don't touch this CMOV.
23740   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23741     return SDValue();
23742
23743   SDValue FalseOp = N->getOperand(0);
23744   SDValue TrueOp = N->getOperand(1);
23745   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23746   SDValue Cond = N->getOperand(3);
23747
23748   if (CC == X86::COND_E || CC == X86::COND_NE) {
23749     switch (Cond.getOpcode()) {
23750     default: break;
23751     case X86ISD::BSR:
23752     case X86ISD::BSF:
23753       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23754       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23755         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23756     }
23757   }
23758
23759   SDValue Flags;
23760
23761   Flags = checkBoolTestSetCCCombine(Cond, CC);
23762   if (Flags.getNode() &&
23763       // Extra check as FCMOV only supports a subset of X86 cond.
23764       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23765     SDValue Ops[] = { FalseOp, TrueOp,
23766                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23767     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23768   }
23769
23770   // If this is a select between two integer constants, try to do some
23771   // optimizations.  Note that the operands are ordered the opposite of SELECT
23772   // operands.
23773   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23774     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23775       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23776       // larger than FalseC (the false value).
23777       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23778         CC = X86::GetOppositeBranchCondition(CC);
23779         std::swap(TrueC, FalseC);
23780         std::swap(TrueOp, FalseOp);
23781       }
23782
23783       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23784       // This is efficient for any integer data type (including i8/i16) and
23785       // shift amount.
23786       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23787         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23788                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23789
23790         // Zero extend the condition if needed.
23791         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23792
23793         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23794         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23795                            DAG.getConstant(ShAmt, DL, MVT::i8));
23796         if (N->getNumValues() == 2)  // Dead flag value?
23797           return DCI.CombineTo(N, Cond, SDValue());
23798         return Cond;
23799       }
23800
23801       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23802       // for any integer data type, including i8/i16.
23803       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23804         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23805                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23806
23807         // Zero extend the condition if needed.
23808         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23809                            FalseC->getValueType(0), Cond);
23810         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23811                            SDValue(FalseC, 0));
23812
23813         if (N->getNumValues() == 2)  // Dead flag value?
23814           return DCI.CombineTo(N, Cond, SDValue());
23815         return Cond;
23816       }
23817
23818       // Optimize cases that will turn into an LEA instruction.  This requires
23819       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23820       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23821         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23822         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23823
23824         bool isFastMultiplier = false;
23825         if (Diff < 10) {
23826           switch ((unsigned char)Diff) {
23827           default: break;
23828           case 1:  // result = add base, cond
23829           case 2:  // result = lea base(    , cond*2)
23830           case 3:  // result = lea base(cond, cond*2)
23831           case 4:  // result = lea base(    , cond*4)
23832           case 5:  // result = lea base(cond, cond*4)
23833           case 8:  // result = lea base(    , cond*8)
23834           case 9:  // result = lea base(cond, cond*8)
23835             isFastMultiplier = true;
23836             break;
23837           }
23838         }
23839
23840         if (isFastMultiplier) {
23841           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23842           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23843                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23844           // Zero extend the condition if needed.
23845           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23846                              Cond);
23847           // Scale the condition by the difference.
23848           if (Diff != 1)
23849             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23850                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23851
23852           // Add the base if non-zero.
23853           if (FalseC->getAPIntValue() != 0)
23854             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23855                                SDValue(FalseC, 0));
23856           if (N->getNumValues() == 2)  // Dead flag value?
23857             return DCI.CombineTo(N, Cond, SDValue());
23858           return Cond;
23859         }
23860       }
23861     }
23862   }
23863
23864   // Handle these cases:
23865   //   (select (x != c), e, c) -> select (x != c), e, x),
23866   //   (select (x == c), c, e) -> select (x == c), x, e)
23867   // where the c is an integer constant, and the "select" is the combination
23868   // of CMOV and CMP.
23869   //
23870   // The rationale for this change is that the conditional-move from a constant
23871   // needs two instructions, however, conditional-move from a register needs
23872   // only one instruction.
23873   //
23874   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23875   //  some instruction-combining opportunities. This opt needs to be
23876   //  postponed as late as possible.
23877   //
23878   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23879     // the DCI.xxxx conditions are provided to postpone the optimization as
23880     // late as possible.
23881
23882     ConstantSDNode *CmpAgainst = nullptr;
23883     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23884         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23885         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23886
23887       if (CC == X86::COND_NE &&
23888           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23889         CC = X86::GetOppositeBranchCondition(CC);
23890         std::swap(TrueOp, FalseOp);
23891       }
23892
23893       if (CC == X86::COND_E &&
23894           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23895         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23896                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23897         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23898       }
23899     }
23900   }
23901
23902   // Fold and/or of setcc's to double CMOV:
23903   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23904   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23905   //
23906   // This combine lets us generate:
23907   //   cmovcc1 (jcc1 if we don't have CMOV)
23908   //   cmovcc2 (same)
23909   // instead of:
23910   //   setcc1
23911   //   setcc2
23912   //   and/or
23913   //   cmovne (jne if we don't have CMOV)
23914   // When we can't use the CMOV instruction, it might increase branch
23915   // mispredicts.
23916   // When we can use CMOV, or when there is no mispredict, this improves
23917   // throughput and reduces register pressure.
23918   //
23919   if (CC == X86::COND_NE) {
23920     SDValue Flags;
23921     X86::CondCode CC0, CC1;
23922     bool isAndSetCC;
23923     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23924       if (isAndSetCC) {
23925         std::swap(FalseOp, TrueOp);
23926         CC0 = X86::GetOppositeBranchCondition(CC0);
23927         CC1 = X86::GetOppositeBranchCondition(CC1);
23928       }
23929
23930       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23931         Flags};
23932       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23933       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23934       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23935       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23936       return CMOV;
23937     }
23938   }
23939
23940   return SDValue();
23941 }
23942
23943 /// PerformMulCombine - Optimize a single multiply with constant into two
23944 /// in order to implement it with two cheaper instructions, e.g.
23945 /// LEA + SHL, LEA + LEA.
23946 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23947                                  TargetLowering::DAGCombinerInfo &DCI) {
23948   // An imul is usually smaller than the alternative sequence.
23949   if (DAG.getMachineFunction().getFunction()->optForMinSize())
23950     return SDValue();
23951
23952   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23953     return SDValue();
23954
23955   EVT VT = N->getValueType(0);
23956   if (VT != MVT::i64 && VT != MVT::i32)
23957     return SDValue();
23958
23959   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23960   if (!C)
23961     return SDValue();
23962   uint64_t MulAmt = C->getZExtValue();
23963   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23964     return SDValue();
23965
23966   uint64_t MulAmt1 = 0;
23967   uint64_t MulAmt2 = 0;
23968   if ((MulAmt % 9) == 0) {
23969     MulAmt1 = 9;
23970     MulAmt2 = MulAmt / 9;
23971   } else if ((MulAmt % 5) == 0) {
23972     MulAmt1 = 5;
23973     MulAmt2 = MulAmt / 5;
23974   } else if ((MulAmt % 3) == 0) {
23975     MulAmt1 = 3;
23976     MulAmt2 = MulAmt / 3;
23977   }
23978   if (MulAmt2 &&
23979       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23980     SDLoc DL(N);
23981
23982     if (isPowerOf2_64(MulAmt2) &&
23983         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23984       // If second multiplifer is pow2, issue it first. We want the multiply by
23985       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23986       // is an add.
23987       std::swap(MulAmt1, MulAmt2);
23988
23989     SDValue NewMul;
23990     if (isPowerOf2_64(MulAmt1))
23991       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23992                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23993     else
23994       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23995                            DAG.getConstant(MulAmt1, DL, VT));
23996
23997     if (isPowerOf2_64(MulAmt2))
23998       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23999                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
24000     else
24001       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
24002                            DAG.getConstant(MulAmt2, DL, VT));
24003
24004     // Do not add new nodes to DAG combiner worklist.
24005     DCI.CombineTo(N, NewMul, false);
24006   }
24007   return SDValue();
24008 }
24009
24010 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
24011   SDValue N0 = N->getOperand(0);
24012   SDValue N1 = N->getOperand(1);
24013   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
24014   EVT VT = N0.getValueType();
24015
24016   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
24017   // since the result of setcc_c is all zero's or all ones.
24018   if (VT.isInteger() && !VT.isVector() &&
24019       N1C && N0.getOpcode() == ISD::AND &&
24020       N0.getOperand(1).getOpcode() == ISD::Constant) {
24021     SDValue N00 = N0.getOperand(0);
24022     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
24023     APInt ShAmt = N1C->getAPIntValue();
24024     Mask = Mask.shl(ShAmt);
24025     bool MaskOK = false;
24026     // We can handle cases concerning bit-widening nodes containing setcc_c if
24027     // we carefully interrogate the mask to make sure we are semantics
24028     // preserving.
24029     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
24030     // of the underlying setcc_c operation if the setcc_c was zero extended.
24031     // Consider the following example:
24032     //   zext(setcc_c)                 -> i32 0x0000FFFF
24033     //   c1                            -> i32 0x0000FFFF
24034     //   c2                            -> i32 0x00000001
24035     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
24036     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
24037     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24038       MaskOK = true;
24039     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
24040                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24041       MaskOK = true;
24042     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
24043                 N00.getOpcode() == ISD::ANY_EXTEND) &&
24044                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24045       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
24046     }
24047     if (MaskOK && Mask != 0) {
24048       SDLoc DL(N);
24049       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
24050     }
24051   }
24052
24053   // Hardware support for vector shifts is sparse which makes us scalarize the
24054   // vector operations in many cases. Also, on sandybridge ADD is faster than
24055   // shl.
24056   // (shl V, 1) -> add V,V
24057   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
24058     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
24059       assert(N0.getValueType().isVector() && "Invalid vector shift type");
24060       // We shift all of the values by one. In many cases we do not have
24061       // hardware support for this operation. This is better expressed as an ADD
24062       // of two values.
24063       if (N1SplatC->getAPIntValue() == 1)
24064         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
24065     }
24066
24067   return SDValue();
24068 }
24069
24070 /// \brief Returns a vector of 0s if the node in input is a vector logical
24071 /// shift by a constant amount which is known to be bigger than or equal
24072 /// to the vector element size in bits.
24073 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
24074                                       const X86Subtarget *Subtarget) {
24075   EVT VT = N->getValueType(0);
24076
24077   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
24078       (!Subtarget->hasInt256() ||
24079        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
24080     return SDValue();
24081
24082   SDValue Amt = N->getOperand(1);
24083   SDLoc DL(N);
24084   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
24085     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
24086       APInt ShiftAmt = AmtSplat->getAPIntValue();
24087       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
24088
24089       // SSE2/AVX2 logical shifts always return a vector of 0s
24090       // if the shift amount is bigger than or equal to
24091       // the element size. The constant shift amount will be
24092       // encoded as a 8-bit immediate.
24093       if (ShiftAmt.trunc(8).uge(MaxAmount))
24094         return getZeroVector(VT, Subtarget, DAG, DL);
24095     }
24096
24097   return SDValue();
24098 }
24099
24100 /// PerformShiftCombine - Combine shifts.
24101 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
24102                                    TargetLowering::DAGCombinerInfo &DCI,
24103                                    const X86Subtarget *Subtarget) {
24104   if (N->getOpcode() == ISD::SHL)
24105     if (SDValue V = PerformSHLCombine(N, DAG))
24106       return V;
24107
24108   // Try to fold this logical shift into a zero vector.
24109   if (N->getOpcode() != ISD::SRA)
24110     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
24111       return V;
24112
24113   return SDValue();
24114 }
24115
24116 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
24117 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
24118 // and friends.  Likewise for OR -> CMPNEQSS.
24119 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
24120                             TargetLowering::DAGCombinerInfo &DCI,
24121                             const X86Subtarget *Subtarget) {
24122   unsigned opcode;
24123
24124   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
24125   // we're requiring SSE2 for both.
24126   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
24127     SDValue N0 = N->getOperand(0);
24128     SDValue N1 = N->getOperand(1);
24129     SDValue CMP0 = N0->getOperand(1);
24130     SDValue CMP1 = N1->getOperand(1);
24131     SDLoc DL(N);
24132
24133     // The SETCCs should both refer to the same CMP.
24134     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
24135       return SDValue();
24136
24137     SDValue CMP00 = CMP0->getOperand(0);
24138     SDValue CMP01 = CMP0->getOperand(1);
24139     EVT     VT    = CMP00.getValueType();
24140
24141     if (VT == MVT::f32 || VT == MVT::f64) {
24142       bool ExpectingFlags = false;
24143       // Check for any users that want flags:
24144       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
24145            !ExpectingFlags && UI != UE; ++UI)
24146         switch (UI->getOpcode()) {
24147         default:
24148         case ISD::BR_CC:
24149         case ISD::BRCOND:
24150         case ISD::SELECT:
24151           ExpectingFlags = true;
24152           break;
24153         case ISD::CopyToReg:
24154         case ISD::SIGN_EXTEND:
24155         case ISD::ZERO_EXTEND:
24156         case ISD::ANY_EXTEND:
24157           break;
24158         }
24159
24160       if (!ExpectingFlags) {
24161         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24162         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24163
24164         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24165           X86::CondCode tmp = cc0;
24166           cc0 = cc1;
24167           cc1 = tmp;
24168         }
24169
24170         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
24171             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24172           // FIXME: need symbolic constants for these magic numbers.
24173           // See X86ATTInstPrinter.cpp:printSSECC().
24174           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24175           if (Subtarget->hasAVX512()) {
24176             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24177                                          CMP01,
24178                                          DAG.getConstant(x86cc, DL, MVT::i8));
24179             if (N->getValueType(0) != MVT::i1)
24180               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24181                                  FSetCC);
24182             return FSetCC;
24183           }
24184           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24185                                               CMP00.getValueType(), CMP00, CMP01,
24186                                               DAG.getConstant(x86cc, DL,
24187                                                               MVT::i8));
24188
24189           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24190           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24191
24192           if (is64BitFP && !Subtarget->is64Bit()) {
24193             // On a 32-bit target, we cannot bitcast the 64-bit float to a
24194             // 64-bit integer, since that's not a legal type. Since
24195             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24196             // bits, but can do this little dance to extract the lowest 32 bits
24197             // and work with those going forward.
24198             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24199                                            OnesOrZeroesF);
24200             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
24201             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24202                                         Vector32, DAG.getIntPtrConstant(0, DL));
24203             IntVT = MVT::i32;
24204           }
24205
24206           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
24207           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24208                                       DAG.getConstant(1, DL, IntVT));
24209           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
24210                                               ANDed);
24211           return OneBitOfTruth;
24212         }
24213       }
24214     }
24215   }
24216   return SDValue();
24217 }
24218
24219 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24220 /// so it can be folded inside ANDNP.
24221 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24222   EVT VT = N->getValueType(0);
24223
24224   // Match direct AllOnes for 128 and 256-bit vectors
24225   if (ISD::isBuildVectorAllOnes(N))
24226     return true;
24227
24228   // Look through a bit convert.
24229   if (N->getOpcode() == ISD::BITCAST)
24230     N = N->getOperand(0).getNode();
24231
24232   // Sometimes the operand may come from a insert_subvector building a 256-bit
24233   // allones vector
24234   if (VT.is256BitVector() &&
24235       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24236     SDValue V1 = N->getOperand(0);
24237     SDValue V2 = N->getOperand(1);
24238
24239     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24240         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24241         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24242         ISD::isBuildVectorAllOnes(V2.getNode()))
24243       return true;
24244   }
24245
24246   return false;
24247 }
24248
24249 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24250 // register. In most cases we actually compare or select YMM-sized registers
24251 // and mixing the two types creates horrible code. This method optimizes
24252 // some of the transition sequences.
24253 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24254                                  TargetLowering::DAGCombinerInfo &DCI,
24255                                  const X86Subtarget *Subtarget) {
24256   EVT VT = N->getValueType(0);
24257   if (!VT.is256BitVector())
24258     return SDValue();
24259
24260   assert((N->getOpcode() == ISD::ANY_EXTEND ||
24261           N->getOpcode() == ISD::ZERO_EXTEND ||
24262           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24263
24264   SDValue Narrow = N->getOperand(0);
24265   EVT NarrowVT = Narrow->getValueType(0);
24266   if (!NarrowVT.is128BitVector())
24267     return SDValue();
24268
24269   if (Narrow->getOpcode() != ISD::XOR &&
24270       Narrow->getOpcode() != ISD::AND &&
24271       Narrow->getOpcode() != ISD::OR)
24272     return SDValue();
24273
24274   SDValue N0  = Narrow->getOperand(0);
24275   SDValue N1  = Narrow->getOperand(1);
24276   SDLoc DL(Narrow);
24277
24278   // The Left side has to be a trunc.
24279   if (N0.getOpcode() != ISD::TRUNCATE)
24280     return SDValue();
24281
24282   // The type of the truncated inputs.
24283   EVT WideVT = N0->getOperand(0)->getValueType(0);
24284   if (WideVT != VT)
24285     return SDValue();
24286
24287   // The right side has to be a 'trunc' or a constant vector.
24288   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24289   ConstantSDNode *RHSConstSplat = nullptr;
24290   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24291     RHSConstSplat = RHSBV->getConstantSplatNode();
24292   if (!RHSTrunc && !RHSConstSplat)
24293     return SDValue();
24294
24295   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24296
24297   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24298     return SDValue();
24299
24300   // Set N0 and N1 to hold the inputs to the new wide operation.
24301   N0 = N0->getOperand(0);
24302   if (RHSConstSplat) {
24303     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24304                      SDValue(RHSConstSplat, 0));
24305     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24306     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24307   } else if (RHSTrunc) {
24308     N1 = N1->getOperand(0);
24309   }
24310
24311   // Generate the wide operation.
24312   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24313   unsigned Opcode = N->getOpcode();
24314   switch (Opcode) {
24315   case ISD::ANY_EXTEND:
24316     return Op;
24317   case ISD::ZERO_EXTEND: {
24318     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24319     APInt Mask = APInt::getAllOnesValue(InBits);
24320     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24321     return DAG.getNode(ISD::AND, DL, VT,
24322                        Op, DAG.getConstant(Mask, DL, VT));
24323   }
24324   case ISD::SIGN_EXTEND:
24325     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24326                        Op, DAG.getValueType(NarrowVT));
24327   default:
24328     llvm_unreachable("Unexpected opcode");
24329   }
24330 }
24331
24332 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
24333                                  TargetLowering::DAGCombinerInfo &DCI,
24334                                  const X86Subtarget *Subtarget) {
24335   SDValue N0 = N->getOperand(0);
24336   SDValue N1 = N->getOperand(1);
24337   SDLoc DL(N);
24338
24339   // A vector zext_in_reg may be represented as a shuffle,
24340   // feeding into a bitcast (this represents anyext) feeding into
24341   // an and with a mask.
24342   // We'd like to try to combine that into a shuffle with zero
24343   // plus a bitcast, removing the and.
24344   if (N0.getOpcode() != ISD::BITCAST ||
24345       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
24346     return SDValue();
24347
24348   // The other side of the AND should be a splat of 2^C, where C
24349   // is the number of bits in the source type.
24350   if (N1.getOpcode() == ISD::BITCAST)
24351     N1 = N1.getOperand(0);
24352   if (N1.getOpcode() != ISD::BUILD_VECTOR)
24353     return SDValue();
24354   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
24355
24356   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
24357   EVT SrcType = Shuffle->getValueType(0);
24358
24359   // We expect a single-source shuffle
24360   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
24361     return SDValue();
24362
24363   unsigned SrcSize = SrcType.getScalarSizeInBits();
24364
24365   APInt SplatValue, SplatUndef;
24366   unsigned SplatBitSize;
24367   bool HasAnyUndefs;
24368   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
24369                                 SplatBitSize, HasAnyUndefs))
24370     return SDValue();
24371
24372   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
24373   // Make sure the splat matches the mask we expect
24374   if (SplatBitSize > ResSize ||
24375       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
24376     return SDValue();
24377
24378   // Make sure the input and output size make sense
24379   if (SrcSize >= ResSize || ResSize % SrcSize)
24380     return SDValue();
24381
24382   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
24383   // The number of u's between each two values depends on the ratio between
24384   // the source and dest type.
24385   unsigned ZextRatio = ResSize / SrcSize;
24386   bool IsZext = true;
24387   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
24388     if (i % ZextRatio) {
24389       if (Shuffle->getMaskElt(i) > 0) {
24390         // Expected undef
24391         IsZext = false;
24392         break;
24393       }
24394     } else {
24395       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
24396         // Expected element number
24397         IsZext = false;
24398         break;
24399       }
24400     }
24401   }
24402
24403   if (!IsZext)
24404     return SDValue();
24405
24406   // Ok, perform the transformation - replace the shuffle with
24407   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24408   // (instead of undef) where the k elements come from the zero vector.
24409   SmallVector<int, 8> Mask;
24410   unsigned NumElems = SrcType.getVectorNumElements();
24411   for (unsigned i = 0; i < NumElems; ++i)
24412     if (i % ZextRatio)
24413       Mask.push_back(NumElems);
24414     else
24415       Mask.push_back(i / ZextRatio);
24416
24417   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24418     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24419   return DAG.getBitcast(N0.getValueType(), NewShuffle);
24420 }
24421
24422 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24423                                  TargetLowering::DAGCombinerInfo &DCI,
24424                                  const X86Subtarget *Subtarget) {
24425   if (DCI.isBeforeLegalizeOps())
24426     return SDValue();
24427
24428   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24429     return Zext;
24430
24431   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24432     return R;
24433
24434   EVT VT = N->getValueType(0);
24435   SDValue N0 = N->getOperand(0);
24436   SDValue N1 = N->getOperand(1);
24437   SDLoc DL(N);
24438
24439   // Create BEXTR instructions
24440   // BEXTR is ((X >> imm) & (2**size-1))
24441   if (VT == MVT::i32 || VT == MVT::i64) {
24442     // Check for BEXTR.
24443     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24444         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24445       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24446       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24447       if (MaskNode && ShiftNode) {
24448         uint64_t Mask = MaskNode->getZExtValue();
24449         uint64_t Shift = ShiftNode->getZExtValue();
24450         if (isMask_64(Mask)) {
24451           uint64_t MaskSize = countPopulation(Mask);
24452           if (Shift + MaskSize <= VT.getSizeInBits())
24453             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24454                                DAG.getConstant(Shift | (MaskSize << 8), DL,
24455                                                VT));
24456         }
24457       }
24458     } // BEXTR
24459
24460     return SDValue();
24461   }
24462
24463   // Want to form ANDNP nodes:
24464   // 1) In the hopes of then easily combining them with OR and AND nodes
24465   //    to form PBLEND/PSIGN.
24466   // 2) To match ANDN packed intrinsics
24467   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24468     return SDValue();
24469
24470   // Check LHS for vnot
24471   if (N0.getOpcode() == ISD::XOR &&
24472       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24473       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24474     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24475
24476   // Check RHS for vnot
24477   if (N1.getOpcode() == ISD::XOR &&
24478       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24479       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24480     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24481
24482   return SDValue();
24483 }
24484
24485 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24486                                 TargetLowering::DAGCombinerInfo &DCI,
24487                                 const X86Subtarget *Subtarget) {
24488   if (DCI.isBeforeLegalizeOps())
24489     return SDValue();
24490
24491   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24492     return R;
24493
24494   SDValue N0 = N->getOperand(0);
24495   SDValue N1 = N->getOperand(1);
24496   EVT VT = N->getValueType(0);
24497
24498   // look for psign/blend
24499   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24500     if (!Subtarget->hasSSSE3() ||
24501         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24502       return SDValue();
24503
24504     // Canonicalize pandn to RHS
24505     if (N0.getOpcode() == X86ISD::ANDNP)
24506       std::swap(N0, N1);
24507     // or (and (m, y), (pandn m, x))
24508     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24509       SDValue Mask = N1.getOperand(0);
24510       SDValue X    = N1.getOperand(1);
24511       SDValue Y;
24512       if (N0.getOperand(0) == Mask)
24513         Y = N0.getOperand(1);
24514       if (N0.getOperand(1) == Mask)
24515         Y = N0.getOperand(0);
24516
24517       // Check to see if the mask appeared in both the AND and ANDNP and
24518       if (!Y.getNode())
24519         return SDValue();
24520
24521       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24522       // Look through mask bitcast.
24523       if (Mask.getOpcode() == ISD::BITCAST)
24524         Mask = Mask.getOperand(0);
24525       if (X.getOpcode() == ISD::BITCAST)
24526         X = X.getOperand(0);
24527       if (Y.getOpcode() == ISD::BITCAST)
24528         Y = Y.getOperand(0);
24529
24530       EVT MaskVT = Mask.getValueType();
24531
24532       // Validate that the Mask operand is a vector sra node.
24533       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24534       // there is no psrai.b
24535       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24536       unsigned SraAmt = ~0;
24537       if (Mask.getOpcode() == ISD::SRA) {
24538         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24539           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24540             SraAmt = AmtConst->getZExtValue();
24541       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24542         SDValue SraC = Mask.getOperand(1);
24543         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24544       }
24545       if ((SraAmt + 1) != EltBits)
24546         return SDValue();
24547
24548       SDLoc DL(N);
24549
24550       // Now we know we at least have a plendvb with the mask val.  See if
24551       // we can form a psignb/w/d.
24552       // psign = x.type == y.type == mask.type && y = sub(0, x);
24553       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24554           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24555           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24556         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24557                "Unsupported VT for PSIGN");
24558         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24559         return DAG.getBitcast(VT, Mask);
24560       }
24561       // PBLENDVB only available on SSE 4.1
24562       if (!Subtarget->hasSSE41())
24563         return SDValue();
24564
24565       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24566
24567       X = DAG.getBitcast(BlendVT, X);
24568       Y = DAG.getBitcast(BlendVT, Y);
24569       Mask = DAG.getBitcast(BlendVT, Mask);
24570       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24571       return DAG.getBitcast(VT, Mask);
24572     }
24573   }
24574
24575   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24576     return SDValue();
24577
24578   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24579   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24580
24581   // SHLD/SHRD instructions have lower register pressure, but on some
24582   // platforms they have higher latency than the equivalent
24583   // series of shifts/or that would otherwise be generated.
24584   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24585   // have higher latencies and we are not optimizing for size.
24586   if (!OptForSize && Subtarget->isSHLDSlow())
24587     return SDValue();
24588
24589   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24590     std::swap(N0, N1);
24591   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24592     return SDValue();
24593   if (!N0.hasOneUse() || !N1.hasOneUse())
24594     return SDValue();
24595
24596   SDValue ShAmt0 = N0.getOperand(1);
24597   if (ShAmt0.getValueType() != MVT::i8)
24598     return SDValue();
24599   SDValue ShAmt1 = N1.getOperand(1);
24600   if (ShAmt1.getValueType() != MVT::i8)
24601     return SDValue();
24602   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24603     ShAmt0 = ShAmt0.getOperand(0);
24604   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24605     ShAmt1 = ShAmt1.getOperand(0);
24606
24607   SDLoc DL(N);
24608   unsigned Opc = X86ISD::SHLD;
24609   SDValue Op0 = N0.getOperand(0);
24610   SDValue Op1 = N1.getOperand(0);
24611   if (ShAmt0.getOpcode() == ISD::SUB) {
24612     Opc = X86ISD::SHRD;
24613     std::swap(Op0, Op1);
24614     std::swap(ShAmt0, ShAmt1);
24615   }
24616
24617   unsigned Bits = VT.getSizeInBits();
24618   if (ShAmt1.getOpcode() == ISD::SUB) {
24619     SDValue Sum = ShAmt1.getOperand(0);
24620     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24621       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24622       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24623         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24624       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24625         return DAG.getNode(Opc, DL, VT,
24626                            Op0, Op1,
24627                            DAG.getNode(ISD::TRUNCATE, DL,
24628                                        MVT::i8, ShAmt0));
24629     }
24630   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24631     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24632     if (ShAmt0C &&
24633         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24634       return DAG.getNode(Opc, DL, VT,
24635                          N0.getOperand(0), N1.getOperand(0),
24636                          DAG.getNode(ISD::TRUNCATE, DL,
24637                                        MVT::i8, ShAmt0));
24638   }
24639
24640   return SDValue();
24641 }
24642
24643 // Generate NEG and CMOV for integer abs.
24644 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24645   EVT VT = N->getValueType(0);
24646
24647   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24648   // 8-bit integer abs to NEG and CMOV.
24649   if (VT.isInteger() && VT.getSizeInBits() == 8)
24650     return SDValue();
24651
24652   SDValue N0 = N->getOperand(0);
24653   SDValue N1 = N->getOperand(1);
24654   SDLoc DL(N);
24655
24656   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24657   // and change it to SUB and CMOV.
24658   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24659       N0.getOpcode() == ISD::ADD &&
24660       N0.getOperand(1) == N1 &&
24661       N1.getOpcode() == ISD::SRA &&
24662       N1.getOperand(0) == N0.getOperand(0))
24663     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24664       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24665         // Generate SUB & CMOV.
24666         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24667                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24668
24669         SDValue Ops[] = { N0.getOperand(0), Neg,
24670                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24671                           SDValue(Neg.getNode(), 1) };
24672         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24673       }
24674   return SDValue();
24675 }
24676
24677 // Try to turn tests against the signbit in the form of:
24678 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24679 // into:
24680 //   SETGT(X, -1)
24681 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24682   // This is only worth doing if the output type is i8.
24683   if (N->getValueType(0) != MVT::i8)
24684     return SDValue();
24685
24686   SDValue N0 = N->getOperand(0);
24687   SDValue N1 = N->getOperand(1);
24688
24689   // We should be performing an xor against a truncated shift.
24690   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24691     return SDValue();
24692
24693   // Make sure we are performing an xor against one.
24694   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24695     return SDValue();
24696
24697   // SetCC on x86 zero extends so only act on this if it's a logical shift.
24698   SDValue Shift = N0.getOperand(0);
24699   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24700     return SDValue();
24701
24702   // Make sure we are truncating from one of i16, i32 or i64.
24703   EVT ShiftTy = Shift.getValueType();
24704   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24705     return SDValue();
24706
24707   // Make sure the shift amount extracts the sign bit.
24708   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24709       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24710     return SDValue();
24711
24712   // Create a greater-than comparison against -1.
24713   // N.B. Using SETGE against 0 works but we want a canonical looking
24714   // comparison, using SETGT matches up with what TranslateX86CC.
24715   SDLoc DL(N);
24716   SDValue ShiftOp = Shift.getOperand(0);
24717   EVT ShiftOpTy = ShiftOp.getValueType();
24718   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24719                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24720   return Cond;
24721 }
24722
24723 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24724                                  TargetLowering::DAGCombinerInfo &DCI,
24725                                  const X86Subtarget *Subtarget) {
24726   if (DCI.isBeforeLegalizeOps())
24727     return SDValue();
24728
24729   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24730     return RV;
24731
24732   if (Subtarget->hasCMov())
24733     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24734       return RV;
24735
24736   return SDValue();
24737 }
24738
24739 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24740 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24741                                   TargetLowering::DAGCombinerInfo &DCI,
24742                                   const X86Subtarget *Subtarget) {
24743   LoadSDNode *Ld = cast<LoadSDNode>(N);
24744   EVT RegVT = Ld->getValueType(0);
24745   EVT MemVT = Ld->getMemoryVT();
24746   SDLoc dl(Ld);
24747   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24748
24749   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24750   // into two 16-byte operations.
24751   ISD::LoadExtType Ext = Ld->getExtensionType();
24752   bool Fast;
24753   unsigned AddressSpace = Ld->getAddressSpace();
24754   unsigned Alignment = Ld->getAlignment();
24755   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
24756       Ext == ISD::NON_EXTLOAD &&
24757       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
24758                              AddressSpace, Alignment, &Fast) && !Fast) {
24759     unsigned NumElems = RegVT.getVectorNumElements();
24760     if (NumElems < 2)
24761       return SDValue();
24762
24763     SDValue Ptr = Ld->getBasePtr();
24764     SDValue Increment =
24765         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24766
24767     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24768                                   NumElems/2);
24769     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24770                                 Ld->getPointerInfo(), Ld->isVolatile(),
24771                                 Ld->isNonTemporal(), Ld->isInvariant(),
24772                                 Alignment);
24773     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24774     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24775                                 Ld->getPointerInfo(), Ld->isVolatile(),
24776                                 Ld->isNonTemporal(), Ld->isInvariant(),
24777                                 std::min(16U, Alignment));
24778     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24779                              Load1.getValue(1),
24780                              Load2.getValue(1));
24781
24782     SDValue NewVec = DAG.getUNDEF(RegVT);
24783     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24784     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24785     return DCI.CombineTo(N, NewVec, TF, true);
24786   }
24787
24788   return SDValue();
24789 }
24790
24791 /// PerformMLOADCombine - Resolve extending loads
24792 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24793                                    TargetLowering::DAGCombinerInfo &DCI,
24794                                    const X86Subtarget *Subtarget) {
24795   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24796   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24797     return SDValue();
24798
24799   EVT VT = Mld->getValueType(0);
24800   unsigned NumElems = VT.getVectorNumElements();
24801   EVT LdVT = Mld->getMemoryVT();
24802   SDLoc dl(Mld);
24803
24804   assert(LdVT != VT && "Cannot extend to the same type");
24805   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24806   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24807   // From, To sizes and ElemCount must be pow of two
24808   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24809     "Unexpected size for extending masked load");
24810
24811   unsigned SizeRatio  = ToSz / FromSz;
24812   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24813
24814   // Create a type on which we perform the shuffle
24815   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24816           LdVT.getScalarType(), NumElems*SizeRatio);
24817   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24818
24819   // Convert Src0 value
24820   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24821   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24822     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24823     for (unsigned i = 0; i != NumElems; ++i)
24824       ShuffleVec[i] = i * SizeRatio;
24825
24826     // Can't shuffle using an illegal type.
24827     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24828             && "WideVecVT should be legal");
24829     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24830                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24831   }
24832   // Prepare the new mask
24833   SDValue NewMask;
24834   SDValue Mask = Mld->getMask();
24835   if (Mask.getValueType() == VT) {
24836     // Mask and original value have the same type
24837     NewMask = DAG.getBitcast(WideVecVT, Mask);
24838     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24839     for (unsigned i = 0; i != NumElems; ++i)
24840       ShuffleVec[i] = i * SizeRatio;
24841     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24842       ShuffleVec[i] = NumElems*SizeRatio;
24843     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24844                                    DAG.getConstant(0, dl, WideVecVT),
24845                                    &ShuffleVec[0]);
24846   }
24847   else {
24848     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24849     unsigned WidenNumElts = NumElems*SizeRatio;
24850     unsigned MaskNumElts = VT.getVectorNumElements();
24851     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24852                                      WidenNumElts);
24853
24854     unsigned NumConcat = WidenNumElts / MaskNumElts;
24855     SmallVector<SDValue, 16> Ops(NumConcat);
24856     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24857     Ops[0] = Mask;
24858     for (unsigned i = 1; i != NumConcat; ++i)
24859       Ops[i] = ZeroVal;
24860
24861     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24862   }
24863
24864   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24865                                      Mld->getBasePtr(), NewMask, WideSrc0,
24866                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24867                                      ISD::NON_EXTLOAD);
24868   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24869   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24870
24871 }
24872 /// PerformMSTORECombine - Resolve truncating stores
24873 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24874                                     const X86Subtarget *Subtarget) {
24875   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24876   if (!Mst->isTruncatingStore())
24877     return SDValue();
24878
24879   EVT VT = Mst->getValue().getValueType();
24880   unsigned NumElems = VT.getVectorNumElements();
24881   EVT StVT = Mst->getMemoryVT();
24882   SDLoc dl(Mst);
24883
24884   assert(StVT != VT && "Cannot truncate to the same type");
24885   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24886   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24887
24888   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24889
24890   // The truncating store is legal in some cases. For example
24891   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24892   // are designated for truncate store.
24893   // In this case we don't need any further transformations.
24894   if (TLI.isTruncStoreLegal(VT, StVT))
24895     return SDValue();
24896
24897   // From, To sizes and ElemCount must be pow of two
24898   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24899     "Unexpected size for truncating masked store");
24900   // We are going to use the original vector elt for storing.
24901   // Accumulated smaller vector elements must be a multiple of the store size.
24902   assert (((NumElems * FromSz) % ToSz) == 0 &&
24903           "Unexpected ratio for truncating masked store");
24904
24905   unsigned SizeRatio  = FromSz / ToSz;
24906   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24907
24908   // Create a type on which we perform the shuffle
24909   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24910           StVT.getScalarType(), NumElems*SizeRatio);
24911
24912   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24913
24914   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24915   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24916   for (unsigned i = 0; i != NumElems; ++i)
24917     ShuffleVec[i] = i * SizeRatio;
24918
24919   // Can't shuffle using an illegal type.
24920   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24921           && "WideVecVT should be legal");
24922
24923   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24924                                         DAG.getUNDEF(WideVecVT),
24925                                         &ShuffleVec[0]);
24926
24927   SDValue NewMask;
24928   SDValue Mask = Mst->getMask();
24929   if (Mask.getValueType() == VT) {
24930     // Mask and original value have the same type
24931     NewMask = DAG.getBitcast(WideVecVT, Mask);
24932     for (unsigned i = 0; i != NumElems; ++i)
24933       ShuffleVec[i] = i * SizeRatio;
24934     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24935       ShuffleVec[i] = NumElems*SizeRatio;
24936     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24937                                    DAG.getConstant(0, dl, WideVecVT),
24938                                    &ShuffleVec[0]);
24939   }
24940   else {
24941     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24942     unsigned WidenNumElts = NumElems*SizeRatio;
24943     unsigned MaskNumElts = VT.getVectorNumElements();
24944     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24945                                      WidenNumElts);
24946
24947     unsigned NumConcat = WidenNumElts / MaskNumElts;
24948     SmallVector<SDValue, 16> Ops(NumConcat);
24949     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24950     Ops[0] = Mask;
24951     for (unsigned i = 1; i != NumConcat; ++i)
24952       Ops[i] = ZeroVal;
24953
24954     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24955   }
24956
24957   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24958                             NewMask, StVT, Mst->getMemOperand(), false);
24959 }
24960 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24961 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24962                                    const X86Subtarget *Subtarget) {
24963   StoreSDNode *St = cast<StoreSDNode>(N);
24964   EVT VT = St->getValue().getValueType();
24965   EVT StVT = St->getMemoryVT();
24966   SDLoc dl(St);
24967   SDValue StoredVal = St->getOperand(1);
24968   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24969
24970   // If we are saving a concatenation of two XMM registers and 32-byte stores
24971   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24972   bool Fast;
24973   unsigned AddressSpace = St->getAddressSpace();
24974   unsigned Alignment = St->getAlignment();
24975   if (VT.is256BitVector() && StVT == VT &&
24976       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
24977                              AddressSpace, Alignment, &Fast) && !Fast) {
24978     unsigned NumElems = VT.getVectorNumElements();
24979     if (NumElems < 2)
24980       return SDValue();
24981
24982     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24983     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24984
24985     SDValue Stride =
24986         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24987     SDValue Ptr0 = St->getBasePtr();
24988     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24989
24990     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24991                                 St->getPointerInfo(), St->isVolatile(),
24992                                 St->isNonTemporal(), Alignment);
24993     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24994                                 St->getPointerInfo(), St->isVolatile(),
24995                                 St->isNonTemporal(),
24996                                 std::min(16U, Alignment));
24997     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24998   }
24999
25000   // Optimize trunc store (of multiple scalars) to shuffle and store.
25001   // First, pack all of the elements in one place. Next, store to memory
25002   // in fewer chunks.
25003   if (St->isTruncatingStore() && VT.isVector()) {
25004     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25005     unsigned NumElems = VT.getVectorNumElements();
25006     assert(StVT != VT && "Cannot truncate to the same type");
25007     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25008     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25009
25010     // The truncating store is legal in some cases. For example
25011     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25012     // are designated for truncate store.
25013     // In this case we don't need any further transformations.
25014     if (TLI.isTruncStoreLegal(VT, StVT))
25015       return SDValue();
25016
25017     // From, To sizes and ElemCount must be pow of two
25018     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
25019     // We are going to use the original vector elt for storing.
25020     // Accumulated smaller vector elements must be a multiple of the store size.
25021     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
25022
25023     unsigned SizeRatio  = FromSz / ToSz;
25024
25025     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25026
25027     // Create a type on which we perform the shuffle
25028     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25029             StVT.getScalarType(), NumElems*SizeRatio);
25030
25031     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25032
25033     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
25034     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
25035     for (unsigned i = 0; i != NumElems; ++i)
25036       ShuffleVec[i] = i * SizeRatio;
25037
25038     // Can't shuffle using an illegal type.
25039     if (!TLI.isTypeLegal(WideVecVT))
25040       return SDValue();
25041
25042     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25043                                          DAG.getUNDEF(WideVecVT),
25044                                          &ShuffleVec[0]);
25045     // At this point all of the data is stored at the bottom of the
25046     // register. We now need to save it to mem.
25047
25048     // Find the largest store unit
25049     MVT StoreType = MVT::i8;
25050     for (MVT Tp : MVT::integer_valuetypes()) {
25051       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
25052         StoreType = Tp;
25053     }
25054
25055     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
25056     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
25057         (64 <= NumElems * ToSz))
25058       StoreType = MVT::f64;
25059
25060     // Bitcast the original vector into a vector of store-size units
25061     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
25062             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
25063     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
25064     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
25065     SmallVector<SDValue, 8> Chains;
25066     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
25067                                         TLI.getPointerTy(DAG.getDataLayout()));
25068     SDValue Ptr = St->getBasePtr();
25069
25070     // Perform one or more big stores into memory.
25071     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
25072       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
25073                                    StoreType, ShuffWide,
25074                                    DAG.getIntPtrConstant(i, dl));
25075       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
25076                                 St->getPointerInfo(), St->isVolatile(),
25077                                 St->isNonTemporal(), St->getAlignment());
25078       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25079       Chains.push_back(Ch);
25080     }
25081
25082     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
25083   }
25084
25085   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
25086   // the FP state in cases where an emms may be missing.
25087   // A preferable solution to the general problem is to figure out the right
25088   // places to insert EMMS.  This qualifies as a quick hack.
25089
25090   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
25091   if (VT.getSizeInBits() != 64)
25092     return SDValue();
25093
25094   const Function *F = DAG.getMachineFunction().getFunction();
25095   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
25096   bool F64IsLegal =
25097       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
25098   if ((VT.isVector() ||
25099        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
25100       isa<LoadSDNode>(St->getValue()) &&
25101       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
25102       St->getChain().hasOneUse() && !St->isVolatile()) {
25103     SDNode* LdVal = St->getValue().getNode();
25104     LoadSDNode *Ld = nullptr;
25105     int TokenFactorIndex = -1;
25106     SmallVector<SDValue, 8> Ops;
25107     SDNode* ChainVal = St->getChain().getNode();
25108     // Must be a store of a load.  We currently handle two cases:  the load
25109     // is a direct child, and it's under an intervening TokenFactor.  It is
25110     // possible to dig deeper under nested TokenFactors.
25111     if (ChainVal == LdVal)
25112       Ld = cast<LoadSDNode>(St->getChain());
25113     else if (St->getValue().hasOneUse() &&
25114              ChainVal->getOpcode() == ISD::TokenFactor) {
25115       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
25116         if (ChainVal->getOperand(i).getNode() == LdVal) {
25117           TokenFactorIndex = i;
25118           Ld = cast<LoadSDNode>(St->getValue());
25119         } else
25120           Ops.push_back(ChainVal->getOperand(i));
25121       }
25122     }
25123
25124     if (!Ld || !ISD::isNormalLoad(Ld))
25125       return SDValue();
25126
25127     // If this is not the MMX case, i.e. we are just turning i64 load/store
25128     // into f64 load/store, avoid the transformation if there are multiple
25129     // uses of the loaded value.
25130     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
25131       return SDValue();
25132
25133     SDLoc LdDL(Ld);
25134     SDLoc StDL(N);
25135     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
25136     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
25137     // pair instead.
25138     if (Subtarget->is64Bit() || F64IsLegal) {
25139       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
25140       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
25141                                   Ld->getPointerInfo(), Ld->isVolatile(),
25142                                   Ld->isNonTemporal(), Ld->isInvariant(),
25143                                   Ld->getAlignment());
25144       SDValue NewChain = NewLd.getValue(1);
25145       if (TokenFactorIndex != -1) {
25146         Ops.push_back(NewChain);
25147         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25148       }
25149       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
25150                           St->getPointerInfo(),
25151                           St->isVolatile(), St->isNonTemporal(),
25152                           St->getAlignment());
25153     }
25154
25155     // Otherwise, lower to two pairs of 32-bit loads / stores.
25156     SDValue LoAddr = Ld->getBasePtr();
25157     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
25158                                  DAG.getConstant(4, LdDL, MVT::i32));
25159
25160     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
25161                                Ld->getPointerInfo(),
25162                                Ld->isVolatile(), Ld->isNonTemporal(),
25163                                Ld->isInvariant(), Ld->getAlignment());
25164     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
25165                                Ld->getPointerInfo().getWithOffset(4),
25166                                Ld->isVolatile(), Ld->isNonTemporal(),
25167                                Ld->isInvariant(),
25168                                MinAlign(Ld->getAlignment(), 4));
25169
25170     SDValue NewChain = LoLd.getValue(1);
25171     if (TokenFactorIndex != -1) {
25172       Ops.push_back(LoLd);
25173       Ops.push_back(HiLd);
25174       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25175     }
25176
25177     LoAddr = St->getBasePtr();
25178     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
25179                          DAG.getConstant(4, StDL, MVT::i32));
25180
25181     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
25182                                 St->getPointerInfo(),
25183                                 St->isVolatile(), St->isNonTemporal(),
25184                                 St->getAlignment());
25185     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
25186                                 St->getPointerInfo().getWithOffset(4),
25187                                 St->isVolatile(),
25188                                 St->isNonTemporal(),
25189                                 MinAlign(St->getAlignment(), 4));
25190     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
25191   }
25192
25193   // This is similar to the above case, but here we handle a scalar 64-bit
25194   // integer store that is extracted from a vector on a 32-bit target.
25195   // If we have SSE2, then we can treat it like a floating-point double
25196   // to get past legalization. The execution dependencies fixup pass will
25197   // choose the optimal machine instruction for the store if this really is
25198   // an integer or v2f32 rather than an f64.
25199   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
25200       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
25201     SDValue OldExtract = St->getOperand(1);
25202     SDValue ExtOp0 = OldExtract.getOperand(0);
25203     unsigned VecSize = ExtOp0.getValueSizeInBits();
25204     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
25205     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
25206     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
25207                                      BitCast, OldExtract.getOperand(1));
25208     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
25209                         St->getPointerInfo(), St->isVolatile(),
25210                         St->isNonTemporal(), St->getAlignment());
25211   }
25212
25213   return SDValue();
25214 }
25215
25216 /// Return 'true' if this vector operation is "horizontal"
25217 /// and return the operands for the horizontal operation in LHS and RHS.  A
25218 /// horizontal operation performs the binary operation on successive elements
25219 /// of its first operand, then on successive elements of its second operand,
25220 /// returning the resulting values in a vector.  For example, if
25221 ///   A = < float a0, float a1, float a2, float a3 >
25222 /// and
25223 ///   B = < float b0, float b1, float b2, float b3 >
25224 /// then the result of doing a horizontal operation on A and B is
25225 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
25226 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
25227 /// A horizontal-op B, for some already available A and B, and if so then LHS is
25228 /// set to A, RHS to B, and the routine returns 'true'.
25229 /// Note that the binary operation should have the property that if one of the
25230 /// operands is UNDEF then the result is UNDEF.
25231 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
25232   // Look for the following pattern: if
25233   //   A = < float a0, float a1, float a2, float a3 >
25234   //   B = < float b0, float b1, float b2, float b3 >
25235   // and
25236   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
25237   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
25238   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
25239   // which is A horizontal-op B.
25240
25241   // At least one of the operands should be a vector shuffle.
25242   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
25243       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
25244     return false;
25245
25246   MVT VT = LHS.getSimpleValueType();
25247
25248   assert((VT.is128BitVector() || VT.is256BitVector()) &&
25249          "Unsupported vector type for horizontal add/sub");
25250
25251   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
25252   // operate independently on 128-bit lanes.
25253   unsigned NumElts = VT.getVectorNumElements();
25254   unsigned NumLanes = VT.getSizeInBits()/128;
25255   unsigned NumLaneElts = NumElts / NumLanes;
25256   assert((NumLaneElts % 2 == 0) &&
25257          "Vector type should have an even number of elements in each lane");
25258   unsigned HalfLaneElts = NumLaneElts/2;
25259
25260   // View LHS in the form
25261   //   LHS = VECTOR_SHUFFLE A, B, LMask
25262   // If LHS is not a shuffle then pretend it is the shuffle
25263   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
25264   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
25265   // type VT.
25266   SDValue A, B;
25267   SmallVector<int, 16> LMask(NumElts);
25268   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25269     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
25270       A = LHS.getOperand(0);
25271     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
25272       B = LHS.getOperand(1);
25273     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
25274     std::copy(Mask.begin(), Mask.end(), LMask.begin());
25275   } else {
25276     if (LHS.getOpcode() != ISD::UNDEF)
25277       A = LHS;
25278     for (unsigned i = 0; i != NumElts; ++i)
25279       LMask[i] = i;
25280   }
25281
25282   // Likewise, view RHS in the form
25283   //   RHS = VECTOR_SHUFFLE C, D, RMask
25284   SDValue C, D;
25285   SmallVector<int, 16> RMask(NumElts);
25286   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25287     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
25288       C = RHS.getOperand(0);
25289     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
25290       D = RHS.getOperand(1);
25291     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
25292     std::copy(Mask.begin(), Mask.end(), RMask.begin());
25293   } else {
25294     if (RHS.getOpcode() != ISD::UNDEF)
25295       C = RHS;
25296     for (unsigned i = 0; i != NumElts; ++i)
25297       RMask[i] = i;
25298   }
25299
25300   // Check that the shuffles are both shuffling the same vectors.
25301   if (!(A == C && B == D) && !(A == D && B == C))
25302     return false;
25303
25304   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
25305   if (!A.getNode() && !B.getNode())
25306     return false;
25307
25308   // If A and B occur in reverse order in RHS, then "swap" them (which means
25309   // rewriting the mask).
25310   if (A != C)
25311     ShuffleVectorSDNode::commuteMask(RMask);
25312
25313   // At this point LHS and RHS are equivalent to
25314   //   LHS = VECTOR_SHUFFLE A, B, LMask
25315   //   RHS = VECTOR_SHUFFLE A, B, RMask
25316   // Check that the masks correspond to performing a horizontal operation.
25317   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
25318     for (unsigned i = 0; i != NumLaneElts; ++i) {
25319       int LIdx = LMask[i+l], RIdx = RMask[i+l];
25320
25321       // Ignore any UNDEF components.
25322       if (LIdx < 0 || RIdx < 0 ||
25323           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
25324           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
25325         continue;
25326
25327       // Check that successive elements are being operated on.  If not, this is
25328       // not a horizontal operation.
25329       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
25330       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
25331       if (!(LIdx == Index && RIdx == Index + 1) &&
25332           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
25333         return false;
25334     }
25335   }
25336
25337   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
25338   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
25339   return true;
25340 }
25341
25342 /// Do target-specific dag combines on floating point adds.
25343 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
25344                                   const X86Subtarget *Subtarget) {
25345   EVT VT = N->getValueType(0);
25346   SDValue LHS = N->getOperand(0);
25347   SDValue RHS = N->getOperand(1);
25348
25349   // Try to synthesize horizontal adds from adds of shuffles.
25350   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25351        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25352       isHorizontalBinOp(LHS, RHS, true))
25353     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
25354   return SDValue();
25355 }
25356
25357 /// Do target-specific dag combines on floating point subs.
25358 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
25359                                   const X86Subtarget *Subtarget) {
25360   EVT VT = N->getValueType(0);
25361   SDValue LHS = N->getOperand(0);
25362   SDValue RHS = N->getOperand(1);
25363
25364   // Try to synthesize horizontal subs from subs of shuffles.
25365   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25366        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25367       isHorizontalBinOp(LHS, RHS, false))
25368     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
25369   return SDValue();
25370 }
25371
25372 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
25373 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
25374                                  const X86Subtarget *Subtarget) {
25375   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
25376
25377   // F[X]OR(0.0, x) -> x
25378   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25379     if (C->getValueAPF().isPosZero())
25380       return N->getOperand(1);
25381
25382   // F[X]OR(x, 0.0) -> x
25383   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25384     if (C->getValueAPF().isPosZero())
25385       return N->getOperand(0);
25386
25387   EVT VT = N->getValueType(0);
25388   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
25389     SDLoc dl(N);
25390     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
25391     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
25392
25393     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
25394     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
25395     unsigned IntOpcode = (N->getOpcode() == X86ISD::FOR) ? ISD::OR : ISD::XOR;
25396     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
25397     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
25398   }
25399   return SDValue();
25400 }
25401
25402 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
25403 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
25404   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
25405
25406   // Only perform optimizations if UnsafeMath is used.
25407   if (!DAG.getTarget().Options.UnsafeFPMath)
25408     return SDValue();
25409
25410   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25411   // into FMINC and FMAXC, which are Commutative operations.
25412   unsigned NewOp = 0;
25413   switch (N->getOpcode()) {
25414     default: llvm_unreachable("unknown opcode");
25415     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
25416     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
25417   }
25418
25419   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25420                      N->getOperand(0), N->getOperand(1));
25421 }
25422
25423 /// Do target-specific dag combines on X86ISD::FAND nodes.
25424 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25425   // FAND(0.0, x) -> 0.0
25426   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25427     if (C->getValueAPF().isPosZero())
25428       return N->getOperand(0);
25429
25430   // FAND(x, 0.0) -> 0.0
25431   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25432     if (C->getValueAPF().isPosZero())
25433       return N->getOperand(1);
25434
25435   return SDValue();
25436 }
25437
25438 /// Do target-specific dag combines on X86ISD::FANDN nodes
25439 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25440   // FANDN(0.0, x) -> x
25441   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25442     if (C->getValueAPF().isPosZero())
25443       return N->getOperand(1);
25444
25445   // FANDN(x, 0.0) -> 0.0
25446   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25447     if (C->getValueAPF().isPosZero())
25448       return N->getOperand(1);
25449
25450   return SDValue();
25451 }
25452
25453 static SDValue PerformBTCombine(SDNode *N,
25454                                 SelectionDAG &DAG,
25455                                 TargetLowering::DAGCombinerInfo &DCI) {
25456   // BT ignores high bits in the bit index operand.
25457   SDValue Op1 = N->getOperand(1);
25458   if (Op1.hasOneUse()) {
25459     unsigned BitWidth = Op1.getValueSizeInBits();
25460     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25461     APInt KnownZero, KnownOne;
25462     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25463                                           !DCI.isBeforeLegalizeOps());
25464     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25465     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25466         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25467       DCI.CommitTargetLoweringOpt(TLO);
25468   }
25469   return SDValue();
25470 }
25471
25472 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25473   SDValue Op = N->getOperand(0);
25474   if (Op.getOpcode() == ISD::BITCAST)
25475     Op = Op.getOperand(0);
25476   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25477   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25478       VT.getVectorElementType().getSizeInBits() ==
25479       OpVT.getVectorElementType().getSizeInBits()) {
25480     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25481   }
25482   return SDValue();
25483 }
25484
25485 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25486                                                const X86Subtarget *Subtarget) {
25487   EVT VT = N->getValueType(0);
25488   if (!VT.isVector())
25489     return SDValue();
25490
25491   SDValue N0 = N->getOperand(0);
25492   SDValue N1 = N->getOperand(1);
25493   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25494   SDLoc dl(N);
25495
25496   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25497   // both SSE and AVX2 since there is no sign-extended shift right
25498   // operation on a vector with 64-bit elements.
25499   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25500   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25501   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25502       N0.getOpcode() == ISD::SIGN_EXTEND)) {
25503     SDValue N00 = N0.getOperand(0);
25504
25505     // EXTLOAD has a better solution on AVX2,
25506     // it may be replaced with X86ISD::VSEXT node.
25507     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25508       if (!ISD::isNormalLoad(N00.getNode()))
25509         return SDValue();
25510
25511     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25512         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25513                                   N00, N1);
25514       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25515     }
25516   }
25517   return SDValue();
25518 }
25519
25520 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25521                                   TargetLowering::DAGCombinerInfo &DCI,
25522                                   const X86Subtarget *Subtarget) {
25523   SDValue N0 = N->getOperand(0);
25524   EVT VT = N->getValueType(0);
25525   EVT SVT = VT.getScalarType();
25526   EVT InVT = N0.getValueType();
25527   EVT InSVT = InVT.getScalarType();
25528   SDLoc DL(N);
25529
25530   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25531   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25532   // This exposes the sext to the sdivrem lowering, so that it directly extends
25533   // from AH (which we otherwise need to do contortions to access).
25534   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25535       InVT == MVT::i8 && VT == MVT::i32) {
25536     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25537     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25538                             N0.getOperand(0), N0.getOperand(1));
25539     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25540     return R.getValue(1);
25541   }
25542
25543   if (!DCI.isBeforeLegalizeOps()) {
25544     if (InVT == MVT::i1) {
25545       SDValue Zero = DAG.getConstant(0, DL, VT);
25546       SDValue AllOnes =
25547         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25548       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25549     }
25550     return SDValue();
25551   }
25552
25553   if (VT.isVector() && Subtarget->hasSSE2()) {
25554     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25555       EVT InVT = N.getValueType();
25556       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25557                                    Size / InVT.getScalarSizeInBits());
25558       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25559                                     DAG.getUNDEF(InVT));
25560       Opnds[0] = N;
25561       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25562     };
25563
25564     // If target-size is less than 128-bits, extend to a type that would extend
25565     // to 128 bits, extend that and extract the original target vector.
25566     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25567         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25568         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25569       unsigned Scale = 128 / VT.getSizeInBits();
25570       EVT ExVT =
25571           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25572       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25573       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25574       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25575                          DAG.getIntPtrConstant(0, DL));
25576     }
25577
25578     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25579     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25580     if (VT.getSizeInBits() == 128 &&
25581         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25582         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25583       SDValue ExOp = ExtendVecSize(DL, N0, 128);
25584       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25585     }
25586
25587     // On pre-AVX2 targets, split into 128-bit nodes of
25588     // ISD::SIGN_EXTEND_VECTOR_INREG.
25589     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25590         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25591         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25592       unsigned NumVecs = VT.getSizeInBits() / 128;
25593       unsigned NumSubElts = 128 / SVT.getSizeInBits();
25594       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25595       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25596
25597       SmallVector<SDValue, 8> Opnds;
25598       for (unsigned i = 0, Offset = 0; i != NumVecs;
25599            ++i, Offset += NumSubElts) {
25600         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25601                                      DAG.getIntPtrConstant(Offset, DL));
25602         SrcVec = ExtendVecSize(DL, SrcVec, 128);
25603         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25604         Opnds.push_back(SrcVec);
25605       }
25606       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25607     }
25608   }
25609
25610   if (!Subtarget->hasFp256())
25611     return SDValue();
25612
25613   if (VT.isVector() && VT.getSizeInBits() == 256)
25614     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25615       return R;
25616
25617   return SDValue();
25618 }
25619
25620 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25621                                  const X86Subtarget* Subtarget) {
25622   SDLoc dl(N);
25623   EVT VT = N->getValueType(0);
25624
25625   // Let legalize expand this if it isn't a legal type yet.
25626   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25627     return SDValue();
25628
25629   EVT ScalarVT = VT.getScalarType();
25630   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25631       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25632        !Subtarget->hasAVX512()))
25633     return SDValue();
25634
25635   SDValue A = N->getOperand(0);
25636   SDValue B = N->getOperand(1);
25637   SDValue C = N->getOperand(2);
25638
25639   bool NegA = (A.getOpcode() == ISD::FNEG);
25640   bool NegB = (B.getOpcode() == ISD::FNEG);
25641   bool NegC = (C.getOpcode() == ISD::FNEG);
25642
25643   // Negative multiplication when NegA xor NegB
25644   bool NegMul = (NegA != NegB);
25645   if (NegA)
25646     A = A.getOperand(0);
25647   if (NegB)
25648     B = B.getOperand(0);
25649   if (NegC)
25650     C = C.getOperand(0);
25651
25652   unsigned Opcode;
25653   if (!NegMul)
25654     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25655   else
25656     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25657
25658   return DAG.getNode(Opcode, dl, VT, A, B, C);
25659 }
25660
25661 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25662                                   TargetLowering::DAGCombinerInfo &DCI,
25663                                   const X86Subtarget *Subtarget) {
25664   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
25665   //           (and (i32 x86isd::setcc_carry), 1)
25666   // This eliminates the zext. This transformation is necessary because
25667   // ISD::SETCC is always legalized to i8.
25668   SDLoc dl(N);
25669   SDValue N0 = N->getOperand(0);
25670   EVT VT = N->getValueType(0);
25671
25672   if (N0.getOpcode() == ISD::AND &&
25673       N0.hasOneUse() &&
25674       N0.getOperand(0).hasOneUse()) {
25675     SDValue N00 = N0.getOperand(0);
25676     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25677       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25678       if (!C || C->getZExtValue() != 1)
25679         return SDValue();
25680       return DAG.getNode(ISD::AND, dl, VT,
25681                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25682                                      N00.getOperand(0), N00.getOperand(1)),
25683                          DAG.getConstant(1, dl, VT));
25684     }
25685   }
25686
25687   if (N0.getOpcode() == ISD::TRUNCATE &&
25688       N0.hasOneUse() &&
25689       N0.getOperand(0).hasOneUse()) {
25690     SDValue N00 = N0.getOperand(0);
25691     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25692       return DAG.getNode(ISD::AND, dl, VT,
25693                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25694                                      N00.getOperand(0), N00.getOperand(1)),
25695                          DAG.getConstant(1, dl, VT));
25696     }
25697   }
25698
25699   if (VT.is256BitVector())
25700     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25701       return R;
25702
25703   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25704   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25705   // This exposes the zext to the udivrem lowering, so that it directly extends
25706   // from AH (which we otherwise need to do contortions to access).
25707   if (N0.getOpcode() == ISD::UDIVREM &&
25708       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25709       (VT == MVT::i32 || VT == MVT::i64)) {
25710     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25711     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25712                             N0.getOperand(0), N0.getOperand(1));
25713     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25714     return R.getValue(1);
25715   }
25716
25717   return SDValue();
25718 }
25719
25720 // Optimize x == -y --> x+y == 0
25721 //          x != -y --> x+y != 0
25722 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25723                                       const X86Subtarget* Subtarget) {
25724   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25725   SDValue LHS = N->getOperand(0);
25726   SDValue RHS = N->getOperand(1);
25727   EVT VT = N->getValueType(0);
25728   SDLoc DL(N);
25729
25730   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25731     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25732       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25733         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25734                                    LHS.getOperand(1));
25735         return DAG.getSetCC(DL, N->getValueType(0), addV,
25736                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25737       }
25738   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25739     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25740       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25741         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25742                                    RHS.getOperand(1));
25743         return DAG.getSetCC(DL, N->getValueType(0), addV,
25744                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25745       }
25746
25747   if (VT.getScalarType() == MVT::i1 &&
25748       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25749     bool IsSEXT0 =
25750         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25751         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25752     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25753
25754     if (!IsSEXT0 || !IsVZero1) {
25755       // Swap the operands and update the condition code.
25756       std::swap(LHS, RHS);
25757       CC = ISD::getSetCCSwappedOperands(CC);
25758
25759       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25760                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25761       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25762     }
25763
25764     if (IsSEXT0 && IsVZero1) {
25765       assert(VT == LHS.getOperand(0).getValueType() &&
25766              "Uexpected operand type");
25767       if (CC == ISD::SETGT)
25768         return DAG.getConstant(0, DL, VT);
25769       if (CC == ISD::SETLE)
25770         return DAG.getConstant(1, DL, VT);
25771       if (CC == ISD::SETEQ || CC == ISD::SETGE)
25772         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25773
25774       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25775              "Unexpected condition code!");
25776       return LHS.getOperand(0);
25777     }
25778   }
25779
25780   return SDValue();
25781 }
25782
25783 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25784                                          SelectionDAG &DAG) {
25785   SDLoc dl(Load);
25786   MVT VT = Load->getSimpleValueType(0);
25787   MVT EVT = VT.getVectorElementType();
25788   SDValue Addr = Load->getOperand(1);
25789   SDValue NewAddr = DAG.getNode(
25790       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25791       DAG.getConstant(Index * EVT.getStoreSize(), dl,
25792                       Addr.getSimpleValueType()));
25793
25794   SDValue NewLoad =
25795       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25796                   DAG.getMachineFunction().getMachineMemOperand(
25797                       Load->getMemOperand(), 0, EVT.getStoreSize()));
25798   return NewLoad;
25799 }
25800
25801 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25802                                       const X86Subtarget *Subtarget) {
25803   SDLoc dl(N);
25804   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25805   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25806          "X86insertps is only defined for v4x32");
25807
25808   SDValue Ld = N->getOperand(1);
25809   if (MayFoldLoad(Ld)) {
25810     // Extract the countS bits from the immediate so we can get the proper
25811     // address when narrowing the vector load to a specific element.
25812     // When the second source op is a memory address, insertps doesn't use
25813     // countS and just gets an f32 from that address.
25814     unsigned DestIndex =
25815         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25816
25817     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25818
25819     // Create this as a scalar to vector to match the instruction pattern.
25820     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25821     // countS bits are ignored when loading from memory on insertps, which
25822     // means we don't need to explicitly set them to 0.
25823     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25824                        LoadScalarToVector, N->getOperand(2));
25825   }
25826   return SDValue();
25827 }
25828
25829 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25830   SDValue V0 = N->getOperand(0);
25831   SDValue V1 = N->getOperand(1);
25832   SDLoc DL(N);
25833   EVT VT = N->getValueType(0);
25834
25835   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25836   // operands and changing the mask to 1. This saves us a bunch of
25837   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25838   // x86InstrInfo knows how to commute this back after instruction selection
25839   // if it would help register allocation.
25840
25841   // TODO: If optimizing for size or a processor that doesn't suffer from
25842   // partial register update stalls, this should be transformed into a MOVSD
25843   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25844
25845   if (VT == MVT::v2f64)
25846     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25847       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25848         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25849         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25850       }
25851
25852   return SDValue();
25853 }
25854
25855 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25856 // as "sbb reg,reg", since it can be extended without zext and produces
25857 // an all-ones bit which is more useful than 0/1 in some cases.
25858 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25859                                MVT VT) {
25860   if (VT == MVT::i8)
25861     return DAG.getNode(ISD::AND, DL, VT,
25862                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25863                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25864                                    EFLAGS),
25865                        DAG.getConstant(1, DL, VT));
25866   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25867   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25868                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25869                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25870                                  EFLAGS));
25871 }
25872
25873 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25874 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25875                                    TargetLowering::DAGCombinerInfo &DCI,
25876                                    const X86Subtarget *Subtarget) {
25877   SDLoc DL(N);
25878   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25879   SDValue EFLAGS = N->getOperand(1);
25880
25881   if (CC == X86::COND_A) {
25882     // Try to convert COND_A into COND_B in an attempt to facilitate
25883     // materializing "setb reg".
25884     //
25885     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25886     // cannot take an immediate as its first operand.
25887     //
25888     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25889         EFLAGS.getValueType().isInteger() &&
25890         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25891       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25892                                    EFLAGS.getNode()->getVTList(),
25893                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25894       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25895       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25896     }
25897   }
25898
25899   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25900   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25901   // cases.
25902   if (CC == X86::COND_B)
25903     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25904
25905   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25906     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25907     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25908   }
25909
25910   return SDValue();
25911 }
25912
25913 // Optimize branch condition evaluation.
25914 //
25915 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25916                                     TargetLowering::DAGCombinerInfo &DCI,
25917                                     const X86Subtarget *Subtarget) {
25918   SDLoc DL(N);
25919   SDValue Chain = N->getOperand(0);
25920   SDValue Dest = N->getOperand(1);
25921   SDValue EFLAGS = N->getOperand(3);
25922   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25923
25924   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25925     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25926     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25927                        Flags);
25928   }
25929
25930   return SDValue();
25931 }
25932
25933 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25934                                                          SelectionDAG &DAG) {
25935   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25936   // optimize away operation when it's from a constant.
25937   //
25938   // The general transformation is:
25939   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25940   //       AND(VECTOR_CMP(x,y), constant2)
25941   //    constant2 = UNARYOP(constant)
25942
25943   // Early exit if this isn't a vector operation, the operand of the
25944   // unary operation isn't a bitwise AND, or if the sizes of the operations
25945   // aren't the same.
25946   EVT VT = N->getValueType(0);
25947   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25948       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25949       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25950     return SDValue();
25951
25952   // Now check that the other operand of the AND is a constant. We could
25953   // make the transformation for non-constant splats as well, but it's unclear
25954   // that would be a benefit as it would not eliminate any operations, just
25955   // perform one more step in scalar code before moving to the vector unit.
25956   if (BuildVectorSDNode *BV =
25957           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25958     // Bail out if the vector isn't a constant.
25959     if (!BV->isConstant())
25960       return SDValue();
25961
25962     // Everything checks out. Build up the new and improved node.
25963     SDLoc DL(N);
25964     EVT IntVT = BV->getValueType(0);
25965     // Create a new constant of the appropriate type for the transformed
25966     // DAG.
25967     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25968     // The AND node needs bitcasts to/from an integer vector type around it.
25969     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25970     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25971                                  N->getOperand(0)->getOperand(0), MaskConst);
25972     SDValue Res = DAG.getBitcast(VT, NewAnd);
25973     return Res;
25974   }
25975
25976   return SDValue();
25977 }
25978
25979 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25980                                         const X86Subtarget *Subtarget) {
25981   SDValue Op0 = N->getOperand(0);
25982   EVT VT = N->getValueType(0);
25983   EVT InVT = Op0.getValueType();
25984   EVT InSVT = InVT.getScalarType();
25985   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25986
25987   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25988   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25989   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25990     SDLoc dl(N);
25991     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25992                                  InVT.getVectorNumElements());
25993     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25994
25995     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25996       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25997
25998     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25999   }
26000
26001   return SDValue();
26002 }
26003
26004 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26005                                         const X86Subtarget *Subtarget) {
26006   // First try to optimize away the conversion entirely when it's
26007   // conditionally from a constant. Vectors only.
26008   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
26009     return Res;
26010
26011   // Now move on to more general possibilities.
26012   SDValue Op0 = N->getOperand(0);
26013   EVT VT = N->getValueType(0);
26014   EVT InVT = Op0.getValueType();
26015   EVT InSVT = InVT.getScalarType();
26016
26017   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
26018   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
26019   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26020     SDLoc dl(N);
26021     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26022                                  InVT.getVectorNumElements());
26023     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
26024     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26025   }
26026
26027   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
26028   // a 32-bit target where SSE doesn't support i64->FP operations.
26029   if (Op0.getOpcode() == ISD::LOAD) {
26030     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
26031     EVT LdVT = Ld->getValueType(0);
26032
26033     // This transformation is not supported if the result type is f16
26034     if (VT == MVT::f16)
26035       return SDValue();
26036
26037     if (!Ld->isVolatile() && !VT.isVector() &&
26038         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
26039         !Subtarget->is64Bit() && LdVT == MVT::i64) {
26040       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
26041           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
26042       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
26043       return FILDChain;
26044     }
26045   }
26046   return SDValue();
26047 }
26048
26049 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
26050 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
26051                                  X86TargetLowering::DAGCombinerInfo &DCI) {
26052   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
26053   // the result is either zero or one (depending on the input carry bit).
26054   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
26055   if (X86::isZeroNode(N->getOperand(0)) &&
26056       X86::isZeroNode(N->getOperand(1)) &&
26057       // We don't have a good way to replace an EFLAGS use, so only do this when
26058       // dead right now.
26059       SDValue(N, 1).use_empty()) {
26060     SDLoc DL(N);
26061     EVT VT = N->getValueType(0);
26062     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
26063     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
26064                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
26065                                            DAG.getConstant(X86::COND_B, DL,
26066                                                            MVT::i8),
26067                                            N->getOperand(2)),
26068                                DAG.getConstant(1, DL, VT));
26069     return DCI.CombineTo(N, Res1, CarryOut);
26070   }
26071
26072   return SDValue();
26073 }
26074
26075 // fold (add Y, (sete  X, 0)) -> adc  0, Y
26076 //      (add Y, (setne X, 0)) -> sbb -1, Y
26077 //      (sub (sete  X, 0), Y) -> sbb  0, Y
26078 //      (sub (setne X, 0), Y) -> adc -1, Y
26079 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
26080   SDLoc DL(N);
26081
26082   // Look through ZExts.
26083   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
26084   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
26085     return SDValue();
26086
26087   SDValue SetCC = Ext.getOperand(0);
26088   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
26089     return SDValue();
26090
26091   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
26092   if (CC != X86::COND_E && CC != X86::COND_NE)
26093     return SDValue();
26094
26095   SDValue Cmp = SetCC.getOperand(1);
26096   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
26097       !X86::isZeroNode(Cmp.getOperand(1)) ||
26098       !Cmp.getOperand(0).getValueType().isInteger())
26099     return SDValue();
26100
26101   SDValue CmpOp0 = Cmp.getOperand(0);
26102   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
26103                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
26104
26105   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
26106   if (CC == X86::COND_NE)
26107     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
26108                        DL, OtherVal.getValueType(), OtherVal,
26109                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
26110                        NewCmp);
26111   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
26112                      DL, OtherVal.getValueType(), OtherVal,
26113                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
26114 }
26115
26116 /// PerformADDCombine - Do target-specific dag combines on integer adds.
26117 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
26118                                  const X86Subtarget *Subtarget) {
26119   EVT VT = N->getValueType(0);
26120   SDValue Op0 = N->getOperand(0);
26121   SDValue Op1 = N->getOperand(1);
26122
26123   // Try to synthesize horizontal adds from adds of shuffles.
26124   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26125        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26126       isHorizontalBinOp(Op0, Op1, true))
26127     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
26128
26129   return OptimizeConditionalInDecrement(N, DAG);
26130 }
26131
26132 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
26133                                  const X86Subtarget *Subtarget) {
26134   SDValue Op0 = N->getOperand(0);
26135   SDValue Op1 = N->getOperand(1);
26136
26137   // X86 can't encode an immediate LHS of a sub. See if we can push the
26138   // negation into a preceding instruction.
26139   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
26140     // If the RHS of the sub is a XOR with one use and a constant, invert the
26141     // immediate. Then add one to the LHS of the sub so we can turn
26142     // X-Y -> X+~Y+1, saving one register.
26143     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
26144         isa<ConstantSDNode>(Op1.getOperand(1))) {
26145       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
26146       EVT VT = Op0.getValueType();
26147       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
26148                                    Op1.getOperand(0),
26149                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
26150       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
26151                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
26152     }
26153   }
26154
26155   // Try to synthesize horizontal adds from adds of shuffles.
26156   EVT VT = N->getValueType(0);
26157   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26158        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26159       isHorizontalBinOp(Op0, Op1, true))
26160     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
26161
26162   return OptimizeConditionalInDecrement(N, DAG);
26163 }
26164
26165 /// performVZEXTCombine - Performs build vector combines
26166 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
26167                                    TargetLowering::DAGCombinerInfo &DCI,
26168                                    const X86Subtarget *Subtarget) {
26169   SDLoc DL(N);
26170   MVT VT = N->getSimpleValueType(0);
26171   SDValue Op = N->getOperand(0);
26172   MVT OpVT = Op.getSimpleValueType();
26173   MVT OpEltVT = OpVT.getVectorElementType();
26174   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
26175
26176   // (vzext (bitcast (vzext (x)) -> (vzext x)
26177   SDValue V = Op;
26178   while (V.getOpcode() == ISD::BITCAST)
26179     V = V.getOperand(0);
26180
26181   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
26182     MVT InnerVT = V.getSimpleValueType();
26183     MVT InnerEltVT = InnerVT.getVectorElementType();
26184
26185     // If the element sizes match exactly, we can just do one larger vzext. This
26186     // is always an exact type match as vzext operates on integer types.
26187     if (OpEltVT == InnerEltVT) {
26188       assert(OpVT == InnerVT && "Types must match for vzext!");
26189       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
26190     }
26191
26192     // The only other way we can combine them is if only a single element of the
26193     // inner vzext is used in the input to the outer vzext.
26194     if (InnerEltVT.getSizeInBits() < InputBits)
26195       return SDValue();
26196
26197     // In this case, the inner vzext is completely dead because we're going to
26198     // only look at bits inside of the low element. Just do the outer vzext on
26199     // a bitcast of the input to the inner.
26200     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
26201   }
26202
26203   // Check if we can bypass extracting and re-inserting an element of an input
26204   // vector. Essentially:
26205   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
26206   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
26207       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
26208       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
26209     SDValue ExtractedV = V.getOperand(0);
26210     SDValue OrigV = ExtractedV.getOperand(0);
26211     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
26212       if (ExtractIdx->getZExtValue() == 0) {
26213         MVT OrigVT = OrigV.getSimpleValueType();
26214         // Extract a subvector if necessary...
26215         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
26216           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
26217           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
26218                                     OrigVT.getVectorNumElements() / Ratio);
26219           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
26220                               DAG.getIntPtrConstant(0, DL));
26221         }
26222         Op = DAG.getBitcast(OpVT, OrigV);
26223         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
26224       }
26225   }
26226
26227   return SDValue();
26228 }
26229
26230 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
26231                                              DAGCombinerInfo &DCI) const {
26232   SelectionDAG &DAG = DCI.DAG;
26233   switch (N->getOpcode()) {
26234   default: break;
26235   case ISD::EXTRACT_VECTOR_ELT:
26236     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
26237   case ISD::VSELECT:
26238   case ISD::SELECT:
26239   case X86ISD::SHRUNKBLEND:
26240     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
26241   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
26242   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
26243   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
26244   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
26245   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
26246   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
26247   case ISD::SHL:
26248   case ISD::SRA:
26249   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
26250   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
26251   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
26252   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
26253   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
26254   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
26255   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
26256   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
26257   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
26258   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
26259   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
26260   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
26261   case X86ISD::FXOR:
26262   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
26263   case X86ISD::FMIN:
26264   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
26265   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
26266   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
26267   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
26268   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
26269   case ISD::ANY_EXTEND:
26270   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
26271   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
26272   case ISD::SIGN_EXTEND_INREG:
26273     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
26274   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
26275   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
26276   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
26277   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
26278   case X86ISD::SHUFP:       // Handle all target specific shuffles
26279   case X86ISD::PALIGNR:
26280   case X86ISD::UNPCKH:
26281   case X86ISD::UNPCKL:
26282   case X86ISD::MOVHLPS:
26283   case X86ISD::MOVLHPS:
26284   case X86ISD::PSHUFB:
26285   case X86ISD::PSHUFD:
26286   case X86ISD::PSHUFHW:
26287   case X86ISD::PSHUFLW:
26288   case X86ISD::MOVSS:
26289   case X86ISD::MOVSD:
26290   case X86ISD::VPERMILPI:
26291   case X86ISD::VPERM2X128:
26292   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
26293   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
26294   case X86ISD::INSERTPS: {
26295     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
26296       return PerformINSERTPSCombine(N, DAG, Subtarget);
26297     break;
26298   }
26299   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
26300   }
26301
26302   return SDValue();
26303 }
26304
26305 /// isTypeDesirableForOp - Return true if the target has native support for
26306 /// the specified value type and it is 'desirable' to use the type for the
26307 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
26308 /// instruction encodings are longer and some i16 instructions are slow.
26309 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
26310   if (!isTypeLegal(VT))
26311     return false;
26312   if (VT != MVT::i16)
26313     return true;
26314
26315   switch (Opc) {
26316   default:
26317     return true;
26318   case ISD::LOAD:
26319   case ISD::SIGN_EXTEND:
26320   case ISD::ZERO_EXTEND:
26321   case ISD::ANY_EXTEND:
26322   case ISD::SHL:
26323   case ISD::SRL:
26324   case ISD::SUB:
26325   case ISD::ADD:
26326   case ISD::MUL:
26327   case ISD::AND:
26328   case ISD::OR:
26329   case ISD::XOR:
26330     return false;
26331   }
26332 }
26333
26334 /// IsDesirableToPromoteOp - This method query the target whether it is
26335 /// beneficial for dag combiner to promote the specified node. If true, it
26336 /// should return the desired promotion type by reference.
26337 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
26338   EVT VT = Op.getValueType();
26339   if (VT != MVT::i16)
26340     return false;
26341
26342   bool Promote = false;
26343   bool Commute = false;
26344   switch (Op.getOpcode()) {
26345   default: break;
26346   case ISD::LOAD: {
26347     LoadSDNode *LD = cast<LoadSDNode>(Op);
26348     // If the non-extending load has a single use and it's not live out, then it
26349     // might be folded.
26350     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
26351                                                      Op.hasOneUse()*/) {
26352       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
26353              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
26354         // The only case where we'd want to promote LOAD (rather then it being
26355         // promoted as an operand is when it's only use is liveout.
26356         if (UI->getOpcode() != ISD::CopyToReg)
26357           return false;
26358       }
26359     }
26360     Promote = true;
26361     break;
26362   }
26363   case ISD::SIGN_EXTEND:
26364   case ISD::ZERO_EXTEND:
26365   case ISD::ANY_EXTEND:
26366     Promote = true;
26367     break;
26368   case ISD::SHL:
26369   case ISD::SRL: {
26370     SDValue N0 = Op.getOperand(0);
26371     // Look out for (store (shl (load), x)).
26372     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
26373       return false;
26374     Promote = true;
26375     break;
26376   }
26377   case ISD::ADD:
26378   case ISD::MUL:
26379   case ISD::AND:
26380   case ISD::OR:
26381   case ISD::XOR:
26382     Commute = true;
26383     // fallthrough
26384   case ISD::SUB: {
26385     SDValue N0 = Op.getOperand(0);
26386     SDValue N1 = Op.getOperand(1);
26387     if (!Commute && MayFoldLoad(N1))
26388       return false;
26389     // Avoid disabling potential load folding opportunities.
26390     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
26391       return false;
26392     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
26393       return false;
26394     Promote = true;
26395   }
26396   }
26397
26398   PVT = MVT::i32;
26399   return Promote;
26400 }
26401
26402 //===----------------------------------------------------------------------===//
26403 //                           X86 Inline Assembly Support
26404 //===----------------------------------------------------------------------===//
26405
26406 // Helper to match a string separated by whitespace.
26407 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
26408   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
26409
26410   for (StringRef Piece : Pieces) {
26411     if (!S.startswith(Piece)) // Check if the piece matches.
26412       return false;
26413
26414     S = S.substr(Piece.size());
26415     StringRef::size_type Pos = S.find_first_not_of(" \t");
26416     if (Pos == 0) // We matched a prefix.
26417       return false;
26418
26419     S = S.substr(Pos);
26420   }
26421
26422   return S.empty();
26423 }
26424
26425 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26426
26427   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26428     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26429         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26430         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26431
26432       if (AsmPieces.size() == 3)
26433         return true;
26434       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26435         return true;
26436     }
26437   }
26438   return false;
26439 }
26440
26441 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26442   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26443
26444   std::string AsmStr = IA->getAsmString();
26445
26446   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26447   if (!Ty || Ty->getBitWidth() % 16 != 0)
26448     return false;
26449
26450   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26451   SmallVector<StringRef, 4> AsmPieces;
26452   SplitString(AsmStr, AsmPieces, ";\n");
26453
26454   switch (AsmPieces.size()) {
26455   default: return false;
26456   case 1:
26457     // FIXME: this should verify that we are targeting a 486 or better.  If not,
26458     // we will turn this bswap into something that will be lowered to logical
26459     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
26460     // lower so don't worry about this.
26461     // bswap $0
26462     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26463         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26464         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26465         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26466         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26467         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26468       // No need to check constraints, nothing other than the equivalent of
26469       // "=r,0" would be valid here.
26470       return IntrinsicLowering::LowerToByteSwap(CI);
26471     }
26472
26473     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
26474     if (CI->getType()->isIntegerTy(16) &&
26475         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26476         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26477          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26478       AsmPieces.clear();
26479       StringRef ConstraintsStr = IA->getConstraintString();
26480       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26481       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26482       if (clobbersFlagRegisters(AsmPieces))
26483         return IntrinsicLowering::LowerToByteSwap(CI);
26484     }
26485     break;
26486   case 3:
26487     if (CI->getType()->isIntegerTy(32) &&
26488         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26489         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26490         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26491         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26492       AsmPieces.clear();
26493       StringRef ConstraintsStr = IA->getConstraintString();
26494       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26495       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26496       if (clobbersFlagRegisters(AsmPieces))
26497         return IntrinsicLowering::LowerToByteSwap(CI);
26498     }
26499
26500     if (CI->getType()->isIntegerTy(64)) {
26501       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26502       if (Constraints.size() >= 2 &&
26503           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26504           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26505         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
26506         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26507             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26508             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26509           return IntrinsicLowering::LowerToByteSwap(CI);
26510       }
26511     }
26512     break;
26513   }
26514   return false;
26515 }
26516
26517 /// getConstraintType - Given a constraint letter, return the type of
26518 /// constraint it is for this target.
26519 X86TargetLowering::ConstraintType
26520 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26521   if (Constraint.size() == 1) {
26522     switch (Constraint[0]) {
26523     case 'R':
26524     case 'q':
26525     case 'Q':
26526     case 'f':
26527     case 't':
26528     case 'u':
26529     case 'y':
26530     case 'x':
26531     case 'Y':
26532     case 'l':
26533       return C_RegisterClass;
26534     case 'a':
26535     case 'b':
26536     case 'c':
26537     case 'd':
26538     case 'S':
26539     case 'D':
26540     case 'A':
26541       return C_Register;
26542     case 'I':
26543     case 'J':
26544     case 'K':
26545     case 'L':
26546     case 'M':
26547     case 'N':
26548     case 'G':
26549     case 'C':
26550     case 'e':
26551     case 'Z':
26552       return C_Other;
26553     default:
26554       break;
26555     }
26556   }
26557   return TargetLowering::getConstraintType(Constraint);
26558 }
26559
26560 /// Examine constraint type and operand type and determine a weight value.
26561 /// This object must already have been set up with the operand type
26562 /// and the current alternative constraint selected.
26563 TargetLowering::ConstraintWeight
26564   X86TargetLowering::getSingleConstraintMatchWeight(
26565     AsmOperandInfo &info, const char *constraint) const {
26566   ConstraintWeight weight = CW_Invalid;
26567   Value *CallOperandVal = info.CallOperandVal;
26568     // If we don't have a value, we can't do a match,
26569     // but allow it at the lowest weight.
26570   if (!CallOperandVal)
26571     return CW_Default;
26572   Type *type = CallOperandVal->getType();
26573   // Look at the constraint type.
26574   switch (*constraint) {
26575   default:
26576     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26577   case 'R':
26578   case 'q':
26579   case 'Q':
26580   case 'a':
26581   case 'b':
26582   case 'c':
26583   case 'd':
26584   case 'S':
26585   case 'D':
26586   case 'A':
26587     if (CallOperandVal->getType()->isIntegerTy())
26588       weight = CW_SpecificReg;
26589     break;
26590   case 'f':
26591   case 't':
26592   case 'u':
26593     if (type->isFloatingPointTy())
26594       weight = CW_SpecificReg;
26595     break;
26596   case 'y':
26597     if (type->isX86_MMXTy() && Subtarget->hasMMX())
26598       weight = CW_SpecificReg;
26599     break;
26600   case 'x':
26601   case 'Y':
26602     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26603         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26604       weight = CW_Register;
26605     break;
26606   case 'I':
26607     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26608       if (C->getZExtValue() <= 31)
26609         weight = CW_Constant;
26610     }
26611     break;
26612   case 'J':
26613     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26614       if (C->getZExtValue() <= 63)
26615         weight = CW_Constant;
26616     }
26617     break;
26618   case 'K':
26619     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26620       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26621         weight = CW_Constant;
26622     }
26623     break;
26624   case 'L':
26625     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26626       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26627         weight = CW_Constant;
26628     }
26629     break;
26630   case 'M':
26631     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26632       if (C->getZExtValue() <= 3)
26633         weight = CW_Constant;
26634     }
26635     break;
26636   case 'N':
26637     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26638       if (C->getZExtValue() <= 0xff)
26639         weight = CW_Constant;
26640     }
26641     break;
26642   case 'G':
26643   case 'C':
26644     if (isa<ConstantFP>(CallOperandVal)) {
26645       weight = CW_Constant;
26646     }
26647     break;
26648   case 'e':
26649     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26650       if ((C->getSExtValue() >= -0x80000000LL) &&
26651           (C->getSExtValue() <= 0x7fffffffLL))
26652         weight = CW_Constant;
26653     }
26654     break;
26655   case 'Z':
26656     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26657       if (C->getZExtValue() <= 0xffffffff)
26658         weight = CW_Constant;
26659     }
26660     break;
26661   }
26662   return weight;
26663 }
26664
26665 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26666 /// with another that has more specific requirements based on the type of the
26667 /// corresponding operand.
26668 const char *X86TargetLowering::
26669 LowerXConstraint(EVT ConstraintVT) const {
26670   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26671   // 'f' like normal targets.
26672   if (ConstraintVT.isFloatingPoint()) {
26673     if (Subtarget->hasSSE2())
26674       return "Y";
26675     if (Subtarget->hasSSE1())
26676       return "x";
26677   }
26678
26679   return TargetLowering::LowerXConstraint(ConstraintVT);
26680 }
26681
26682 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26683 /// vector.  If it is invalid, don't add anything to Ops.
26684 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26685                                                      std::string &Constraint,
26686                                                      std::vector<SDValue>&Ops,
26687                                                      SelectionDAG &DAG) const {
26688   SDValue Result;
26689
26690   // Only support length 1 constraints for now.
26691   if (Constraint.length() > 1) return;
26692
26693   char ConstraintLetter = Constraint[0];
26694   switch (ConstraintLetter) {
26695   default: break;
26696   case 'I':
26697     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26698       if (C->getZExtValue() <= 31) {
26699         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26700                                        Op.getValueType());
26701         break;
26702       }
26703     }
26704     return;
26705   case 'J':
26706     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26707       if (C->getZExtValue() <= 63) {
26708         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26709                                        Op.getValueType());
26710         break;
26711       }
26712     }
26713     return;
26714   case 'K':
26715     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26716       if (isInt<8>(C->getSExtValue())) {
26717         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26718                                        Op.getValueType());
26719         break;
26720       }
26721     }
26722     return;
26723   case 'L':
26724     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26725       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26726           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26727         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26728                                        Op.getValueType());
26729         break;
26730       }
26731     }
26732     return;
26733   case 'M':
26734     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26735       if (C->getZExtValue() <= 3) {
26736         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26737                                        Op.getValueType());
26738         break;
26739       }
26740     }
26741     return;
26742   case 'N':
26743     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26744       if (C->getZExtValue() <= 255) {
26745         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26746                                        Op.getValueType());
26747         break;
26748       }
26749     }
26750     return;
26751   case 'O':
26752     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26753       if (C->getZExtValue() <= 127) {
26754         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26755                                        Op.getValueType());
26756         break;
26757       }
26758     }
26759     return;
26760   case 'e': {
26761     // 32-bit signed value
26762     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26763       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26764                                            C->getSExtValue())) {
26765         // Widen to 64 bits here to get it sign extended.
26766         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26767         break;
26768       }
26769     // FIXME gcc accepts some relocatable values here too, but only in certain
26770     // memory models; it's complicated.
26771     }
26772     return;
26773   }
26774   case 'Z': {
26775     // 32-bit unsigned value
26776     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26777       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26778                                            C->getZExtValue())) {
26779         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26780                                        Op.getValueType());
26781         break;
26782       }
26783     }
26784     // FIXME gcc accepts some relocatable values here too, but only in certain
26785     // memory models; it's complicated.
26786     return;
26787   }
26788   case 'i': {
26789     // Literal immediates are always ok.
26790     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26791       // Widen to 64 bits here to get it sign extended.
26792       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26793       break;
26794     }
26795
26796     // In any sort of PIC mode addresses need to be computed at runtime by
26797     // adding in a register or some sort of table lookup.  These can't
26798     // be used as immediates.
26799     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26800       return;
26801
26802     // If we are in non-pic codegen mode, we allow the address of a global (with
26803     // an optional displacement) to be used with 'i'.
26804     GlobalAddressSDNode *GA = nullptr;
26805     int64_t Offset = 0;
26806
26807     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26808     while (1) {
26809       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26810         Offset += GA->getOffset();
26811         break;
26812       } else if (Op.getOpcode() == ISD::ADD) {
26813         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26814           Offset += C->getZExtValue();
26815           Op = Op.getOperand(0);
26816           continue;
26817         }
26818       } else if (Op.getOpcode() == ISD::SUB) {
26819         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26820           Offset += -C->getZExtValue();
26821           Op = Op.getOperand(0);
26822           continue;
26823         }
26824       }
26825
26826       // Otherwise, this isn't something we can handle, reject it.
26827       return;
26828     }
26829
26830     const GlobalValue *GV = GA->getGlobal();
26831     // If we require an extra load to get this address, as in PIC mode, we
26832     // can't accept it.
26833     if (isGlobalStubReference(
26834             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26835       return;
26836
26837     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26838                                         GA->getValueType(0), Offset);
26839     break;
26840   }
26841   }
26842
26843   if (Result.getNode()) {
26844     Ops.push_back(Result);
26845     return;
26846   }
26847   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26848 }
26849
26850 std::pair<unsigned, const TargetRegisterClass *>
26851 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26852                                                 StringRef Constraint,
26853                                                 MVT VT) const {
26854   // First, see if this is a constraint that directly corresponds to an LLVM
26855   // register class.
26856   if (Constraint.size() == 1) {
26857     // GCC Constraint Letters
26858     switch (Constraint[0]) {
26859     default: break;
26860       // TODO: Slight differences here in allocation order and leaving
26861       // RIP in the class. Do they matter any more here than they do
26862       // in the normal allocation?
26863     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26864       if (Subtarget->is64Bit()) {
26865         if (VT == MVT::i32 || VT == MVT::f32)
26866           return std::make_pair(0U, &X86::GR32RegClass);
26867         if (VT == MVT::i16)
26868           return std::make_pair(0U, &X86::GR16RegClass);
26869         if (VT == MVT::i8 || VT == MVT::i1)
26870           return std::make_pair(0U, &X86::GR8RegClass);
26871         if (VT == MVT::i64 || VT == MVT::f64)
26872           return std::make_pair(0U, &X86::GR64RegClass);
26873         break;
26874       }
26875       // 32-bit fallthrough
26876     case 'Q':   // Q_REGS
26877       if (VT == MVT::i32 || VT == MVT::f32)
26878         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26879       if (VT == MVT::i16)
26880         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26881       if (VT == MVT::i8 || VT == MVT::i1)
26882         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26883       if (VT == MVT::i64)
26884         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26885       break;
26886     case 'r':   // GENERAL_REGS
26887     case 'l':   // INDEX_REGS
26888       if (VT == MVT::i8 || VT == MVT::i1)
26889         return std::make_pair(0U, &X86::GR8RegClass);
26890       if (VT == MVT::i16)
26891         return std::make_pair(0U, &X86::GR16RegClass);
26892       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26893         return std::make_pair(0U, &X86::GR32RegClass);
26894       return std::make_pair(0U, &X86::GR64RegClass);
26895     case 'R':   // LEGACY_REGS
26896       if (VT == MVT::i8 || VT == MVT::i1)
26897         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26898       if (VT == MVT::i16)
26899         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26900       if (VT == MVT::i32 || !Subtarget->is64Bit())
26901         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26902       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26903     case 'f':  // FP Stack registers.
26904       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26905       // value to the correct fpstack register class.
26906       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26907         return std::make_pair(0U, &X86::RFP32RegClass);
26908       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26909         return std::make_pair(0U, &X86::RFP64RegClass);
26910       return std::make_pair(0U, &X86::RFP80RegClass);
26911     case 'y':   // MMX_REGS if MMX allowed.
26912       if (!Subtarget->hasMMX()) break;
26913       return std::make_pair(0U, &X86::VR64RegClass);
26914     case 'Y':   // SSE_REGS if SSE2 allowed
26915       if (!Subtarget->hasSSE2()) break;
26916       // FALL THROUGH.
26917     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26918       if (!Subtarget->hasSSE1()) break;
26919
26920       switch (VT.SimpleTy) {
26921       default: break;
26922       // Scalar SSE types.
26923       case MVT::f32:
26924       case MVT::i32:
26925         return std::make_pair(0U, &X86::FR32RegClass);
26926       case MVT::f64:
26927       case MVT::i64:
26928         return std::make_pair(0U, &X86::FR64RegClass);
26929       // Vector types.
26930       case MVT::v16i8:
26931       case MVT::v8i16:
26932       case MVT::v4i32:
26933       case MVT::v2i64:
26934       case MVT::v4f32:
26935       case MVT::v2f64:
26936         return std::make_pair(0U, &X86::VR128RegClass);
26937       // AVX types.
26938       case MVT::v32i8:
26939       case MVT::v16i16:
26940       case MVT::v8i32:
26941       case MVT::v4i64:
26942       case MVT::v8f32:
26943       case MVT::v4f64:
26944         return std::make_pair(0U, &X86::VR256RegClass);
26945       case MVT::v8f64:
26946       case MVT::v16f32:
26947       case MVT::v16i32:
26948       case MVT::v8i64:
26949         return std::make_pair(0U, &X86::VR512RegClass);
26950       }
26951       break;
26952     }
26953   }
26954
26955   // Use the default implementation in TargetLowering to convert the register
26956   // constraint into a member of a register class.
26957   std::pair<unsigned, const TargetRegisterClass*> Res;
26958   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26959
26960   // Not found as a standard register?
26961   if (!Res.second) {
26962     // Map st(0) -> st(7) -> ST0
26963     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26964         tolower(Constraint[1]) == 's' &&
26965         tolower(Constraint[2]) == 't' &&
26966         Constraint[3] == '(' &&
26967         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26968         Constraint[5] == ')' &&
26969         Constraint[6] == '}') {
26970
26971       Res.first = X86::FP0+Constraint[4]-'0';
26972       Res.second = &X86::RFP80RegClass;
26973       return Res;
26974     }
26975
26976     // GCC allows "st(0)" to be called just plain "st".
26977     if (StringRef("{st}").equals_lower(Constraint)) {
26978       Res.first = X86::FP0;
26979       Res.second = &X86::RFP80RegClass;
26980       return Res;
26981     }
26982
26983     // flags -> EFLAGS
26984     if (StringRef("{flags}").equals_lower(Constraint)) {
26985       Res.first = X86::EFLAGS;
26986       Res.second = &X86::CCRRegClass;
26987       return Res;
26988     }
26989
26990     // 'A' means EAX + EDX.
26991     if (Constraint == "A") {
26992       Res.first = X86::EAX;
26993       Res.second = &X86::GR32_ADRegClass;
26994       return Res;
26995     }
26996     return Res;
26997   }
26998
26999   // Otherwise, check to see if this is a register class of the wrong value
27000   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
27001   // turn into {ax},{dx}.
27002   // MVT::Other is used to specify clobber names.
27003   if (Res.second->hasType(VT) || VT == MVT::Other)
27004     return Res;   // Correct type already, nothing to do.
27005
27006   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
27007   // return "eax". This should even work for things like getting 64bit integer
27008   // registers when given an f64 type.
27009   const TargetRegisterClass *Class = Res.second;
27010   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
27011       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
27012     unsigned Size = VT.getSizeInBits();
27013     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
27014                                   : Size == 16 ? MVT::i16
27015                                   : Size == 32 ? MVT::i32
27016                                   : Size == 64 ? MVT::i64
27017                                   : MVT::Other;
27018     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
27019     if (DestReg > 0) {
27020       Res.first = DestReg;
27021       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
27022                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
27023                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
27024                  : &X86::GR64RegClass;
27025       assert(Res.second->contains(Res.first) && "Register in register class");
27026     } else {
27027       // No register found/type mismatch.
27028       Res.first = 0;
27029       Res.second = nullptr;
27030     }
27031   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
27032              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
27033              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
27034              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
27035              Class == &X86::VR512RegClass) {
27036     // Handle references to XMM physical registers that got mapped into the
27037     // wrong class.  This can happen with constraints like {xmm0} where the
27038     // target independent register mapper will just pick the first match it can
27039     // find, ignoring the required type.
27040
27041     if (VT == MVT::f32 || VT == MVT::i32)
27042       Res.second = &X86::FR32RegClass;
27043     else if (VT == MVT::f64 || VT == MVT::i64)
27044       Res.second = &X86::FR64RegClass;
27045     else if (X86::VR128RegClass.hasType(VT))
27046       Res.second = &X86::VR128RegClass;
27047     else if (X86::VR256RegClass.hasType(VT))
27048       Res.second = &X86::VR256RegClass;
27049     else if (X86::VR512RegClass.hasType(VT))
27050       Res.second = &X86::VR512RegClass;
27051     else {
27052       // Type mismatch and not a clobber: Return an error;
27053       Res.first = 0;
27054       Res.second = nullptr;
27055     }
27056   }
27057
27058   return Res;
27059 }
27060
27061 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
27062                                             const AddrMode &AM, Type *Ty,
27063                                             unsigned AS) const {
27064   // Scaling factors are not free at all.
27065   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
27066   // will take 2 allocations in the out of order engine instead of 1
27067   // for plain addressing mode, i.e. inst (reg1).
27068   // E.g.,
27069   // vaddps (%rsi,%drx), %ymm0, %ymm1
27070   // Requires two allocations (one for the load, one for the computation)
27071   // whereas:
27072   // vaddps (%rsi), %ymm0, %ymm1
27073   // Requires just 1 allocation, i.e., freeing allocations for other operations
27074   // and having less micro operations to execute.
27075   //
27076   // For some X86 architectures, this is even worse because for instance for
27077   // stores, the complex addressing mode forces the instruction to use the
27078   // "load" ports instead of the dedicated "store" port.
27079   // E.g., on Haswell:
27080   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
27081   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
27082   if (isLegalAddressingMode(DL, AM, Ty, AS))
27083     // Scale represents reg2 * scale, thus account for 1
27084     // as soon as we use a second register.
27085     return AM.Scale != 0;
27086   return -1;
27087 }
27088
27089 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
27090   // Integer division on x86 is expensive. However, when aggressively optimizing
27091   // for code size, we prefer to use a div instruction, as it is usually smaller
27092   // than the alternative sequence.
27093   // The exception to this is vector division. Since x86 doesn't have vector
27094   // integer division, leaving the division as-is is a loss even in terms of
27095   // size, because it will have to be scalarized, while the alternative code
27096   // sequence can be performed in vector form.
27097   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
27098                                    Attribute::MinSize);
27099   return OptSize && !VT.isVector();
27100 }