12b2f4ee8a111d4dde0aab1ba93796e7f13e4a7a
[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 X86TargetLowering::CanLowerReturn(
2098     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2099     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2100   SmallVector<CCValAssign, 16> RVLocs;
2101   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2102   return CCInfo.CheckReturn(Outs, RetCC_X86);
2103 }
2104
2105 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2106   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2107   return ScratchRegs;
2108 }
2109
2110 SDValue
2111 X86TargetLowering::LowerReturn(SDValue Chain,
2112                                CallingConv::ID CallConv, bool isVarArg,
2113                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2114                                const SmallVectorImpl<SDValue> &OutVals,
2115                                SDLoc dl, SelectionDAG &DAG) const {
2116   MachineFunction &MF = DAG.getMachineFunction();
2117   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2118
2119   SmallVector<CCValAssign, 16> RVLocs;
2120   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2121   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2122
2123   SDValue Flag;
2124   SmallVector<SDValue, 6> RetOps;
2125   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2126   // Operand #1 = Bytes To Pop
2127   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2128                    MVT::i16));
2129
2130   // Copy the result values into the output registers.
2131   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2132     CCValAssign &VA = RVLocs[i];
2133     assert(VA.isRegLoc() && "Can only return in registers!");
2134     SDValue ValToCopy = OutVals[i];
2135     EVT ValVT = ValToCopy.getValueType();
2136
2137     // Promote values to the appropriate types.
2138     if (VA.getLocInfo() == CCValAssign::SExt)
2139       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2140     else if (VA.getLocInfo() == CCValAssign::ZExt)
2141       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2142     else if (VA.getLocInfo() == CCValAssign::AExt) {
2143       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2144         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2145       else
2146         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2147     }
2148     else if (VA.getLocInfo() == CCValAssign::BCvt)
2149       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2150
2151     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2152            "Unexpected FP-extend for return value.");
2153
2154     // If this is x86-64, and we disabled SSE, we can't return FP values,
2155     // or SSE or MMX vectors.
2156     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2157          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2158           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2159       report_fatal_error("SSE register return with SSE disabled");
2160     }
2161     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2162     // llvm-gcc has never done it right and no one has noticed, so this
2163     // should be OK for now.
2164     if (ValVT == MVT::f64 &&
2165         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2166       report_fatal_error("SSE2 register return with SSE2 disabled");
2167
2168     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2169     // the RET instruction and handled by the FP Stackifier.
2170     if (VA.getLocReg() == X86::FP0 ||
2171         VA.getLocReg() == X86::FP1) {
2172       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2173       // change the value to the FP stack register class.
2174       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2175         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2176       RetOps.push_back(ValToCopy);
2177       // Don't emit a copytoreg.
2178       continue;
2179     }
2180
2181     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2182     // which is returned in RAX / RDX.
2183     if (Subtarget->is64Bit()) {
2184       if (ValVT == MVT::x86mmx) {
2185         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2186           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2187           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2188                                   ValToCopy);
2189           // If we don't have SSE2 available, convert to v4f32 so the generated
2190           // register is legal.
2191           if (!Subtarget->hasSSE2())
2192             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2193         }
2194       }
2195     }
2196
2197     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2198     Flag = Chain.getValue(1);
2199     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2200   }
2201
2202   // All x86 ABIs require that for returning structs by value we copy
2203   // the sret argument into %rax/%eax (depending on ABI) for the return.
2204   // We saved the argument into a virtual register in the entry block,
2205   // so now we copy the value out and into %rax/%eax.
2206   //
2207   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2208   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2209   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2210   // either case FuncInfo->setSRetReturnReg() will have been called.
2211   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2212     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2213                                      getPointerTy(MF.getDataLayout()));
2214
2215     unsigned RetValReg
2216         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2217           X86::RAX : X86::EAX;
2218     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2219     Flag = Chain.getValue(1);
2220
2221     // RAX/EAX now acts like a return value.
2222     RetOps.push_back(
2223         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2224   }
2225
2226   RetOps[0] = Chain;  // Update chain.
2227
2228   // Add the flag if we have it.
2229   if (Flag.getNode())
2230     RetOps.push_back(Flag);
2231
2232   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2233 }
2234
2235 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2236   if (N->getNumValues() != 1)
2237     return false;
2238   if (!N->hasNUsesOfValue(1, 0))
2239     return false;
2240
2241   SDValue TCChain = Chain;
2242   SDNode *Copy = *N->use_begin();
2243   if (Copy->getOpcode() == ISD::CopyToReg) {
2244     // If the copy has a glue operand, we conservatively assume it isn't safe to
2245     // perform a tail call.
2246     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2247       return false;
2248     TCChain = Copy->getOperand(0);
2249   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2250     return false;
2251
2252   bool HasRet = false;
2253   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2254        UI != UE; ++UI) {
2255     if (UI->getOpcode() != X86ISD::RET_FLAG)
2256       return false;
2257     // If we are returning more than one value, we can definitely
2258     // not make a tail call see PR19530
2259     if (UI->getNumOperands() > 4)
2260       return false;
2261     if (UI->getNumOperands() == 4 &&
2262         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2263       return false;
2264     HasRet = true;
2265   }
2266
2267   if (!HasRet)
2268     return false;
2269
2270   Chain = TCChain;
2271   return true;
2272 }
2273
2274 EVT
2275 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2276                                             ISD::NodeType ExtendKind) const {
2277   MVT ReturnMVT;
2278   // TODO: Is this also valid on 32-bit?
2279   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2280     ReturnMVT = MVT::i8;
2281   else
2282     ReturnMVT = MVT::i32;
2283
2284   EVT MinVT = getRegisterType(Context, ReturnMVT);
2285   return VT.bitsLT(MinVT) ? MinVT : VT;
2286 }
2287
2288 /// Lower the result values of a call into the
2289 /// appropriate copies out of appropriate physical registers.
2290 ///
2291 SDValue
2292 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2293                                    CallingConv::ID CallConv, bool isVarArg,
2294                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2295                                    SDLoc dl, SelectionDAG &DAG,
2296                                    SmallVectorImpl<SDValue> &InVals) const {
2297
2298   // Assign locations to each value returned by this call.
2299   SmallVector<CCValAssign, 16> RVLocs;
2300   bool Is64Bit = Subtarget->is64Bit();
2301   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2302                  *DAG.getContext());
2303   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2304
2305   // Copy all of the result registers out of their specified physreg.
2306   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2307     CCValAssign &VA = RVLocs[i];
2308     EVT CopyVT = VA.getLocVT();
2309
2310     // If this is x86-64, and we disabled SSE, we can't return FP values
2311     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2312         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2313       report_fatal_error("SSE register return with SSE disabled");
2314     }
2315
2316     // If we prefer to use the value in xmm registers, copy it out as f80 and
2317     // use a truncate to move it from fp stack reg to xmm reg.
2318     bool RoundAfterCopy = false;
2319     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2320         isScalarFPTypeInSSEReg(VA.getValVT())) {
2321       CopyVT = MVT::f80;
2322       RoundAfterCopy = (CopyVT != VA.getLocVT());
2323     }
2324
2325     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2326                                CopyVT, InFlag).getValue(1);
2327     SDValue Val = Chain.getValue(0);
2328
2329     if (RoundAfterCopy)
2330       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2331                         // This truncation won't change the value.
2332                         DAG.getIntPtrConstant(1, dl));
2333
2334     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2335       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2336
2337     InFlag = Chain.getValue(2);
2338     InVals.push_back(Val);
2339   }
2340
2341   return Chain;
2342 }
2343
2344 //===----------------------------------------------------------------------===//
2345 //                C & StdCall & Fast Calling Convention implementation
2346 //===----------------------------------------------------------------------===//
2347 //  StdCall calling convention seems to be standard for many Windows' API
2348 //  routines and around. It differs from C calling convention just a little:
2349 //  callee should clean up the stack, not caller. Symbols should be also
2350 //  decorated in some fancy way :) It doesn't support any vector arguments.
2351 //  For info on fast calling convention see Fast Calling Convention (tail call)
2352 //  implementation LowerX86_32FastCCCallTo.
2353
2354 /// CallIsStructReturn - Determines whether a call uses struct return
2355 /// semantics.
2356 enum StructReturnType {
2357   NotStructReturn,
2358   RegStructReturn,
2359   StackStructReturn
2360 };
2361 static StructReturnType
2362 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2363   if (Outs.empty())
2364     return NotStructReturn;
2365
2366   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2367   if (!Flags.isSRet())
2368     return NotStructReturn;
2369   if (Flags.isInReg())
2370     return RegStructReturn;
2371   return StackStructReturn;
2372 }
2373
2374 /// Determines whether a function uses struct return semantics.
2375 static StructReturnType
2376 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2377   if (Ins.empty())
2378     return NotStructReturn;
2379
2380   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2381   if (!Flags.isSRet())
2382     return NotStructReturn;
2383   if (Flags.isInReg())
2384     return RegStructReturn;
2385   return StackStructReturn;
2386 }
2387
2388 /// Make a copy of an aggregate at address specified by "Src" to address
2389 /// "Dst" with size and alignment information specified by the specific
2390 /// parameter attribute. The copy will be passed as a byval function parameter.
2391 static SDValue
2392 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2393                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2394                           SDLoc dl) {
2395   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2396
2397   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2398                        /*isVolatile*/false, /*AlwaysInline=*/true,
2399                        /*isTailCall*/false,
2400                        MachinePointerInfo(), MachinePointerInfo());
2401 }
2402
2403 /// Return true if the calling convention is one that
2404 /// supports tail call optimization.
2405 static bool IsTailCallConvention(CallingConv::ID CC) {
2406   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2407           CC == CallingConv::HiPE);
2408 }
2409
2410 /// \brief Return true if the calling convention is a C calling convention.
2411 static bool IsCCallConvention(CallingConv::ID CC) {
2412   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2413           CC == CallingConv::X86_64_SysV);
2414 }
2415
2416 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2417   auto Attr =
2418       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2419   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2420     return false;
2421
2422   CallSite CS(CI);
2423   CallingConv::ID CalleeCC = CS.getCallingConv();
2424   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2425     return false;
2426
2427   return true;
2428 }
2429
2430 /// Return true if the function is being made into
2431 /// a tailcall target by changing its ABI.
2432 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2433                                    bool GuaranteedTailCallOpt) {
2434   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2435 }
2436
2437 SDValue
2438 X86TargetLowering::LowerMemArgument(SDValue Chain,
2439                                     CallingConv::ID CallConv,
2440                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2441                                     SDLoc dl, SelectionDAG &DAG,
2442                                     const CCValAssign &VA,
2443                                     MachineFrameInfo *MFI,
2444                                     unsigned i) const {
2445   // Create the nodes corresponding to a load from this parameter slot.
2446   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2447   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2448       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2449   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2450   EVT ValVT;
2451
2452   // If value is passed by pointer we have address passed instead of the value
2453   // itself.
2454   bool ExtendedInMem = VA.isExtInLoc() &&
2455     VA.getValVT().getScalarType() == MVT::i1;
2456
2457   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2458     ValVT = VA.getLocVT();
2459   else
2460     ValVT = VA.getValVT();
2461
2462   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2463   // changed with more analysis.
2464   // In case of tail call optimization mark all arguments mutable. Since they
2465   // could be overwritten by lowering of arguments in case of a tail call.
2466   if (Flags.isByVal()) {
2467     unsigned Bytes = Flags.getByValSize();
2468     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2469     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2470     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2471   } else {
2472     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2473                                     VA.getLocMemOffset(), isImmutable);
2474     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2475     SDValue Val = DAG.getLoad(
2476         ValVT, dl, Chain, FIN,
2477         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2478         false, false, 0);
2479     return ExtendedInMem ?
2480       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2481   }
2482 }
2483
2484 // FIXME: Get this from tablegen.
2485 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2486                                                 const X86Subtarget *Subtarget) {
2487   assert(Subtarget->is64Bit());
2488
2489   if (Subtarget->isCallingConvWin64(CallConv)) {
2490     static const MCPhysReg GPR64ArgRegsWin64[] = {
2491       X86::RCX, X86::RDX, X86::R8,  X86::R9
2492     };
2493     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2494   }
2495
2496   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2497     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2498   };
2499   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2500 }
2501
2502 // FIXME: Get this from tablegen.
2503 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2504                                                 CallingConv::ID CallConv,
2505                                                 const X86Subtarget *Subtarget) {
2506   assert(Subtarget->is64Bit());
2507   if (Subtarget->isCallingConvWin64(CallConv)) {
2508     // The XMM registers which might contain var arg parameters are shadowed
2509     // in their paired GPR.  So we only need to save the GPR to their home
2510     // slots.
2511     // TODO: __vectorcall will change this.
2512     return None;
2513   }
2514
2515   const Function *Fn = MF.getFunction();
2516   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2517   bool isSoftFloat = Subtarget->useSoftFloat();
2518   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2519          "SSE register cannot be used when SSE is disabled!");
2520   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2521     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2522     // registers.
2523     return None;
2524
2525   static const MCPhysReg XMMArgRegs64Bit[] = {
2526     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2527     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2528   };
2529   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2530 }
2531
2532 SDValue X86TargetLowering::LowerFormalArguments(
2533     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2534     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2535     SmallVectorImpl<SDValue> &InVals) const {
2536   MachineFunction &MF = DAG.getMachineFunction();
2537   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2538   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2539
2540   const Function* Fn = MF.getFunction();
2541   if (Fn->hasExternalLinkage() &&
2542       Subtarget->isTargetCygMing() &&
2543       Fn->getName() == "main")
2544     FuncInfo->setForceFramePointer(true);
2545
2546   MachineFrameInfo *MFI = MF.getFrameInfo();
2547   bool Is64Bit = Subtarget->is64Bit();
2548   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2549
2550   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2551          "Var args not supported with calling convention fastcc, ghc or hipe");
2552
2553   // Assign locations to all of the incoming arguments.
2554   SmallVector<CCValAssign, 16> ArgLocs;
2555   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2556
2557   // Allocate shadow area for Win64
2558   if (IsWin64)
2559     CCInfo.AllocateStack(32, 8);
2560
2561   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2562
2563   unsigned LastVal = ~0U;
2564   SDValue ArgValue;
2565   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2566     CCValAssign &VA = ArgLocs[i];
2567     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2568     // places.
2569     assert(VA.getValNo() != LastVal &&
2570            "Don't support value assigned to multiple locs yet");
2571     (void)LastVal;
2572     LastVal = VA.getValNo();
2573
2574     if (VA.isRegLoc()) {
2575       EVT RegVT = VA.getLocVT();
2576       const TargetRegisterClass *RC;
2577       if (RegVT == MVT::i32)
2578         RC = &X86::GR32RegClass;
2579       else if (Is64Bit && RegVT == MVT::i64)
2580         RC = &X86::GR64RegClass;
2581       else if (RegVT == MVT::f32)
2582         RC = &X86::FR32RegClass;
2583       else if (RegVT == MVT::f64)
2584         RC = &X86::FR64RegClass;
2585       else if (RegVT.is512BitVector())
2586         RC = &X86::VR512RegClass;
2587       else if (RegVT.is256BitVector())
2588         RC = &X86::VR256RegClass;
2589       else if (RegVT.is128BitVector())
2590         RC = &X86::VR128RegClass;
2591       else if (RegVT == MVT::x86mmx)
2592         RC = &X86::VR64RegClass;
2593       else if (RegVT == MVT::i1)
2594         RC = &X86::VK1RegClass;
2595       else if (RegVT == MVT::v8i1)
2596         RC = &X86::VK8RegClass;
2597       else if (RegVT == MVT::v16i1)
2598         RC = &X86::VK16RegClass;
2599       else if (RegVT == MVT::v32i1)
2600         RC = &X86::VK32RegClass;
2601       else if (RegVT == MVT::v64i1)
2602         RC = &X86::VK64RegClass;
2603       else
2604         llvm_unreachable("Unknown argument type!");
2605
2606       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2607       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2608
2609       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2610       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2611       // right size.
2612       if (VA.getLocInfo() == CCValAssign::SExt)
2613         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2614                                DAG.getValueType(VA.getValVT()));
2615       else if (VA.getLocInfo() == CCValAssign::ZExt)
2616         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2617                                DAG.getValueType(VA.getValVT()));
2618       else if (VA.getLocInfo() == CCValAssign::BCvt)
2619         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2620
2621       if (VA.isExtInLoc()) {
2622         // Handle MMX values passed in XMM regs.
2623         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2624           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2625         else
2626           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2627       }
2628     } else {
2629       assert(VA.isMemLoc());
2630       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2631     }
2632
2633     // If value is passed via pointer - do a load.
2634     if (VA.getLocInfo() == CCValAssign::Indirect)
2635       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2636                              MachinePointerInfo(), false, false, false, 0);
2637
2638     InVals.push_back(ArgValue);
2639   }
2640
2641   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2642     // All x86 ABIs require that for returning structs by value we copy the
2643     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2644     // the argument into a virtual register so that we can access it from the
2645     // return points.
2646     if (Ins[i].Flags.isSRet()) {
2647       unsigned Reg = FuncInfo->getSRetReturnReg();
2648       if (!Reg) {
2649         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2650         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2651         FuncInfo->setSRetReturnReg(Reg);
2652       }
2653       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2654       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2655       break;
2656     }
2657   }
2658
2659   unsigned StackSize = CCInfo.getNextStackOffset();
2660   // Align stack specially for tail calls.
2661   if (FuncIsMadeTailCallSafe(CallConv,
2662                              MF.getTarget().Options.GuaranteedTailCallOpt))
2663     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2664
2665   // If the function takes variable number of arguments, make a frame index for
2666   // the start of the first vararg value... for expansion of llvm.va_start. We
2667   // can skip this if there are no va_start calls.
2668   if (MFI->hasVAStart() &&
2669       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2670                    CallConv != CallingConv::X86_ThisCall))) {
2671     FuncInfo->setVarArgsFrameIndex(
2672         MFI->CreateFixedObject(1, StackSize, true));
2673   }
2674
2675   MachineModuleInfo &MMI = MF.getMMI();
2676   const Function *WinEHParent = nullptr;
2677   if (MMI.hasWinEHFuncInfo(Fn))
2678     WinEHParent = MMI.getWinEHParent(Fn);
2679   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2680
2681   // Figure out if XMM registers are in use.
2682   assert(!(Subtarget->useSoftFloat() &&
2683            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2684          "SSE register cannot be used when SSE is disabled!");
2685
2686   // 64-bit calling conventions support varargs and register parameters, so we
2687   // have to do extra work to spill them in the prologue.
2688   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2689     // Find the first unallocated argument registers.
2690     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2691     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2692     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2693     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2694     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2695            "SSE register cannot be used when SSE is disabled!");
2696
2697     // Gather all the live in physical registers.
2698     SmallVector<SDValue, 6> LiveGPRs;
2699     SmallVector<SDValue, 8> LiveXMMRegs;
2700     SDValue ALVal;
2701     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2702       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2703       LiveGPRs.push_back(
2704           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2705     }
2706     if (!ArgXMMs.empty()) {
2707       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2708       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2709       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2710         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2711         LiveXMMRegs.push_back(
2712             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2713       }
2714     }
2715
2716     if (IsWin64) {
2717       // Get to the caller-allocated home save location.  Add 8 to account
2718       // for the return address.
2719       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2720       FuncInfo->setRegSaveFrameIndex(
2721           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2722       // Fixup to set vararg frame on shadow area (4 x i64).
2723       if (NumIntRegs < 4)
2724         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2725     } else {
2726       // For X86-64, if there are vararg parameters that are passed via
2727       // registers, then we must store them to their spots on the stack so
2728       // they may be loaded by deferencing the result of va_next.
2729       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2730       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2731       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2732           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2733     }
2734
2735     // Store the integer parameter registers.
2736     SmallVector<SDValue, 8> MemOps;
2737     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2738                                       getPointerTy(DAG.getDataLayout()));
2739     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2740     for (SDValue Val : LiveGPRs) {
2741       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2742                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2743       SDValue Store =
2744           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2745                        MachinePointerInfo::getFixedStack(
2746                            DAG.getMachineFunction(),
2747                            FuncInfo->getRegSaveFrameIndex(), Offset),
2748                        false, false, 0);
2749       MemOps.push_back(Store);
2750       Offset += 8;
2751     }
2752
2753     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2754       // Now store the XMM (fp + vector) parameter registers.
2755       SmallVector<SDValue, 12> SaveXMMOps;
2756       SaveXMMOps.push_back(Chain);
2757       SaveXMMOps.push_back(ALVal);
2758       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2759                              FuncInfo->getRegSaveFrameIndex(), dl));
2760       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2761                              FuncInfo->getVarArgsFPOffset(), dl));
2762       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2763                         LiveXMMRegs.end());
2764       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2765                                    MVT::Other, SaveXMMOps));
2766     }
2767
2768     if (!MemOps.empty())
2769       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2770   }
2771
2772   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2773     // Find the largest legal vector type.
2774     MVT VecVT = MVT::Other;
2775     // FIXME: Only some x86_32 calling conventions support AVX512.
2776     if (Subtarget->hasAVX512() &&
2777         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2778                      CallConv == CallingConv::Intel_OCL_BI)))
2779       VecVT = MVT::v16f32;
2780     else if (Subtarget->hasAVX())
2781       VecVT = MVT::v8f32;
2782     else if (Subtarget->hasSSE2())
2783       VecVT = MVT::v4f32;
2784
2785     // We forward some GPRs and some vector types.
2786     SmallVector<MVT, 2> RegParmTypes;
2787     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2788     RegParmTypes.push_back(IntVT);
2789     if (VecVT != MVT::Other)
2790       RegParmTypes.push_back(VecVT);
2791
2792     // Compute the set of forwarded registers. The rest are scratch.
2793     SmallVectorImpl<ForwardedRegister> &Forwards =
2794         FuncInfo->getForwardedMustTailRegParms();
2795     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2796
2797     // Conservatively forward AL on x86_64, since it might be used for varargs.
2798     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2799       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2800       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2801     }
2802
2803     // Copy all forwards from physical to virtual registers.
2804     for (ForwardedRegister &F : Forwards) {
2805       // FIXME: Can we use a less constrained schedule?
2806       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2807       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2808       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2809     }
2810   }
2811
2812   // Some CCs need callee pop.
2813   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2814                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2815     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2816   } else {
2817     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2818     // If this is an sret function, the return should pop the hidden pointer.
2819     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2820         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2821         argsAreStructReturn(Ins) == StackStructReturn)
2822       FuncInfo->setBytesToPopOnReturn(4);
2823   }
2824
2825   if (!Is64Bit) {
2826     // RegSaveFrameIndex is X86-64 only.
2827     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2828     if (CallConv == CallingConv::X86_FastCall ||
2829         CallConv == CallingConv::X86_ThisCall)
2830       // fastcc functions can't have varargs.
2831       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2832   }
2833
2834   FuncInfo->setArgumentStackSize(StackSize);
2835
2836   if (IsWinEHParent) {
2837     if (Is64Bit) {
2838       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2839       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2840       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2841       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2842       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2843                            MachinePointerInfo::getFixedStack(
2844                                DAG.getMachineFunction(), UnwindHelpFI),
2845                            /*isVolatile=*/true,
2846                            /*isNonTemporal=*/false, /*Alignment=*/0);
2847     } else {
2848       // Functions using Win32 EH are considered to have opaque SP adjustments
2849       // to force local variables to be addressed from the frame or base
2850       // pointers.
2851       MFI->setHasOpaqueSPAdjustment(true);
2852     }
2853   }
2854
2855   return Chain;
2856 }
2857
2858 SDValue
2859 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2860                                     SDValue StackPtr, SDValue Arg,
2861                                     SDLoc dl, SelectionDAG &DAG,
2862                                     const CCValAssign &VA,
2863                                     ISD::ArgFlagsTy Flags) const {
2864   unsigned LocMemOffset = VA.getLocMemOffset();
2865   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2866   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2867                        StackPtr, PtrOff);
2868   if (Flags.isByVal())
2869     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2870
2871   return DAG.getStore(
2872       Chain, dl, Arg, PtrOff,
2873       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2874       false, false, 0);
2875 }
2876
2877 /// Emit a load of return address if tail call
2878 /// optimization is performed and it is required.
2879 SDValue
2880 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2881                                            SDValue &OutRetAddr, SDValue Chain,
2882                                            bool IsTailCall, bool Is64Bit,
2883                                            int FPDiff, SDLoc dl) const {
2884   // Adjust the Return address stack slot.
2885   EVT VT = getPointerTy(DAG.getDataLayout());
2886   OutRetAddr = getReturnAddressFrameIndex(DAG);
2887
2888   // Load the "old" Return address.
2889   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2890                            false, false, false, 0);
2891   return SDValue(OutRetAddr.getNode(), 1);
2892 }
2893
2894 /// Emit a store of the return address if tail call
2895 /// optimization is performed and it is required (FPDiff!=0).
2896 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2897                                         SDValue Chain, SDValue RetAddrFrIdx,
2898                                         EVT PtrVT, unsigned SlotSize,
2899                                         int FPDiff, SDLoc dl) {
2900   // Store the return address to the appropriate stack slot.
2901   if (!FPDiff) return Chain;
2902   // Calculate the new stack slot for the return address.
2903   int NewReturnAddrFI =
2904     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2905                                          false);
2906   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2907   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2908                        MachinePointerInfo::getFixedStack(
2909                            DAG.getMachineFunction(), NewReturnAddrFI),
2910                        false, false, 0);
2911   return Chain;
2912 }
2913
2914 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2915 /// operation of specified width.
2916 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2917                        SDValue V2) {
2918   unsigned NumElems = VT.getVectorNumElements();
2919   SmallVector<int, 8> Mask;
2920   Mask.push_back(NumElems);
2921   for (unsigned i = 1; i != NumElems; ++i)
2922     Mask.push_back(i);
2923   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2924 }
2925
2926 SDValue
2927 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2928                              SmallVectorImpl<SDValue> &InVals) const {
2929   SelectionDAG &DAG                     = CLI.DAG;
2930   SDLoc &dl                             = CLI.DL;
2931   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2932   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2933   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2934   SDValue Chain                         = CLI.Chain;
2935   SDValue Callee                        = CLI.Callee;
2936   CallingConv::ID CallConv              = CLI.CallConv;
2937   bool &isTailCall                      = CLI.IsTailCall;
2938   bool isVarArg                         = CLI.IsVarArg;
2939
2940   MachineFunction &MF = DAG.getMachineFunction();
2941   bool Is64Bit        = Subtarget->is64Bit();
2942   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2943   StructReturnType SR = callIsStructReturn(Outs);
2944   bool IsSibcall      = false;
2945   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2946   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2947
2948   if (Attr.getValueAsString() == "true")
2949     isTailCall = false;
2950
2951   if (Subtarget->isPICStyleGOT() &&
2952       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2953     // If we are using a GOT, disable tail calls to external symbols with
2954     // default visibility. Tail calling such a symbol requires using a GOT
2955     // relocation, which forces early binding of the symbol. This breaks code
2956     // that require lazy function symbol resolution. Using musttail or
2957     // GuaranteedTailCallOpt will override this.
2958     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2959     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2960                G->getGlobal()->hasDefaultVisibility()))
2961       isTailCall = false;
2962   }
2963
2964   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2965   if (IsMustTail) {
2966     // Force this to be a tail call.  The verifier rules are enough to ensure
2967     // that we can lower this successfully without moving the return address
2968     // around.
2969     isTailCall = true;
2970   } else if (isTailCall) {
2971     // Check if it's really possible to do a tail call.
2972     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2973                     isVarArg, SR != NotStructReturn,
2974                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2975                     Outs, OutVals, Ins, DAG);
2976
2977     // Sibcalls are automatically detected tailcalls which do not require
2978     // ABI changes.
2979     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2980       IsSibcall = true;
2981
2982     if (isTailCall)
2983       ++NumTailCalls;
2984   }
2985
2986   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2987          "Var args not supported with calling convention fastcc, ghc or hipe");
2988
2989   // Analyze operands of the call, assigning locations to each operand.
2990   SmallVector<CCValAssign, 16> ArgLocs;
2991   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2992
2993   // Allocate shadow area for Win64
2994   if (IsWin64)
2995     CCInfo.AllocateStack(32, 8);
2996
2997   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2998
2999   // Get a count of how many bytes are to be pushed on the stack.
3000   unsigned NumBytes = CCInfo.getNextStackOffset();
3001   if (IsSibcall)
3002     // This is a sibcall. The memory operands are available in caller's
3003     // own caller's stack.
3004     NumBytes = 0;
3005   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3006            IsTailCallConvention(CallConv))
3007     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3008
3009   int FPDiff = 0;
3010   if (isTailCall && !IsSibcall && !IsMustTail) {
3011     // Lower arguments at fp - stackoffset + fpdiff.
3012     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3013
3014     FPDiff = NumBytesCallerPushed - NumBytes;
3015
3016     // Set the delta of movement of the returnaddr stackslot.
3017     // But only set if delta is greater than previous delta.
3018     if (FPDiff < X86Info->getTCReturnAddrDelta())
3019       X86Info->setTCReturnAddrDelta(FPDiff);
3020   }
3021
3022   unsigned NumBytesToPush = NumBytes;
3023   unsigned NumBytesToPop = NumBytes;
3024
3025   // If we have an inalloca argument, all stack space has already been allocated
3026   // for us and be right at the top of the stack.  We don't support multiple
3027   // arguments passed in memory when using inalloca.
3028   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3029     NumBytesToPush = 0;
3030     if (!ArgLocs.back().isMemLoc())
3031       report_fatal_error("cannot use inalloca attribute on a register "
3032                          "parameter");
3033     if (ArgLocs.back().getLocMemOffset() != 0)
3034       report_fatal_error("any parameter with the inalloca attribute must be "
3035                          "the only memory argument");
3036   }
3037
3038   if (!IsSibcall)
3039     Chain = DAG.getCALLSEQ_START(
3040         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3041
3042   SDValue RetAddrFrIdx;
3043   // Load return address for tail calls.
3044   if (isTailCall && FPDiff)
3045     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3046                                     Is64Bit, FPDiff, dl);
3047
3048   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3049   SmallVector<SDValue, 8> MemOpChains;
3050   SDValue StackPtr;
3051
3052   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3053   // of tail call optimization arguments are handle later.
3054   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3055   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3056     // Skip inalloca arguments, they have already been written.
3057     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3058     if (Flags.isInAlloca())
3059       continue;
3060
3061     CCValAssign &VA = ArgLocs[i];
3062     EVT RegVT = VA.getLocVT();
3063     SDValue Arg = OutVals[i];
3064     bool isByVal = Flags.isByVal();
3065
3066     // Promote the value if needed.
3067     switch (VA.getLocInfo()) {
3068     default: llvm_unreachable("Unknown loc info!");
3069     case CCValAssign::Full: break;
3070     case CCValAssign::SExt:
3071       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3072       break;
3073     case CCValAssign::ZExt:
3074       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3075       break;
3076     case CCValAssign::AExt:
3077       if (Arg.getValueType().isVector() &&
3078           Arg.getValueType().getScalarType() == MVT::i1)
3079         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3080       else if (RegVT.is128BitVector()) {
3081         // Special case: passing MMX values in XMM registers.
3082         Arg = DAG.getBitcast(MVT::i64, Arg);
3083         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3084         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3085       } else
3086         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3087       break;
3088     case CCValAssign::BCvt:
3089       Arg = DAG.getBitcast(RegVT, Arg);
3090       break;
3091     case CCValAssign::Indirect: {
3092       // Store the argument.
3093       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3094       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3095       Chain = DAG.getStore(
3096           Chain, dl, Arg, SpillSlot,
3097           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3098           false, false, 0);
3099       Arg = SpillSlot;
3100       break;
3101     }
3102     }
3103
3104     if (VA.isRegLoc()) {
3105       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3106       if (isVarArg && IsWin64) {
3107         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3108         // shadow reg if callee is a varargs function.
3109         unsigned ShadowReg = 0;
3110         switch (VA.getLocReg()) {
3111         case X86::XMM0: ShadowReg = X86::RCX; break;
3112         case X86::XMM1: ShadowReg = X86::RDX; break;
3113         case X86::XMM2: ShadowReg = X86::R8; break;
3114         case X86::XMM3: ShadowReg = X86::R9; break;
3115         }
3116         if (ShadowReg)
3117           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3118       }
3119     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3120       assert(VA.isMemLoc());
3121       if (!StackPtr.getNode())
3122         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3123                                       getPointerTy(DAG.getDataLayout()));
3124       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3125                                              dl, DAG, VA, Flags));
3126     }
3127   }
3128
3129   if (!MemOpChains.empty())
3130     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3131
3132   if (Subtarget->isPICStyleGOT()) {
3133     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3134     // GOT pointer.
3135     if (!isTailCall) {
3136       RegsToPass.push_back(std::make_pair(
3137           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3138                                           getPointerTy(DAG.getDataLayout()))));
3139     } else {
3140       // If we are tail calling and generating PIC/GOT style code load the
3141       // address of the callee into ECX. The value in ecx is used as target of
3142       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3143       // for tail calls on PIC/GOT architectures. Normally we would just put the
3144       // address of GOT into ebx and then call target@PLT. But for tail calls
3145       // ebx would be restored (since ebx is callee saved) before jumping to the
3146       // target@PLT.
3147
3148       // Note: The actual moving to ECX is done further down.
3149       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3150       if (G && !G->getGlobal()->hasLocalLinkage() &&
3151           G->getGlobal()->hasDefaultVisibility())
3152         Callee = LowerGlobalAddress(Callee, DAG);
3153       else if (isa<ExternalSymbolSDNode>(Callee))
3154         Callee = LowerExternalSymbol(Callee, DAG);
3155     }
3156   }
3157
3158   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3159     // From AMD64 ABI document:
3160     // For calls that may call functions that use varargs or stdargs
3161     // (prototype-less calls or calls to functions containing ellipsis (...) in
3162     // the declaration) %al is used as hidden argument to specify the number
3163     // of SSE registers used. The contents of %al do not need to match exactly
3164     // the number of registers, but must be an ubound on the number of SSE
3165     // registers used and is in the range 0 - 8 inclusive.
3166
3167     // Count the number of XMM registers allocated.
3168     static const MCPhysReg XMMArgRegs[] = {
3169       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3170       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3171     };
3172     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3173     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3174            && "SSE registers cannot be used when SSE is disabled");
3175
3176     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3177                                         DAG.getConstant(NumXMMRegs, dl,
3178                                                         MVT::i8)));
3179   }
3180
3181   if (isVarArg && IsMustTail) {
3182     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3183     for (const auto &F : Forwards) {
3184       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3185       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3186     }
3187   }
3188
3189   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3190   // don't need this because the eligibility check rejects calls that require
3191   // shuffling arguments passed in memory.
3192   if (!IsSibcall && isTailCall) {
3193     // Force all the incoming stack arguments to be loaded from the stack
3194     // before any new outgoing arguments are stored to the stack, because the
3195     // outgoing stack slots may alias the incoming argument stack slots, and
3196     // the alias isn't otherwise explicit. This is slightly more conservative
3197     // than necessary, because it means that each store effectively depends
3198     // on every argument instead of just those arguments it would clobber.
3199     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3200
3201     SmallVector<SDValue, 8> MemOpChains2;
3202     SDValue FIN;
3203     int FI = 0;
3204     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3205       CCValAssign &VA = ArgLocs[i];
3206       if (VA.isRegLoc())
3207         continue;
3208       assert(VA.isMemLoc());
3209       SDValue Arg = OutVals[i];
3210       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3211       // Skip inalloca arguments.  They don't require any work.
3212       if (Flags.isInAlloca())
3213         continue;
3214       // Create frame index.
3215       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3216       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3217       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3218       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3219
3220       if (Flags.isByVal()) {
3221         // Copy relative to framepointer.
3222         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3223         if (!StackPtr.getNode())
3224           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3225                                         getPointerTy(DAG.getDataLayout()));
3226         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3227                              StackPtr, Source);
3228
3229         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3230                                                          ArgChain,
3231                                                          Flags, DAG, dl));
3232       } else {
3233         // Store relative to framepointer.
3234         MemOpChains2.push_back(DAG.getStore(
3235             ArgChain, dl, Arg, FIN,
3236             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3237             false, false, 0));
3238       }
3239     }
3240
3241     if (!MemOpChains2.empty())
3242       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3243
3244     // Store the return address to the appropriate stack slot.
3245     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3246                                      getPointerTy(DAG.getDataLayout()),
3247                                      RegInfo->getSlotSize(), FPDiff, dl);
3248   }
3249
3250   // Build a sequence of copy-to-reg nodes chained together with token chain
3251   // and flag operands which copy the outgoing args into registers.
3252   SDValue InFlag;
3253   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3254     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3255                              RegsToPass[i].second, InFlag);
3256     InFlag = Chain.getValue(1);
3257   }
3258
3259   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3260     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3261     // In the 64-bit large code model, we have to make all calls
3262     // through a register, since the call instruction's 32-bit
3263     // pc-relative offset may not be large enough to hold the whole
3264     // address.
3265   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3266     // If the callee is a GlobalAddress node (quite common, every direct call
3267     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3268     // it.
3269     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3270
3271     // We should use extra load for direct calls to dllimported functions in
3272     // non-JIT mode.
3273     const GlobalValue *GV = G->getGlobal();
3274     if (!GV->hasDLLImportStorageClass()) {
3275       unsigned char OpFlags = 0;
3276       bool ExtraLoad = false;
3277       unsigned WrapperKind = ISD::DELETED_NODE;
3278
3279       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3280       // external symbols most go through the PLT in PIC mode.  If the symbol
3281       // has hidden or protected visibility, or if it is static or local, then
3282       // we don't need to use the PLT - we can directly call it.
3283       if (Subtarget->isTargetELF() &&
3284           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3285           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3286         OpFlags = X86II::MO_PLT;
3287       } else if (Subtarget->isPICStyleStubAny() &&
3288                  !GV->isStrongDefinitionForLinker() &&
3289                  (!Subtarget->getTargetTriple().isMacOSX() ||
3290                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3291         // PC-relative references to external symbols should go through $stub,
3292         // unless we're building with the leopard linker or later, which
3293         // automatically synthesizes these stubs.
3294         OpFlags = X86II::MO_DARWIN_STUB;
3295       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3296                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3297         // If the function is marked as non-lazy, generate an indirect call
3298         // which loads from the GOT directly. This avoids runtime overhead
3299         // at the cost of eager binding (and one extra byte of encoding).
3300         OpFlags = X86II::MO_GOTPCREL;
3301         WrapperKind = X86ISD::WrapperRIP;
3302         ExtraLoad = true;
3303       }
3304
3305       Callee = DAG.getTargetGlobalAddress(
3306           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3307
3308       // Add a wrapper if needed.
3309       if (WrapperKind != ISD::DELETED_NODE)
3310         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3311                              getPointerTy(DAG.getDataLayout()), Callee);
3312       // Add extra indirection if needed.
3313       if (ExtraLoad)
3314         Callee = DAG.getLoad(
3315             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3316             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3317             false, 0);
3318     }
3319   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3320     unsigned char OpFlags = 0;
3321
3322     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3323     // external symbols should go through the PLT.
3324     if (Subtarget->isTargetELF() &&
3325         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3326       OpFlags = X86II::MO_PLT;
3327     } else if (Subtarget->isPICStyleStubAny() &&
3328                (!Subtarget->getTargetTriple().isMacOSX() ||
3329                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3330       // PC-relative references to external symbols should go through $stub,
3331       // unless we're building with the leopard linker or later, which
3332       // automatically synthesizes these stubs.
3333       OpFlags = X86II::MO_DARWIN_STUB;
3334     }
3335
3336     Callee = DAG.getTargetExternalSymbol(
3337         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3338   } else if (Subtarget->isTarget64BitILP32() &&
3339              Callee->getValueType(0) == MVT::i32) {
3340     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3341     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3342   }
3343
3344   // Returns a chain & a flag for retval copy to use.
3345   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3346   SmallVector<SDValue, 8> Ops;
3347
3348   if (!IsSibcall && isTailCall) {
3349     Chain = DAG.getCALLSEQ_END(Chain,
3350                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3351                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3352     InFlag = Chain.getValue(1);
3353   }
3354
3355   Ops.push_back(Chain);
3356   Ops.push_back(Callee);
3357
3358   if (isTailCall)
3359     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3360
3361   // Add argument registers to the end of the list so that they are known live
3362   // into the call.
3363   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3364     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3365                                   RegsToPass[i].second.getValueType()));
3366
3367   // Add a register mask operand representing the call-preserved registers.
3368   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3369   assert(Mask && "Missing call preserved mask for calling convention");
3370
3371   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3372   // the function clobbers all registers. If an exception is thrown, the runtime
3373   // will not restore CSRs.
3374   // FIXME: Model this more precisely so that we can register allocate across
3375   // the normal edge and spill and fill across the exceptional edge.
3376   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3377     const Function *CallerFn = MF.getFunction();
3378     EHPersonality Pers =
3379         CallerFn->hasPersonalityFn()
3380             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3381             : EHPersonality::Unknown;
3382     if (isMSVCEHPersonality(Pers))
3383       Mask = RegInfo->getNoPreservedMask();
3384   }
3385
3386   Ops.push_back(DAG.getRegisterMask(Mask));
3387
3388   if (InFlag.getNode())
3389     Ops.push_back(InFlag);
3390
3391   if (isTailCall) {
3392     // We used to do:
3393     //// If this is the first return lowered for this function, add the regs
3394     //// to the liveout set for the function.
3395     // This isn't right, although it's probably harmless on x86; liveouts
3396     // should be computed from returns not tail calls.  Consider a void
3397     // function making a tail call to a function returning int.
3398     MF.getFrameInfo()->setHasTailCall();
3399     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3400   }
3401
3402   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3403   InFlag = Chain.getValue(1);
3404
3405   // Create the CALLSEQ_END node.
3406   unsigned NumBytesForCalleeToPop;
3407   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3408                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3409     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3410   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3411            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3412            SR == StackStructReturn)
3413     // If this is a call to a struct-return function, the callee
3414     // pops the hidden struct pointer, so we have to push it back.
3415     // This is common for Darwin/X86, Linux & Mingw32 targets.
3416     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3417     NumBytesForCalleeToPop = 4;
3418   else
3419     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3420
3421   // Returns a flag for retval copy to use.
3422   if (!IsSibcall) {
3423     Chain = DAG.getCALLSEQ_END(Chain,
3424                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3425                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3426                                                      true),
3427                                InFlag, dl);
3428     InFlag = Chain.getValue(1);
3429   }
3430
3431   // Handle result values, copying them out of physregs into vregs that we
3432   // return.
3433   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3434                          Ins, dl, DAG, InVals);
3435 }
3436
3437 //===----------------------------------------------------------------------===//
3438 //                Fast Calling Convention (tail call) implementation
3439 //===----------------------------------------------------------------------===//
3440
3441 //  Like std call, callee cleans arguments, convention except that ECX is
3442 //  reserved for storing the tail called function address. Only 2 registers are
3443 //  free for argument passing (inreg). Tail call optimization is performed
3444 //  provided:
3445 //                * tailcallopt is enabled
3446 //                * caller/callee are fastcc
3447 //  On X86_64 architecture with GOT-style position independent code only local
3448 //  (within module) calls are supported at the moment.
3449 //  To keep the stack aligned according to platform abi the function
3450 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3451 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3452 //  If a tail called function callee has more arguments than the caller the
3453 //  caller needs to make sure that there is room to move the RETADDR to. This is
3454 //  achieved by reserving an area the size of the argument delta right after the
3455 //  original RETADDR, but before the saved framepointer or the spilled registers
3456 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3457 //  stack layout:
3458 //    arg1
3459 //    arg2
3460 //    RETADDR
3461 //    [ new RETADDR
3462 //      move area ]
3463 //    (possible EBP)
3464 //    ESI
3465 //    EDI
3466 //    local1 ..
3467
3468 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3469 /// requirement.
3470 unsigned
3471 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3472                                                SelectionDAG& DAG) const {
3473   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3474   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3475   unsigned StackAlignment = TFI.getStackAlignment();
3476   uint64_t AlignMask = StackAlignment - 1;
3477   int64_t Offset = StackSize;
3478   unsigned SlotSize = RegInfo->getSlotSize();
3479   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3480     // Number smaller than 12 so just add the difference.
3481     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3482   } else {
3483     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3484     Offset = ((~AlignMask) & Offset) + StackAlignment +
3485       (StackAlignment-SlotSize);
3486   }
3487   return Offset;
3488 }
3489
3490 /// Return true if the given stack call argument is already available in the
3491 /// same position (relatively) of the caller's incoming argument stack.
3492 static
3493 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3494                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3495                          const X86InstrInfo *TII) {
3496   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3497   int FI = INT_MAX;
3498   if (Arg.getOpcode() == ISD::CopyFromReg) {
3499     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3500     if (!TargetRegisterInfo::isVirtualRegister(VR))
3501       return false;
3502     MachineInstr *Def = MRI->getVRegDef(VR);
3503     if (!Def)
3504       return false;
3505     if (!Flags.isByVal()) {
3506       if (!TII->isLoadFromStackSlot(Def, FI))
3507         return false;
3508     } else {
3509       unsigned Opcode = Def->getOpcode();
3510       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3511            Opcode == X86::LEA64_32r) &&
3512           Def->getOperand(1).isFI()) {
3513         FI = Def->getOperand(1).getIndex();
3514         Bytes = Flags.getByValSize();
3515       } else
3516         return false;
3517     }
3518   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3519     if (Flags.isByVal())
3520       // ByVal argument is passed in as a pointer but it's now being
3521       // dereferenced. e.g.
3522       // define @foo(%struct.X* %A) {
3523       //   tail call @bar(%struct.X* byval %A)
3524       // }
3525       return false;
3526     SDValue Ptr = Ld->getBasePtr();
3527     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3528     if (!FINode)
3529       return false;
3530     FI = FINode->getIndex();
3531   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3532     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3533     FI = FINode->getIndex();
3534     Bytes = Flags.getByValSize();
3535   } else
3536     return false;
3537
3538   assert(FI != INT_MAX);
3539   if (!MFI->isFixedObjectIndex(FI))
3540     return false;
3541   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3542 }
3543
3544 /// Check whether the call is eligible for tail call optimization. Targets
3545 /// that want to do tail call optimization should implement this function.
3546 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3547     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3548     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3549     const SmallVectorImpl<ISD::OutputArg> &Outs,
3550     const SmallVectorImpl<SDValue> &OutVals,
3551     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3552   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3553     return false;
3554
3555   // If -tailcallopt is specified, make fastcc functions tail-callable.
3556   const MachineFunction &MF = DAG.getMachineFunction();
3557   const Function *CallerF = MF.getFunction();
3558
3559   // If the function return type is x86_fp80 and the callee return type is not,
3560   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3561   // perform a tailcall optimization here.
3562   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3563     return false;
3564
3565   CallingConv::ID CallerCC = CallerF->getCallingConv();
3566   bool CCMatch = CallerCC == CalleeCC;
3567   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3568   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3569
3570   // Win64 functions have extra shadow space for argument homing. Don't do the
3571   // sibcall if the caller and callee have mismatched expectations for this
3572   // space.
3573   if (IsCalleeWin64 != IsCallerWin64)
3574     return false;
3575
3576   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3577     if (IsTailCallConvention(CalleeCC) && CCMatch)
3578       return true;
3579     return false;
3580   }
3581
3582   // Look for obvious safe cases to perform tail call optimization that do not
3583   // require ABI changes. This is what gcc calls sibcall.
3584
3585   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3586   // emit a special epilogue.
3587   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3588   if (RegInfo->needsStackRealignment(MF))
3589     return false;
3590
3591   // Also avoid sibcall optimization if either caller or callee uses struct
3592   // return semantics.
3593   if (isCalleeStructRet || isCallerStructRet)
3594     return false;
3595
3596   // An stdcall/thiscall caller is expected to clean up its arguments; the
3597   // callee isn't going to do that.
3598   // FIXME: this is more restrictive than needed. We could produce a tailcall
3599   // when the stack adjustment matches. For example, with a thiscall that takes
3600   // only one argument.
3601   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3602                    CallerCC == CallingConv::X86_ThisCall))
3603     return false;
3604
3605   // Do not sibcall optimize vararg calls unless all arguments are passed via
3606   // registers.
3607   if (isVarArg && !Outs.empty()) {
3608
3609     // Optimizing for varargs on Win64 is unlikely to be safe without
3610     // additional testing.
3611     if (IsCalleeWin64 || IsCallerWin64)
3612       return false;
3613
3614     SmallVector<CCValAssign, 16> ArgLocs;
3615     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3616                    *DAG.getContext());
3617
3618     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3619     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3620       if (!ArgLocs[i].isRegLoc())
3621         return false;
3622   }
3623
3624   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3625   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3626   // this into a sibcall.
3627   bool Unused = false;
3628   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3629     if (!Ins[i].Used) {
3630       Unused = true;
3631       break;
3632     }
3633   }
3634   if (Unused) {
3635     SmallVector<CCValAssign, 16> RVLocs;
3636     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3637                    *DAG.getContext());
3638     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3639     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3640       CCValAssign &VA = RVLocs[i];
3641       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3642         return false;
3643     }
3644   }
3645
3646   // If the calling conventions do not match, then we'd better make sure the
3647   // results are returned in the same way as what the caller expects.
3648   if (!CCMatch) {
3649     SmallVector<CCValAssign, 16> RVLocs1;
3650     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3651                     *DAG.getContext());
3652     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3653
3654     SmallVector<CCValAssign, 16> RVLocs2;
3655     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3656                     *DAG.getContext());
3657     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3658
3659     if (RVLocs1.size() != RVLocs2.size())
3660       return false;
3661     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3662       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3663         return false;
3664       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3665         return false;
3666       if (RVLocs1[i].isRegLoc()) {
3667         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3668           return false;
3669       } else {
3670         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3671           return false;
3672       }
3673     }
3674   }
3675
3676   // If the callee takes no arguments then go on to check the results of the
3677   // call.
3678   if (!Outs.empty()) {
3679     // Check if stack adjustment is needed. For now, do not do this if any
3680     // argument is passed on the stack.
3681     SmallVector<CCValAssign, 16> ArgLocs;
3682     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3683                    *DAG.getContext());
3684
3685     // Allocate shadow area for Win64
3686     if (IsCalleeWin64)
3687       CCInfo.AllocateStack(32, 8);
3688
3689     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3690     if (CCInfo.getNextStackOffset()) {
3691       MachineFunction &MF = DAG.getMachineFunction();
3692       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3693         return false;
3694
3695       // Check if the arguments are already laid out in the right way as
3696       // the caller's fixed stack objects.
3697       MachineFrameInfo *MFI = MF.getFrameInfo();
3698       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3699       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3700       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3701         CCValAssign &VA = ArgLocs[i];
3702         SDValue Arg = OutVals[i];
3703         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3704         if (VA.getLocInfo() == CCValAssign::Indirect)
3705           return false;
3706         if (!VA.isRegLoc()) {
3707           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3708                                    MFI, MRI, TII))
3709             return false;
3710         }
3711       }
3712     }
3713
3714     // If the tailcall address may be in a register, then make sure it's
3715     // possible to register allocate for it. In 32-bit, the call address can
3716     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3717     // callee-saved registers are restored. These happen to be the same
3718     // registers used to pass 'inreg' arguments so watch out for those.
3719     if (!Subtarget->is64Bit() &&
3720         ((!isa<GlobalAddressSDNode>(Callee) &&
3721           !isa<ExternalSymbolSDNode>(Callee)) ||
3722          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3723       unsigned NumInRegs = 0;
3724       // In PIC we need an extra register to formulate the address computation
3725       // for the callee.
3726       unsigned MaxInRegs =
3727         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3728
3729       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3730         CCValAssign &VA = ArgLocs[i];
3731         if (!VA.isRegLoc())
3732           continue;
3733         unsigned Reg = VA.getLocReg();
3734         switch (Reg) {
3735         default: break;
3736         case X86::EAX: case X86::EDX: case X86::ECX:
3737           if (++NumInRegs == MaxInRegs)
3738             return false;
3739           break;
3740         }
3741       }
3742     }
3743   }
3744
3745   return true;
3746 }
3747
3748 FastISel *
3749 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3750                                   const TargetLibraryInfo *libInfo) const {
3751   return X86::createFastISel(funcInfo, libInfo);
3752 }
3753
3754 //===----------------------------------------------------------------------===//
3755 //                           Other Lowering Hooks
3756 //===----------------------------------------------------------------------===//
3757
3758 static bool MayFoldLoad(SDValue Op) {
3759   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3760 }
3761
3762 static bool MayFoldIntoStore(SDValue Op) {
3763   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3764 }
3765
3766 static bool isTargetShuffle(unsigned Opcode) {
3767   switch(Opcode) {
3768   default: return false;
3769   case X86ISD::BLENDI:
3770   case X86ISD::PSHUFB:
3771   case X86ISD::PSHUFD:
3772   case X86ISD::PSHUFHW:
3773   case X86ISD::PSHUFLW:
3774   case X86ISD::SHUFP:
3775   case X86ISD::PALIGNR:
3776   case X86ISD::MOVLHPS:
3777   case X86ISD::MOVLHPD:
3778   case X86ISD::MOVHLPS:
3779   case X86ISD::MOVLPS:
3780   case X86ISD::MOVLPD:
3781   case X86ISD::MOVSHDUP:
3782   case X86ISD::MOVSLDUP:
3783   case X86ISD::MOVDDUP:
3784   case X86ISD::MOVSS:
3785   case X86ISD::MOVSD:
3786   case X86ISD::UNPCKL:
3787   case X86ISD::UNPCKH:
3788   case X86ISD::VPERMILPI:
3789   case X86ISD::VPERM2X128:
3790   case X86ISD::VPERMI:
3791   case X86ISD::VPERMV:
3792   case X86ISD::VPERMV3:
3793     return true;
3794   }
3795 }
3796
3797 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3798                                     SDValue V1, unsigned TargetMask,
3799                                     SelectionDAG &DAG) {
3800   switch(Opc) {
3801   default: llvm_unreachable("Unknown x86 shuffle node");
3802   case X86ISD::PSHUFD:
3803   case X86ISD::PSHUFHW:
3804   case X86ISD::PSHUFLW:
3805   case X86ISD::VPERMILPI:
3806   case X86ISD::VPERMI:
3807     return DAG.getNode(Opc, dl, VT, V1,
3808                        DAG.getConstant(TargetMask, dl, MVT::i8));
3809   }
3810 }
3811
3812 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3813                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3814   switch(Opc) {
3815   default: llvm_unreachable("Unknown x86 shuffle node");
3816   case X86ISD::MOVLHPS:
3817   case X86ISD::MOVLHPD:
3818   case X86ISD::MOVHLPS:
3819   case X86ISD::MOVLPS:
3820   case X86ISD::MOVLPD:
3821   case X86ISD::MOVSS:
3822   case X86ISD::MOVSD:
3823   case X86ISD::UNPCKL:
3824   case X86ISD::UNPCKH:
3825     return DAG.getNode(Opc, dl, VT, V1, V2);
3826   }
3827 }
3828
3829 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3830   MachineFunction &MF = DAG.getMachineFunction();
3831   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3832   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3833   int ReturnAddrIndex = FuncInfo->getRAIndex();
3834
3835   if (ReturnAddrIndex == 0) {
3836     // Set up a frame object for the return address.
3837     unsigned SlotSize = RegInfo->getSlotSize();
3838     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3839                                                            -(int64_t)SlotSize,
3840                                                            false);
3841     FuncInfo->setRAIndex(ReturnAddrIndex);
3842   }
3843
3844   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3845 }
3846
3847 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3848                                        bool hasSymbolicDisplacement) {
3849   // Offset should fit into 32 bit immediate field.
3850   if (!isInt<32>(Offset))
3851     return false;
3852
3853   // If we don't have a symbolic displacement - we don't have any extra
3854   // restrictions.
3855   if (!hasSymbolicDisplacement)
3856     return true;
3857
3858   // FIXME: Some tweaks might be needed for medium code model.
3859   if (M != CodeModel::Small && M != CodeModel::Kernel)
3860     return false;
3861
3862   // For small code model we assume that latest object is 16MB before end of 31
3863   // bits boundary. We may also accept pretty large negative constants knowing
3864   // that all objects are in the positive half of address space.
3865   if (M == CodeModel::Small && Offset < 16*1024*1024)
3866     return true;
3867
3868   // For kernel code model we know that all object resist in the negative half
3869   // of 32bits address space. We may not accept negative offsets, since they may
3870   // be just off and we may accept pretty large positive ones.
3871   if (M == CodeModel::Kernel && Offset >= 0)
3872     return true;
3873
3874   return false;
3875 }
3876
3877 /// Determines whether the callee is required to pop its own arguments.
3878 /// Callee pop is necessary to support tail calls.
3879 bool X86::isCalleePop(CallingConv::ID CallingConv,
3880                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3881   switch (CallingConv) {
3882   default:
3883     return false;
3884   case CallingConv::X86_StdCall:
3885   case CallingConv::X86_FastCall:
3886   case CallingConv::X86_ThisCall:
3887     return !is64Bit;
3888   case CallingConv::Fast:
3889   case CallingConv::GHC:
3890   case CallingConv::HiPE:
3891     if (IsVarArg)
3892       return false;
3893     return TailCallOpt;
3894   }
3895 }
3896
3897 /// \brief Return true if the condition is an unsigned comparison operation.
3898 static bool isX86CCUnsigned(unsigned X86CC) {
3899   switch (X86CC) {
3900   default: llvm_unreachable("Invalid integer condition!");
3901   case X86::COND_E:     return true;
3902   case X86::COND_G:     return false;
3903   case X86::COND_GE:    return false;
3904   case X86::COND_L:     return false;
3905   case X86::COND_LE:    return false;
3906   case X86::COND_NE:    return true;
3907   case X86::COND_B:     return true;
3908   case X86::COND_A:     return true;
3909   case X86::COND_BE:    return true;
3910   case X86::COND_AE:    return true;
3911   }
3912   llvm_unreachable("covered switch fell through?!");
3913 }
3914
3915 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3916 /// condition code, returning the condition code and the LHS/RHS of the
3917 /// comparison to make.
3918 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3919                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3920   if (!isFP) {
3921     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3922       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3923         // X > -1   -> X == 0, jump !sign.
3924         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3925         return X86::COND_NS;
3926       }
3927       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3928         // X < 0   -> X == 0, jump on sign.
3929         return X86::COND_S;
3930       }
3931       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3932         // X < 1   -> X <= 0
3933         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3934         return X86::COND_LE;
3935       }
3936     }
3937
3938     switch (SetCCOpcode) {
3939     default: llvm_unreachable("Invalid integer condition!");
3940     case ISD::SETEQ:  return X86::COND_E;
3941     case ISD::SETGT:  return X86::COND_G;
3942     case ISD::SETGE:  return X86::COND_GE;
3943     case ISD::SETLT:  return X86::COND_L;
3944     case ISD::SETLE:  return X86::COND_LE;
3945     case ISD::SETNE:  return X86::COND_NE;
3946     case ISD::SETULT: return X86::COND_B;
3947     case ISD::SETUGT: return X86::COND_A;
3948     case ISD::SETULE: return X86::COND_BE;
3949     case ISD::SETUGE: return X86::COND_AE;
3950     }
3951   }
3952
3953   // First determine if it is required or is profitable to flip the operands.
3954
3955   // If LHS is a foldable load, but RHS is not, flip the condition.
3956   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3957       !ISD::isNON_EXTLoad(RHS.getNode())) {
3958     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3959     std::swap(LHS, RHS);
3960   }
3961
3962   switch (SetCCOpcode) {
3963   default: break;
3964   case ISD::SETOLT:
3965   case ISD::SETOLE:
3966   case ISD::SETUGT:
3967   case ISD::SETUGE:
3968     std::swap(LHS, RHS);
3969     break;
3970   }
3971
3972   // On a floating point condition, the flags are set as follows:
3973   // ZF  PF  CF   op
3974   //  0 | 0 | 0 | X > Y
3975   //  0 | 0 | 1 | X < Y
3976   //  1 | 0 | 0 | X == Y
3977   //  1 | 1 | 1 | unordered
3978   switch (SetCCOpcode) {
3979   default: llvm_unreachable("Condcode should be pre-legalized away");
3980   case ISD::SETUEQ:
3981   case ISD::SETEQ:   return X86::COND_E;
3982   case ISD::SETOLT:              // flipped
3983   case ISD::SETOGT:
3984   case ISD::SETGT:   return X86::COND_A;
3985   case ISD::SETOLE:              // flipped
3986   case ISD::SETOGE:
3987   case ISD::SETGE:   return X86::COND_AE;
3988   case ISD::SETUGT:              // flipped
3989   case ISD::SETULT:
3990   case ISD::SETLT:   return X86::COND_B;
3991   case ISD::SETUGE:              // flipped
3992   case ISD::SETULE:
3993   case ISD::SETLE:   return X86::COND_BE;
3994   case ISD::SETONE:
3995   case ISD::SETNE:   return X86::COND_NE;
3996   case ISD::SETUO:   return X86::COND_P;
3997   case ISD::SETO:    return X86::COND_NP;
3998   case ISD::SETOEQ:
3999   case ISD::SETUNE:  return X86::COND_INVALID;
4000   }
4001 }
4002
4003 /// Is there a floating point cmov for the specific X86 condition code?
4004 /// Current x86 isa includes the following FP cmov instructions:
4005 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4006 static bool hasFPCMov(unsigned X86CC) {
4007   switch (X86CC) {
4008   default:
4009     return false;
4010   case X86::COND_B:
4011   case X86::COND_BE:
4012   case X86::COND_E:
4013   case X86::COND_P:
4014   case X86::COND_A:
4015   case X86::COND_AE:
4016   case X86::COND_NE:
4017   case X86::COND_NP:
4018     return true;
4019   }
4020 }
4021
4022 /// Returns true if the target can instruction select the
4023 /// specified FP immediate natively. If false, the legalizer will
4024 /// materialize the FP immediate as a load from a constant pool.
4025 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4026   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4027     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4028       return true;
4029   }
4030   return false;
4031 }
4032
4033 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4034                                               ISD::LoadExtType ExtTy,
4035                                               EVT NewVT) const {
4036   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4037   // relocation target a movq or addq instruction: don't let the load shrink.
4038   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4039   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4040     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4041       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4042   return true;
4043 }
4044
4045 /// \brief Returns true if it is beneficial to convert a load of a constant
4046 /// to just the constant itself.
4047 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4048                                                           Type *Ty) const {
4049   assert(Ty->isIntegerTy());
4050
4051   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4052   if (BitSize == 0 || BitSize > 64)
4053     return false;
4054   return true;
4055 }
4056
4057 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4058                                                 unsigned Index) const {
4059   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4060     return false;
4061
4062   return (Index == 0 || Index == ResVT.getVectorNumElements());
4063 }
4064
4065 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4066   // Speculate cttz only if we can directly use TZCNT.
4067   return Subtarget->hasBMI();
4068 }
4069
4070 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4071   // Speculate ctlz only if we can directly use LZCNT.
4072   return Subtarget->hasLZCNT();
4073 }
4074
4075 /// Return true if every element in Mask, beginning
4076 /// from position Pos and ending in Pos+Size is undef.
4077 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4078   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4079     if (0 <= Mask[i])
4080       return false;
4081   return true;
4082 }
4083
4084 /// Return true if Val is undef or if its value falls within the
4085 /// specified range (L, H].
4086 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4087   return (Val < 0) || (Val >= Low && Val < Hi);
4088 }
4089
4090 /// Val is either less than zero (undef) or equal to the specified value.
4091 static bool isUndefOrEqual(int Val, int CmpVal) {
4092   return (Val < 0 || Val == CmpVal);
4093 }
4094
4095 /// Return true if every element in Mask, beginning
4096 /// from position Pos and ending in Pos+Size, falls within the specified
4097 /// sequential range (Low, Low+Size]. or is undef.
4098 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4099                                        unsigned Pos, unsigned Size, int Low) {
4100   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4101     if (!isUndefOrEqual(Mask[i], Low))
4102       return false;
4103   return true;
4104 }
4105
4106 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4107 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4108 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4109   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4110   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4111     return false;
4112
4113   // The index should be aligned on a vecWidth-bit boundary.
4114   uint64_t Index =
4115     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4116
4117   MVT VT = N->getSimpleValueType(0);
4118   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4119   bool Result = (Index * ElSize) % vecWidth == 0;
4120
4121   return Result;
4122 }
4123
4124 /// Return true if the specified INSERT_SUBVECTOR
4125 /// operand specifies a subvector insert that is suitable for input to
4126 /// insertion of 128 or 256-bit subvectors
4127 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4128   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4129   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4130     return false;
4131   // The index should be aligned on a vecWidth-bit boundary.
4132   uint64_t Index =
4133     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4134
4135   MVT VT = N->getSimpleValueType(0);
4136   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4137   bool Result = (Index * ElSize) % vecWidth == 0;
4138
4139   return Result;
4140 }
4141
4142 bool X86::isVINSERT128Index(SDNode *N) {
4143   return isVINSERTIndex(N, 128);
4144 }
4145
4146 bool X86::isVINSERT256Index(SDNode *N) {
4147   return isVINSERTIndex(N, 256);
4148 }
4149
4150 bool X86::isVEXTRACT128Index(SDNode *N) {
4151   return isVEXTRACTIndex(N, 128);
4152 }
4153
4154 bool X86::isVEXTRACT256Index(SDNode *N) {
4155   return isVEXTRACTIndex(N, 256);
4156 }
4157
4158 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4159   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4160   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4161     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4162
4163   uint64_t Index =
4164     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4165
4166   MVT VecVT = N->getOperand(0).getSimpleValueType();
4167   MVT ElVT = VecVT.getVectorElementType();
4168
4169   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4170   return Index / NumElemsPerChunk;
4171 }
4172
4173 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4174   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4175   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4176     llvm_unreachable("Illegal insert subvector for VINSERT");
4177
4178   uint64_t Index =
4179     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4180
4181   MVT VecVT = N->getSimpleValueType(0);
4182   MVT ElVT = VecVT.getVectorElementType();
4183
4184   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4185   return Index / NumElemsPerChunk;
4186 }
4187
4188 /// Return the appropriate immediate to extract the specified
4189 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4190 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4191   return getExtractVEXTRACTImmediate(N, 128);
4192 }
4193
4194 /// Return the appropriate immediate to extract the specified
4195 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4196 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4197   return getExtractVEXTRACTImmediate(N, 256);
4198 }
4199
4200 /// Return the appropriate immediate to insert at the specified
4201 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4202 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4203   return getInsertVINSERTImmediate(N, 128);
4204 }
4205
4206 /// Return the appropriate immediate to insert at the specified
4207 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4208 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4209   return getInsertVINSERTImmediate(N, 256);
4210 }
4211
4212 /// Returns true if Elt is a constant integer zero
4213 static bool isZero(SDValue V) {
4214   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4215   return C && C->isNullValue();
4216 }
4217
4218 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4219 bool X86::isZeroNode(SDValue Elt) {
4220   if (isZero(Elt))
4221     return true;
4222   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4223     return CFP->getValueAPF().isPosZero();
4224   return false;
4225 }
4226
4227 /// Returns a vector of specified type with all zero elements.
4228 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4229                              SelectionDAG &DAG, SDLoc dl) {
4230   assert(VT.isVector() && "Expected a vector type");
4231
4232   // Always build SSE zero vectors as <4 x i32> bitcasted
4233   // to their dest type. This ensures they get CSE'd.
4234   SDValue Vec;
4235   if (VT.is128BitVector()) {  // SSE
4236     if (Subtarget->hasSSE2()) {  // SSE2
4237       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4238       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4239     } else { // SSE1
4240       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4241       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4242     }
4243   } else if (VT.is256BitVector()) { // AVX
4244     if (Subtarget->hasInt256()) { // AVX2
4245       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4246       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4247       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4248     } else {
4249       // 256-bit logic and arithmetic instructions in AVX are all
4250       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4251       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4252       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4253       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4254     }
4255   } else if (VT.is512BitVector()) { // AVX-512
4256       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4257       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4258                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4259       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4260   } else if (VT.getScalarType() == MVT::i1) {
4261
4262     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4263             && "Unexpected vector type");
4264     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4265             && "Unexpected vector type");
4266     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4267     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4268     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4269   } else
4270     llvm_unreachable("Unexpected vector type");
4271
4272   return DAG.getBitcast(VT, Vec);
4273 }
4274
4275 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4276                                 SelectionDAG &DAG, SDLoc dl,
4277                                 unsigned vectorWidth) {
4278   assert((vectorWidth == 128 || vectorWidth == 256) &&
4279          "Unsupported vector width");
4280   EVT VT = Vec.getValueType();
4281   EVT ElVT = VT.getVectorElementType();
4282   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4283   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4284                                   VT.getVectorNumElements()/Factor);
4285
4286   // Extract from UNDEF is UNDEF.
4287   if (Vec.getOpcode() == ISD::UNDEF)
4288     return DAG.getUNDEF(ResultVT);
4289
4290   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4291   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4292
4293   // This is the index of the first element of the vectorWidth-bit chunk
4294   // we want.
4295   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4296                                * ElemsPerChunk);
4297
4298   // If the input is a buildvector just emit a smaller one.
4299   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4300     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4301                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4302                                     ElemsPerChunk));
4303
4304   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4305   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4306 }
4307
4308 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4309 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4310 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4311 /// instructions or a simple subregister reference. Idx is an index in the
4312 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4313 /// lowering EXTRACT_VECTOR_ELT operations easier.
4314 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4315                                    SelectionDAG &DAG, SDLoc dl) {
4316   assert((Vec.getValueType().is256BitVector() ||
4317           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4318   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4319 }
4320
4321 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4322 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4323                                    SelectionDAG &DAG, SDLoc dl) {
4324   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4325   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4326 }
4327
4328 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4329                                unsigned IdxVal, SelectionDAG &DAG,
4330                                SDLoc dl, unsigned vectorWidth) {
4331   assert((vectorWidth == 128 || vectorWidth == 256) &&
4332          "Unsupported vector width");
4333   // Inserting UNDEF is Result
4334   if (Vec.getOpcode() == ISD::UNDEF)
4335     return Result;
4336   EVT VT = Vec.getValueType();
4337   EVT ElVT = VT.getVectorElementType();
4338   EVT ResultVT = Result.getValueType();
4339
4340   // Insert the relevant vectorWidth bits.
4341   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4342
4343   // This is the index of the first element of the vectorWidth-bit chunk
4344   // we want.
4345   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4346                                * ElemsPerChunk);
4347
4348   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4349   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4350 }
4351
4352 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4353 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4354 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4355 /// simple superregister reference.  Idx is an index in the 128 bits
4356 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4357 /// lowering INSERT_VECTOR_ELT operations easier.
4358 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4359                                   SelectionDAG &DAG, SDLoc dl) {
4360   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4361
4362   // For insertion into the zero index (low half) of a 256-bit vector, it is
4363   // more efficient to generate a blend with immediate instead of an insert*128.
4364   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4365   // extend the subvector to the size of the result vector. Make sure that
4366   // we are not recursing on that node by checking for undef here.
4367   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4368       Result.getOpcode() != ISD::UNDEF) {
4369     EVT ResultVT = Result.getValueType();
4370     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4371     SDValue Undef = DAG.getUNDEF(ResultVT);
4372     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4373                                  Vec, ZeroIndex);
4374
4375     // The blend instruction, and therefore its mask, depend on the data type.
4376     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4377     if (ScalarType.isFloatingPoint()) {
4378       // Choose either vblendps (float) or vblendpd (double).
4379       unsigned ScalarSize = ScalarType.getSizeInBits();
4380       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4381       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4382       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4383       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4384     }
4385
4386     const X86Subtarget &Subtarget =
4387     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4388
4389     // AVX2 is needed for 256-bit integer blend support.
4390     // Integers must be cast to 32-bit because there is only vpblendd;
4391     // vpblendw can't be used for this because it has a handicapped mask.
4392
4393     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4394     // is still more efficient than using the wrong domain vinsertf128 that
4395     // will be created by InsertSubVector().
4396     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4397
4398     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4399     Vec256 = DAG.getBitcast(CastVT, Vec256);
4400     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4401     return DAG.getBitcast(ResultVT, Vec256);
4402   }
4403
4404   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4405 }
4406
4407 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4408                                   SelectionDAG &DAG, SDLoc dl) {
4409   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4410   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4411 }
4412
4413 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4414 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4415 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4416 /// large BUILD_VECTORS.
4417 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4418                                    unsigned NumElems, SelectionDAG &DAG,
4419                                    SDLoc dl) {
4420   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4421   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4422 }
4423
4424 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4425                                    unsigned NumElems, SelectionDAG &DAG,
4426                                    SDLoc dl) {
4427   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4428   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4429 }
4430
4431 /// Returns a vector of specified type with all bits set.
4432 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4433 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4434 /// Then bitcast to their original type, ensuring they get CSE'd.
4435 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4436                              SelectionDAG &DAG, SDLoc dl) {
4437   assert(VT.isVector() && "Expected a vector type");
4438
4439   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4440   SDValue Vec;
4441   if (VT.is512BitVector()) {
4442     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4443                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4444     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4445   } else if (VT.is256BitVector()) {
4446     if (Subtarget->hasInt256()) { // AVX2
4447       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4448       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4449     } else { // AVX
4450       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4451       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4452     }
4453   } else if (VT.is128BitVector()) {
4454     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4455   } else
4456     llvm_unreachable("Unexpected vector type");
4457
4458   return DAG.getBitcast(VT, Vec);
4459 }
4460
4461 /// Returns a vector_shuffle node for an unpackl operation.
4462 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4463                           SDValue V2) {
4464   unsigned NumElems = VT.getVectorNumElements();
4465   SmallVector<int, 8> Mask;
4466   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4467     Mask.push_back(i);
4468     Mask.push_back(i + NumElems);
4469   }
4470   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4471 }
4472
4473 /// Returns a vector_shuffle node for an unpackh operation.
4474 static SDValue getUnpackh(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, Half = NumElems/2; i != Half; ++i) {
4479     Mask.push_back(i + Half);
4480     Mask.push_back(i + NumElems + Half);
4481   }
4482   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4483 }
4484
4485 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4486 /// This produces a shuffle where the low element of V2 is swizzled into the
4487 /// zero/undef vector, landing at element Idx.
4488 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4489 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4490                                            bool IsZero,
4491                                            const X86Subtarget *Subtarget,
4492                                            SelectionDAG &DAG) {
4493   MVT VT = V2.getSimpleValueType();
4494   SDValue V1 = IsZero
4495     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4496   unsigned NumElems = VT.getVectorNumElements();
4497   SmallVector<int, 16> MaskVec;
4498   for (unsigned i = 0; i != NumElems; ++i)
4499     // If this is the insertion idx, put the low elt of V2 here.
4500     MaskVec.push_back(i == Idx ? NumElems : i);
4501   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4502 }
4503
4504 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4505 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4506 /// uses one source. Note that this will set IsUnary for shuffles which use a
4507 /// single input multiple times, and in those cases it will
4508 /// adjust the mask to only have indices within that single input.
4509 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4510 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4511                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4512   unsigned NumElems = VT.getVectorNumElements();
4513   SDValue ImmN;
4514
4515   IsUnary = false;
4516   bool IsFakeUnary = false;
4517   switch(N->getOpcode()) {
4518   case X86ISD::BLENDI:
4519     ImmN = N->getOperand(N->getNumOperands()-1);
4520     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4521     break;
4522   case X86ISD::SHUFP:
4523     ImmN = N->getOperand(N->getNumOperands()-1);
4524     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4525     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4526     break;
4527   case X86ISD::UNPCKH:
4528     DecodeUNPCKHMask(VT, Mask);
4529     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4530     break;
4531   case X86ISD::UNPCKL:
4532     DecodeUNPCKLMask(VT, Mask);
4533     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4534     break;
4535   case X86ISD::MOVHLPS:
4536     DecodeMOVHLPSMask(NumElems, Mask);
4537     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4538     break;
4539   case X86ISD::MOVLHPS:
4540     DecodeMOVLHPSMask(NumElems, Mask);
4541     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4542     break;
4543   case X86ISD::PALIGNR:
4544     ImmN = N->getOperand(N->getNumOperands()-1);
4545     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4546     break;
4547   case X86ISD::PSHUFD:
4548   case X86ISD::VPERMILPI:
4549     ImmN = N->getOperand(N->getNumOperands()-1);
4550     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4551     IsUnary = true;
4552     break;
4553   case X86ISD::PSHUFHW:
4554     ImmN = N->getOperand(N->getNumOperands()-1);
4555     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4556     IsUnary = true;
4557     break;
4558   case X86ISD::PSHUFLW:
4559     ImmN = N->getOperand(N->getNumOperands()-1);
4560     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4561     IsUnary = true;
4562     break;
4563   case X86ISD::PSHUFB: {
4564     IsUnary = true;
4565     SDValue MaskNode = N->getOperand(1);
4566     while (MaskNode->getOpcode() == ISD::BITCAST)
4567       MaskNode = MaskNode->getOperand(0);
4568
4569     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4570       // If we have a build-vector, then things are easy.
4571       EVT VT = MaskNode.getValueType();
4572       assert(VT.isVector() &&
4573              "Can't produce a non-vector with a build_vector!");
4574       if (!VT.isInteger())
4575         return false;
4576
4577       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4578
4579       SmallVector<uint64_t, 32> RawMask;
4580       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4581         SDValue Op = MaskNode->getOperand(i);
4582         if (Op->getOpcode() == ISD::UNDEF) {
4583           RawMask.push_back((uint64_t)SM_SentinelUndef);
4584           continue;
4585         }
4586         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4587         if (!CN)
4588           return false;
4589         APInt MaskElement = CN->getAPIntValue();
4590
4591         // We now have to decode the element which could be any integer size and
4592         // extract each byte of it.
4593         for (int j = 0; j < NumBytesPerElement; ++j) {
4594           // Note that this is x86 and so always little endian: the low byte is
4595           // the first byte of the mask.
4596           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4597           MaskElement = MaskElement.lshr(8);
4598         }
4599       }
4600       DecodePSHUFBMask(RawMask, Mask);
4601       break;
4602     }
4603
4604     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4605     if (!MaskLoad)
4606       return false;
4607
4608     SDValue Ptr = MaskLoad->getBasePtr();
4609     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4610         Ptr->getOpcode() == X86ISD::WrapperRIP)
4611       Ptr = Ptr->getOperand(0);
4612
4613     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4614     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4615       return false;
4616
4617     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4618       DecodePSHUFBMask(C, Mask);
4619       if (Mask.empty())
4620         return false;
4621       break;
4622     }
4623
4624     return false;
4625   }
4626   case X86ISD::VPERMI:
4627     ImmN = N->getOperand(N->getNumOperands()-1);
4628     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4629     IsUnary = true;
4630     break;
4631   case X86ISD::MOVSS:
4632   case X86ISD::MOVSD:
4633     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4634     break;
4635   case X86ISD::VPERM2X128:
4636     ImmN = N->getOperand(N->getNumOperands()-1);
4637     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4638     if (Mask.empty()) return false;
4639     // Mask only contains negative index if an element is zero.
4640     if (std::any_of(Mask.begin(), Mask.end(),
4641                     [](int M){ return M == SM_SentinelZero; }))
4642       return false;
4643     break;
4644   case X86ISD::MOVSLDUP:
4645     DecodeMOVSLDUPMask(VT, Mask);
4646     IsUnary = true;
4647     break;
4648   case X86ISD::MOVSHDUP:
4649     DecodeMOVSHDUPMask(VT, Mask);
4650     IsUnary = true;
4651     break;
4652   case X86ISD::MOVDDUP:
4653     DecodeMOVDDUPMask(VT, Mask);
4654     IsUnary = true;
4655     break;
4656   case X86ISD::MOVLHPD:
4657   case X86ISD::MOVLPD:
4658   case X86ISD::MOVLPS:
4659     // Not yet implemented
4660     return false;
4661   case X86ISD::VPERMV: {
4662     IsUnary = true;
4663     SDValue MaskNode = N->getOperand(0);
4664     while (MaskNode->getOpcode() == ISD::BITCAST)
4665       MaskNode = MaskNode->getOperand(0);
4666
4667     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4668     SmallVector<uint64_t, 32> RawMask;
4669     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4670       // If we have a build-vector, then things are easy.
4671       assert(MaskNode.getValueType().isInteger() &&
4672              MaskNode.getValueType().getVectorNumElements() ==
4673              VT.getVectorNumElements());
4674
4675       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4676         SDValue Op = MaskNode->getOperand(i);
4677         if (Op->getOpcode() == ISD::UNDEF)
4678           RawMask.push_back((uint64_t)SM_SentinelUndef);
4679         else if (isa<ConstantSDNode>(Op)) {
4680           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4681           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4682         } else
4683           return false;
4684       }
4685       DecodeVPERMVMask(RawMask, Mask);
4686       break;
4687     }
4688     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4689       unsigned NumEltsInMask = MaskNode->getNumOperands();
4690       MaskNode = MaskNode->getOperand(0);
4691       auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4692       if (CN) {
4693         APInt MaskEltValue = CN->getAPIntValue();
4694         for (unsigned i = 0; i < NumEltsInMask; ++i)
4695           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4696         DecodeVPERMVMask(RawMask, Mask);
4697         break;
4698       }
4699       // It may be a scalar load
4700     }
4701
4702     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4703     if (!MaskLoad)
4704       return false;
4705
4706     SDValue Ptr = MaskLoad->getBasePtr();
4707     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4708         Ptr->getOpcode() == X86ISD::WrapperRIP)
4709       Ptr = Ptr->getOperand(0);
4710
4711     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4712     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4713       return false;
4714
4715     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4716     if (C) {
4717       DecodeVPERMVMask(C, VT, Mask);
4718       if (Mask.empty())
4719         return false;
4720       break;
4721     }
4722     return false;
4723   }
4724   case X86ISD::VPERMV3: {
4725     IsUnary = false;
4726     SDValue MaskNode = N->getOperand(1);
4727     while (MaskNode->getOpcode() == ISD::BITCAST)
4728       MaskNode = MaskNode->getOperand(1);
4729
4730     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4731       // If we have a build-vector, then things are easy.
4732       assert(MaskNode.getValueType().isInteger() &&
4733              MaskNode.getValueType().getVectorNumElements() ==
4734              VT.getVectorNumElements());
4735
4736       SmallVector<uint64_t, 32> RawMask;
4737       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4738
4739       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4740         SDValue Op = MaskNode->getOperand(i);
4741         if (Op->getOpcode() == ISD::UNDEF)
4742           RawMask.push_back((uint64_t)SM_SentinelUndef);
4743         else {
4744           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4745           if (!CN)
4746             return false;
4747           APInt MaskElement = CN->getAPIntValue();
4748           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4749         }
4750       }
4751       DecodeVPERMV3Mask(RawMask, Mask);
4752       break;
4753     }
4754
4755     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4756     if (!MaskLoad)
4757       return false;
4758
4759     SDValue Ptr = MaskLoad->getBasePtr();
4760     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4761         Ptr->getOpcode() == X86ISD::WrapperRIP)
4762       Ptr = Ptr->getOperand(0);
4763
4764     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4765     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4766       return false;
4767
4768     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4769     if (C) {
4770       DecodeVPERMV3Mask(C, VT, Mask);
4771       if (Mask.empty())
4772         return false;
4773       break;
4774     }
4775     return false;
4776   }
4777   default: llvm_unreachable("unknown target shuffle node");
4778   }
4779
4780   // If we have a fake unary shuffle, the shuffle mask is spread across two
4781   // inputs that are actually the same node. Re-map the mask to always point
4782   // into the first input.
4783   if (IsFakeUnary)
4784     for (int &M : Mask)
4785       if (M >= (int)Mask.size())
4786         M -= Mask.size();
4787
4788   return true;
4789 }
4790
4791 /// Returns the scalar element that will make up the ith
4792 /// element of the result of the vector shuffle.
4793 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4794                                    unsigned Depth) {
4795   if (Depth == 6)
4796     return SDValue();  // Limit search depth.
4797
4798   SDValue V = SDValue(N, 0);
4799   EVT VT = V.getValueType();
4800   unsigned Opcode = V.getOpcode();
4801
4802   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4803   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4804     int Elt = SV->getMaskElt(Index);
4805
4806     if (Elt < 0)
4807       return DAG.getUNDEF(VT.getVectorElementType());
4808
4809     unsigned NumElems = VT.getVectorNumElements();
4810     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4811                                          : SV->getOperand(1);
4812     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4813   }
4814
4815   // Recurse into target specific vector shuffles to find scalars.
4816   if (isTargetShuffle(Opcode)) {
4817     MVT ShufVT = V.getSimpleValueType();
4818     unsigned NumElems = ShufVT.getVectorNumElements();
4819     SmallVector<int, 16> ShuffleMask;
4820     bool IsUnary;
4821
4822     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4823       return SDValue();
4824
4825     int Elt = ShuffleMask[Index];
4826     if (Elt < 0)
4827       return DAG.getUNDEF(ShufVT.getVectorElementType());
4828
4829     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4830                                          : N->getOperand(1);
4831     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4832                                Depth+1);
4833   }
4834
4835   // Actual nodes that may contain scalar elements
4836   if (Opcode == ISD::BITCAST) {
4837     V = V.getOperand(0);
4838     EVT SrcVT = V.getValueType();
4839     unsigned NumElems = VT.getVectorNumElements();
4840
4841     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4842       return SDValue();
4843   }
4844
4845   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4846     return (Index == 0) ? V.getOperand(0)
4847                         : DAG.getUNDEF(VT.getVectorElementType());
4848
4849   if (V.getOpcode() == ISD::BUILD_VECTOR)
4850     return V.getOperand(Index);
4851
4852   return SDValue();
4853 }
4854
4855 /// Custom lower build_vector of v16i8.
4856 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4857                                        unsigned NumNonZero, unsigned NumZero,
4858                                        SelectionDAG &DAG,
4859                                        const X86Subtarget* Subtarget,
4860                                        const TargetLowering &TLI) {
4861   if (NumNonZero > 8)
4862     return SDValue();
4863
4864   SDLoc dl(Op);
4865   SDValue V;
4866   bool First = true;
4867
4868   // SSE4.1 - use PINSRB to insert each byte directly.
4869   if (Subtarget->hasSSE41()) {
4870     for (unsigned i = 0; i < 16; ++i) {
4871       bool isNonZero = (NonZeros & (1 << i)) != 0;
4872       if (isNonZero) {
4873         if (First) {
4874           if (NumZero)
4875             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4876           else
4877             V = DAG.getUNDEF(MVT::v16i8);
4878           First = false;
4879         }
4880         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4881                         MVT::v16i8, V, Op.getOperand(i),
4882                         DAG.getIntPtrConstant(i, dl));
4883       }
4884     }
4885
4886     return V;
4887   }
4888
4889   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4890   for (unsigned i = 0; i < 16; ++i) {
4891     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4892     if (ThisIsNonZero && First) {
4893       if (NumZero)
4894         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4895       else
4896         V = DAG.getUNDEF(MVT::v8i16);
4897       First = false;
4898     }
4899
4900     if ((i & 1) != 0) {
4901       SDValue ThisElt, LastElt;
4902       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4903       if (LastIsNonZero) {
4904         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4905                               MVT::i16, Op.getOperand(i-1));
4906       }
4907       if (ThisIsNonZero) {
4908         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4909         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4910                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4911         if (LastIsNonZero)
4912           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4913       } else
4914         ThisElt = LastElt;
4915
4916       if (ThisElt.getNode())
4917         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4918                         DAG.getIntPtrConstant(i/2, dl));
4919     }
4920   }
4921
4922   return DAG.getBitcast(MVT::v16i8, V);
4923 }
4924
4925 /// Custom lower build_vector of v8i16.
4926 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4927                                      unsigned NumNonZero, unsigned NumZero,
4928                                      SelectionDAG &DAG,
4929                                      const X86Subtarget* Subtarget,
4930                                      const TargetLowering &TLI) {
4931   if (NumNonZero > 4)
4932     return SDValue();
4933
4934   SDLoc dl(Op);
4935   SDValue V;
4936   bool First = true;
4937   for (unsigned i = 0; i < 8; ++i) {
4938     bool isNonZero = (NonZeros & (1 << i)) != 0;
4939     if (isNonZero) {
4940       if (First) {
4941         if (NumZero)
4942           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4943         else
4944           V = DAG.getUNDEF(MVT::v8i16);
4945         First = false;
4946       }
4947       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4948                       MVT::v8i16, V, Op.getOperand(i),
4949                       DAG.getIntPtrConstant(i, dl));
4950     }
4951   }
4952
4953   return V;
4954 }
4955
4956 /// Custom lower build_vector of v4i32 or v4f32.
4957 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4958                                      const X86Subtarget *Subtarget,
4959                                      const TargetLowering &TLI) {
4960   // Find all zeroable elements.
4961   std::bitset<4> Zeroable;
4962   for (int i=0; i < 4; ++i) {
4963     SDValue Elt = Op->getOperand(i);
4964     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4965   }
4966   assert(Zeroable.size() - Zeroable.count() > 1 &&
4967          "We expect at least two non-zero elements!");
4968
4969   // We only know how to deal with build_vector nodes where elements are either
4970   // zeroable or extract_vector_elt with constant index.
4971   SDValue FirstNonZero;
4972   unsigned FirstNonZeroIdx;
4973   for (unsigned i=0; i < 4; ++i) {
4974     if (Zeroable[i])
4975       continue;
4976     SDValue Elt = Op->getOperand(i);
4977     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4978         !isa<ConstantSDNode>(Elt.getOperand(1)))
4979       return SDValue();
4980     // Make sure that this node is extracting from a 128-bit vector.
4981     MVT VT = Elt.getOperand(0).getSimpleValueType();
4982     if (!VT.is128BitVector())
4983       return SDValue();
4984     if (!FirstNonZero.getNode()) {
4985       FirstNonZero = Elt;
4986       FirstNonZeroIdx = i;
4987     }
4988   }
4989
4990   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4991   SDValue V1 = FirstNonZero.getOperand(0);
4992   MVT VT = V1.getSimpleValueType();
4993
4994   // See if this build_vector can be lowered as a blend with zero.
4995   SDValue Elt;
4996   unsigned EltMaskIdx, EltIdx;
4997   int Mask[4];
4998   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4999     if (Zeroable[EltIdx]) {
5000       // The zero vector will be on the right hand side.
5001       Mask[EltIdx] = EltIdx+4;
5002       continue;
5003     }
5004
5005     Elt = Op->getOperand(EltIdx);
5006     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5007     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5008     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5009       break;
5010     Mask[EltIdx] = EltIdx;
5011   }
5012
5013   if (EltIdx == 4) {
5014     // Let the shuffle legalizer deal with blend operations.
5015     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5016     if (V1.getSimpleValueType() != VT)
5017       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5018     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5019   }
5020
5021   // See if we can lower this build_vector to a INSERTPS.
5022   if (!Subtarget->hasSSE41())
5023     return SDValue();
5024
5025   SDValue V2 = Elt.getOperand(0);
5026   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5027     V1 = SDValue();
5028
5029   bool CanFold = true;
5030   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5031     if (Zeroable[i])
5032       continue;
5033
5034     SDValue Current = Op->getOperand(i);
5035     SDValue SrcVector = Current->getOperand(0);
5036     if (!V1.getNode())
5037       V1 = SrcVector;
5038     CanFold = SrcVector == V1 &&
5039       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5040   }
5041
5042   if (!CanFold)
5043     return SDValue();
5044
5045   assert(V1.getNode() && "Expected at least two non-zero elements!");
5046   if (V1.getSimpleValueType() != MVT::v4f32)
5047     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5048   if (V2.getSimpleValueType() != MVT::v4f32)
5049     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5050
5051   // Ok, we can emit an INSERTPS instruction.
5052   unsigned ZMask = Zeroable.to_ulong();
5053
5054   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5055   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5056   SDLoc DL(Op);
5057   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5058                                DAG.getIntPtrConstant(InsertPSMask, DL));
5059   return DAG.getBitcast(VT, Result);
5060 }
5061
5062 /// Return a vector logical shift node.
5063 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5064                          unsigned NumBits, SelectionDAG &DAG,
5065                          const TargetLowering &TLI, SDLoc dl) {
5066   assert(VT.is128BitVector() && "Unknown type for VShift");
5067   MVT ShVT = MVT::v2i64;
5068   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5069   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5070   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5071   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5072   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5073   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5074 }
5075
5076 static SDValue
5077 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5078
5079   // Check if the scalar load can be widened into a vector load. And if
5080   // the address is "base + cst" see if the cst can be "absorbed" into
5081   // the shuffle mask.
5082   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5083     SDValue Ptr = LD->getBasePtr();
5084     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5085       return SDValue();
5086     EVT PVT = LD->getValueType(0);
5087     if (PVT != MVT::i32 && PVT != MVT::f32)
5088       return SDValue();
5089
5090     int FI = -1;
5091     int64_t Offset = 0;
5092     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5093       FI = FINode->getIndex();
5094       Offset = 0;
5095     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5096                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5097       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5098       Offset = Ptr.getConstantOperandVal(1);
5099       Ptr = Ptr.getOperand(0);
5100     } else {
5101       return SDValue();
5102     }
5103
5104     // FIXME: 256-bit vector instructions don't require a strict alignment,
5105     // improve this code to support it better.
5106     unsigned RequiredAlign = VT.getSizeInBits()/8;
5107     SDValue Chain = LD->getChain();
5108     // Make sure the stack object alignment is at least 16 or 32.
5109     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5110     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5111       if (MFI->isFixedObjectIndex(FI)) {
5112         // Can't change the alignment. FIXME: It's possible to compute
5113         // the exact stack offset and reference FI + adjust offset instead.
5114         // If someone *really* cares about this. That's the way to implement it.
5115         return SDValue();
5116       } else {
5117         MFI->setObjectAlignment(FI, RequiredAlign);
5118       }
5119     }
5120
5121     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5122     // Ptr + (Offset & ~15).
5123     if (Offset < 0)
5124       return SDValue();
5125     if ((Offset % RequiredAlign) & 3)
5126       return SDValue();
5127     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5128     if (StartOffset) {
5129       SDLoc DL(Ptr);
5130       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5131                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5132     }
5133
5134     int EltNo = (Offset - StartOffset) >> 2;
5135     unsigned NumElems = VT.getVectorNumElements();
5136
5137     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5138     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5139                              LD->getPointerInfo().getWithOffset(StartOffset),
5140                              false, false, false, 0);
5141
5142     SmallVector<int, 8> Mask(NumElems, EltNo);
5143
5144     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5145   }
5146
5147   return SDValue();
5148 }
5149
5150 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5151 /// elements can be replaced by a single large load which has the same value as
5152 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5153 ///
5154 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5155 ///
5156 /// FIXME: we'd also like to handle the case where the last elements are zero
5157 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5158 /// There's even a handy isZeroNode for that purpose.
5159 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5160                                         SDLoc &DL, SelectionDAG &DAG,
5161                                         bool isAfterLegalize) {
5162   unsigned NumElems = Elts.size();
5163
5164   LoadSDNode *LDBase = nullptr;
5165   unsigned LastLoadedElt = -1U;
5166
5167   // For each element in the initializer, see if we've found a load or an undef.
5168   // If we don't find an initial load element, or later load elements are
5169   // non-consecutive, bail out.
5170   for (unsigned i = 0; i < NumElems; ++i) {
5171     SDValue Elt = Elts[i];
5172     // Look through a bitcast.
5173     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5174       Elt = Elt.getOperand(0);
5175     if (!Elt.getNode() ||
5176         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5177       return SDValue();
5178     if (!LDBase) {
5179       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5180         return SDValue();
5181       LDBase = cast<LoadSDNode>(Elt.getNode());
5182       LastLoadedElt = i;
5183       continue;
5184     }
5185     if (Elt.getOpcode() == ISD::UNDEF)
5186       continue;
5187
5188     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5189     EVT LdVT = Elt.getValueType();
5190     // Each loaded element must be the correct fractional portion of the
5191     // requested vector load.
5192     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5193       return SDValue();
5194     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5195       return SDValue();
5196     LastLoadedElt = i;
5197   }
5198
5199   // If we have found an entire vector of loads and undefs, then return a large
5200   // load of the entire vector width starting at the base pointer.  If we found
5201   // consecutive loads for the low half, generate a vzext_load node.
5202   if (LastLoadedElt == NumElems - 1) {
5203     assert(LDBase && "Did not find base load for merging consecutive loads");
5204     EVT EltVT = LDBase->getValueType(0);
5205     // Ensure that the input vector size for the merged loads matches the
5206     // cumulative size of the input elements.
5207     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5208       return SDValue();
5209
5210     if (isAfterLegalize &&
5211         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5212       return SDValue();
5213
5214     SDValue NewLd = SDValue();
5215
5216     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5217                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5218                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5219                         LDBase->getAlignment());
5220
5221     if (LDBase->hasAnyUseOfValue(1)) {
5222       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5223                                      SDValue(LDBase, 1),
5224                                      SDValue(NewLd.getNode(), 1));
5225       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5226       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5227                              SDValue(NewLd.getNode(), 1));
5228     }
5229
5230     return NewLd;
5231   }
5232
5233   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5234   //of a v4i32 / v4f32. It's probably worth generalizing.
5235   EVT EltVT = VT.getVectorElementType();
5236   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5237       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5238     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5239     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5240     SDValue ResNode =
5241         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5242                                 LDBase->getPointerInfo(),
5243                                 LDBase->getAlignment(),
5244                                 false/*isVolatile*/, true/*ReadMem*/,
5245                                 false/*WriteMem*/);
5246
5247     // Make sure the newly-created LOAD is in the same position as LDBase in
5248     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5249     // update uses of LDBase's output chain to use the TokenFactor.
5250     if (LDBase->hasAnyUseOfValue(1)) {
5251       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5252                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5253       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5254       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5255                              SDValue(ResNode.getNode(), 1));
5256     }
5257
5258     return DAG.getBitcast(VT, ResNode);
5259   }
5260   return SDValue();
5261 }
5262
5263 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5264 /// to generate a splat value for the following cases:
5265 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5266 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5267 /// a scalar load, or a constant.
5268 /// The VBROADCAST node is returned when a pattern is found,
5269 /// or SDValue() otherwise.
5270 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5271                                     SelectionDAG &DAG) {
5272   // VBROADCAST requires AVX.
5273   // TODO: Splats could be generated for non-AVX CPUs using SSE
5274   // instructions, but there's less potential gain for only 128-bit vectors.
5275   if (!Subtarget->hasAVX())
5276     return SDValue();
5277
5278   MVT VT = Op.getSimpleValueType();
5279   SDLoc dl(Op);
5280
5281   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5282          "Unsupported vector type for broadcast.");
5283
5284   SDValue Ld;
5285   bool ConstSplatVal;
5286
5287   switch (Op.getOpcode()) {
5288     default:
5289       // Unknown pattern found.
5290       return SDValue();
5291
5292     case ISD::BUILD_VECTOR: {
5293       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5294       BitVector UndefElements;
5295       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5296
5297       // We need a splat of a single value to use broadcast, and it doesn't
5298       // make any sense if the value is only in one element of the vector.
5299       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5300         return SDValue();
5301
5302       Ld = Splat;
5303       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5304                        Ld.getOpcode() == ISD::ConstantFP);
5305
5306       // Make sure that all of the users of a non-constant load are from the
5307       // BUILD_VECTOR node.
5308       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5309         return SDValue();
5310       break;
5311     }
5312
5313     case ISD::VECTOR_SHUFFLE: {
5314       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5315
5316       // Shuffles must have a splat mask where the first element is
5317       // broadcasted.
5318       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5319         return SDValue();
5320
5321       SDValue Sc = Op.getOperand(0);
5322       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5323           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5324
5325         if (!Subtarget->hasInt256())
5326           return SDValue();
5327
5328         // Use the register form of the broadcast instruction available on AVX2.
5329         if (VT.getSizeInBits() >= 256)
5330           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5331         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5332       }
5333
5334       Ld = Sc.getOperand(0);
5335       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5336                        Ld.getOpcode() == ISD::ConstantFP);
5337
5338       // The scalar_to_vector node and the suspected
5339       // load node must have exactly one user.
5340       // Constants may have multiple users.
5341
5342       // AVX-512 has register version of the broadcast
5343       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5344         Ld.getValueType().getSizeInBits() >= 32;
5345       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5346           !hasRegVer))
5347         return SDValue();
5348       break;
5349     }
5350   }
5351
5352   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5353   bool IsGE256 = (VT.getSizeInBits() >= 256);
5354
5355   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5356   // instruction to save 8 or more bytes of constant pool data.
5357   // TODO: If multiple splats are generated to load the same constant,
5358   // it may be detrimental to overall size. There needs to be a way to detect
5359   // that condition to know if this is truly a size win.
5360   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5361
5362   // Handle broadcasting a single constant scalar from the constant pool
5363   // into a vector.
5364   // On Sandybridge (no AVX2), it is still better to load a constant vector
5365   // from the constant pool and not to broadcast it from a scalar.
5366   // But override that restriction when optimizing for size.
5367   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5368   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5369     EVT CVT = Ld.getValueType();
5370     assert(!CVT.isVector() && "Must not broadcast a vector type");
5371
5372     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5373     // For size optimization, also splat v2f64 and v2i64, and for size opt
5374     // with AVX2, also splat i8 and i16.
5375     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5376     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5377         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5378       const Constant *C = nullptr;
5379       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5380         C = CI->getConstantIntValue();
5381       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5382         C = CF->getConstantFPValue();
5383
5384       assert(C && "Invalid constant type");
5385
5386       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5387       SDValue CP =
5388           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5389       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5390       Ld = DAG.getLoad(
5391           CVT, dl, DAG.getEntryNode(), CP,
5392           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5393           false, false, Alignment);
5394
5395       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5396     }
5397   }
5398
5399   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5400
5401   // Handle AVX2 in-register broadcasts.
5402   if (!IsLoad && Subtarget->hasInt256() &&
5403       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5404     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5405
5406   // The scalar source must be a normal load.
5407   if (!IsLoad)
5408     return SDValue();
5409
5410   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5411       (Subtarget->hasVLX() && ScalarSize == 64))
5412     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5413
5414   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5415   // double since there is no vbroadcastsd xmm
5416   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5417     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5418       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5419   }
5420
5421   // Unsupported broadcast.
5422   return SDValue();
5423 }
5424
5425 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5426 /// underlying vector and index.
5427 ///
5428 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5429 /// index.
5430 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5431                                          SDValue ExtIdx) {
5432   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5433   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5434     return Idx;
5435
5436   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5437   // lowered this:
5438   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5439   // to:
5440   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5441   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5442   //                           undef)
5443   //                       Constant<0>)
5444   // In this case the vector is the extract_subvector expression and the index
5445   // is 2, as specified by the shuffle.
5446   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5447   SDValue ShuffleVec = SVOp->getOperand(0);
5448   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5449   assert(ShuffleVecVT.getVectorElementType() ==
5450          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5451
5452   int ShuffleIdx = SVOp->getMaskElt(Idx);
5453   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5454     ExtractedFromVec = ShuffleVec;
5455     return ShuffleIdx;
5456   }
5457   return Idx;
5458 }
5459
5460 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5461   MVT VT = Op.getSimpleValueType();
5462
5463   // Skip if insert_vec_elt is not supported.
5464   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5465   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5466     return SDValue();
5467
5468   SDLoc DL(Op);
5469   unsigned NumElems = Op.getNumOperands();
5470
5471   SDValue VecIn1;
5472   SDValue VecIn2;
5473   SmallVector<unsigned, 4> InsertIndices;
5474   SmallVector<int, 8> Mask(NumElems, -1);
5475
5476   for (unsigned i = 0; i != NumElems; ++i) {
5477     unsigned Opc = Op.getOperand(i).getOpcode();
5478
5479     if (Opc == ISD::UNDEF)
5480       continue;
5481
5482     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5483       // Quit if more than 1 elements need inserting.
5484       if (InsertIndices.size() > 1)
5485         return SDValue();
5486
5487       InsertIndices.push_back(i);
5488       continue;
5489     }
5490
5491     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5492     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5493     // Quit if non-constant index.
5494     if (!isa<ConstantSDNode>(ExtIdx))
5495       return SDValue();
5496     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5497
5498     // Quit if extracted from vector of different type.
5499     if (ExtractedFromVec.getValueType() != VT)
5500       return SDValue();
5501
5502     if (!VecIn1.getNode())
5503       VecIn1 = ExtractedFromVec;
5504     else if (VecIn1 != ExtractedFromVec) {
5505       if (!VecIn2.getNode())
5506         VecIn2 = ExtractedFromVec;
5507       else if (VecIn2 != ExtractedFromVec)
5508         // Quit if more than 2 vectors to shuffle
5509         return SDValue();
5510     }
5511
5512     if (ExtractedFromVec == VecIn1)
5513       Mask[i] = Idx;
5514     else if (ExtractedFromVec == VecIn2)
5515       Mask[i] = Idx + NumElems;
5516   }
5517
5518   if (!VecIn1.getNode())
5519     return SDValue();
5520
5521   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5522   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5523   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5524     unsigned Idx = InsertIndices[i];
5525     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5526                      DAG.getIntPtrConstant(Idx, DL));
5527   }
5528
5529   return NV;
5530 }
5531
5532 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5533   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5534          Op.getScalarValueSizeInBits() == 1 &&
5535          "Can not convert non-constant vector");
5536   uint64_t Immediate = 0;
5537   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5538     SDValue In = Op.getOperand(idx);
5539     if (In.getOpcode() != ISD::UNDEF)
5540       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5541   }
5542   SDLoc dl(Op);
5543   MVT VT =
5544    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5545   return DAG.getConstant(Immediate, dl, VT);
5546 }
5547 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5548 SDValue
5549 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5550
5551   MVT VT = Op.getSimpleValueType();
5552   assert((VT.getVectorElementType() == MVT::i1) &&
5553          "Unexpected type in LowerBUILD_VECTORvXi1!");
5554
5555   SDLoc dl(Op);
5556   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5557     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5558     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5559     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5560   }
5561
5562   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5563     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5564     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5565     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5566   }
5567
5568   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5569     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5570     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5571       return DAG.getBitcast(VT, Imm);
5572     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5573     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5574                         DAG.getIntPtrConstant(0, dl));
5575   }
5576
5577   // Vector has one or more non-const elements
5578   uint64_t Immediate = 0;
5579   SmallVector<unsigned, 16> NonConstIdx;
5580   bool IsSplat = true;
5581   bool HasConstElts = false;
5582   int SplatIdx = -1;
5583   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5584     SDValue In = Op.getOperand(idx);
5585     if (In.getOpcode() == ISD::UNDEF)
5586       continue;
5587     if (!isa<ConstantSDNode>(In))
5588       NonConstIdx.push_back(idx);
5589     else {
5590       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5591       HasConstElts = true;
5592     }
5593     if (SplatIdx == -1)
5594       SplatIdx = idx;
5595     else if (In != Op.getOperand(SplatIdx))
5596       IsSplat = false;
5597   }
5598
5599   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5600   if (IsSplat)
5601     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5602                        DAG.getConstant(1, dl, VT),
5603                        DAG.getConstant(0, dl, VT));
5604
5605   // insert elements one by one
5606   SDValue DstVec;
5607   SDValue Imm;
5608   if (Immediate) {
5609     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5610     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5611   }
5612   else if (HasConstElts)
5613     Imm = DAG.getConstant(0, dl, VT);
5614   else
5615     Imm = DAG.getUNDEF(VT);
5616   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5617     DstVec = DAG.getBitcast(VT, Imm);
5618   else {
5619     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5620     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5621                          DAG.getIntPtrConstant(0, dl));
5622   }
5623
5624   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5625     unsigned InsertIdx = NonConstIdx[i];
5626     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5627                          Op.getOperand(InsertIdx),
5628                          DAG.getIntPtrConstant(InsertIdx, dl));
5629   }
5630   return DstVec;
5631 }
5632
5633 /// \brief Return true if \p N implements a horizontal binop and return the
5634 /// operands for the horizontal binop into V0 and V1.
5635 ///
5636 /// This is a helper function of LowerToHorizontalOp().
5637 /// This function checks that the build_vector \p N in input implements a
5638 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5639 /// operation to match.
5640 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5641 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5642 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5643 /// arithmetic sub.
5644 ///
5645 /// This function only analyzes elements of \p N whose indices are
5646 /// in range [BaseIdx, LastIdx).
5647 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5648                               SelectionDAG &DAG,
5649                               unsigned BaseIdx, unsigned LastIdx,
5650                               SDValue &V0, SDValue &V1) {
5651   EVT VT = N->getValueType(0);
5652
5653   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5654   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5655          "Invalid Vector in input!");
5656
5657   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5658   bool CanFold = true;
5659   unsigned ExpectedVExtractIdx = BaseIdx;
5660   unsigned NumElts = LastIdx - BaseIdx;
5661   V0 = DAG.getUNDEF(VT);
5662   V1 = DAG.getUNDEF(VT);
5663
5664   // Check if N implements a horizontal binop.
5665   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5666     SDValue Op = N->getOperand(i + BaseIdx);
5667
5668     // Skip UNDEFs.
5669     if (Op->getOpcode() == ISD::UNDEF) {
5670       // Update the expected vector extract index.
5671       if (i * 2 == NumElts)
5672         ExpectedVExtractIdx = BaseIdx;
5673       ExpectedVExtractIdx += 2;
5674       continue;
5675     }
5676
5677     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5678
5679     if (!CanFold)
5680       break;
5681
5682     SDValue Op0 = Op.getOperand(0);
5683     SDValue Op1 = Op.getOperand(1);
5684
5685     // Try to match the following pattern:
5686     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5687     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5688         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5689         Op0.getOperand(0) == Op1.getOperand(0) &&
5690         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5691         isa<ConstantSDNode>(Op1.getOperand(1)));
5692     if (!CanFold)
5693       break;
5694
5695     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5696     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5697
5698     if (i * 2 < NumElts) {
5699       if (V0.getOpcode() == ISD::UNDEF) {
5700         V0 = Op0.getOperand(0);
5701         if (V0.getValueType() != VT)
5702           return false;
5703       }
5704     } else {
5705       if (V1.getOpcode() == ISD::UNDEF) {
5706         V1 = Op0.getOperand(0);
5707         if (V1.getValueType() != VT)
5708           return false;
5709       }
5710       if (i * 2 == NumElts)
5711         ExpectedVExtractIdx = BaseIdx;
5712     }
5713
5714     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5715     if (I0 == ExpectedVExtractIdx)
5716       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5717     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5718       // Try to match the following dag sequence:
5719       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5720       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5721     } else
5722       CanFold = false;
5723
5724     ExpectedVExtractIdx += 2;
5725   }
5726
5727   return CanFold;
5728 }
5729
5730 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5731 /// a concat_vector.
5732 ///
5733 /// This is a helper function of LowerToHorizontalOp().
5734 /// This function expects two 256-bit vectors called V0 and V1.
5735 /// At first, each vector is split into two separate 128-bit vectors.
5736 /// Then, the resulting 128-bit vectors are used to implement two
5737 /// horizontal binary operations.
5738 ///
5739 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5740 ///
5741 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5742 /// the two new horizontal binop.
5743 /// When Mode is set, the first horizontal binop dag node would take as input
5744 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5745 /// horizontal binop dag node would take as input the lower 128-bit of V1
5746 /// and the upper 128-bit of V1.
5747 ///   Example:
5748 ///     HADD V0_LO, V0_HI
5749 ///     HADD V1_LO, V1_HI
5750 ///
5751 /// Otherwise, the first horizontal binop dag node takes as input the lower
5752 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5753 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5754 ///   Example:
5755 ///     HADD V0_LO, V1_LO
5756 ///     HADD V0_HI, V1_HI
5757 ///
5758 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5759 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5760 /// the upper 128-bits of the result.
5761 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5762                                      SDLoc DL, SelectionDAG &DAG,
5763                                      unsigned X86Opcode, bool Mode,
5764                                      bool isUndefLO, bool isUndefHI) {
5765   EVT VT = V0.getValueType();
5766   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5767          "Invalid nodes in input!");
5768
5769   unsigned NumElts = VT.getVectorNumElements();
5770   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5771   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5772   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5773   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5774   EVT NewVT = V0_LO.getValueType();
5775
5776   SDValue LO = DAG.getUNDEF(NewVT);
5777   SDValue HI = DAG.getUNDEF(NewVT);
5778
5779   if (Mode) {
5780     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5781     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5782       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5783     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5784       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5785   } else {
5786     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5787     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5788                        V1_LO->getOpcode() != ISD::UNDEF))
5789       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5790
5791     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5792                        V1_HI->getOpcode() != ISD::UNDEF))
5793       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5794   }
5795
5796   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5797 }
5798
5799 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5800 /// node.
5801 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5802                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5803   EVT VT = BV->getValueType(0);
5804   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5805       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5806     return SDValue();
5807
5808   SDLoc DL(BV);
5809   unsigned NumElts = VT.getVectorNumElements();
5810   SDValue InVec0 = DAG.getUNDEF(VT);
5811   SDValue InVec1 = DAG.getUNDEF(VT);
5812
5813   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5814           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5815
5816   // Odd-numbered elements in the input build vector are obtained from
5817   // adding two integer/float elements.
5818   // Even-numbered elements in the input build vector are obtained from
5819   // subtracting two integer/float elements.
5820   unsigned ExpectedOpcode = ISD::FSUB;
5821   unsigned NextExpectedOpcode = ISD::FADD;
5822   bool AddFound = false;
5823   bool SubFound = false;
5824
5825   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5826     SDValue Op = BV->getOperand(i);
5827
5828     // Skip 'undef' values.
5829     unsigned Opcode = Op.getOpcode();
5830     if (Opcode == ISD::UNDEF) {
5831       std::swap(ExpectedOpcode, NextExpectedOpcode);
5832       continue;
5833     }
5834
5835     // Early exit if we found an unexpected opcode.
5836     if (Opcode != ExpectedOpcode)
5837       return SDValue();
5838
5839     SDValue Op0 = Op.getOperand(0);
5840     SDValue Op1 = Op.getOperand(1);
5841
5842     // Try to match the following pattern:
5843     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5844     // Early exit if we cannot match that sequence.
5845     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5846         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5847         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5848         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5849         Op0.getOperand(1) != Op1.getOperand(1))
5850       return SDValue();
5851
5852     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5853     if (I0 != i)
5854       return SDValue();
5855
5856     // We found a valid add/sub node. Update the information accordingly.
5857     if (i & 1)
5858       AddFound = true;
5859     else
5860       SubFound = true;
5861
5862     // Update InVec0 and InVec1.
5863     if (InVec0.getOpcode() == ISD::UNDEF) {
5864       InVec0 = Op0.getOperand(0);
5865       if (InVec0.getValueType() != VT)
5866         return SDValue();
5867     }
5868     if (InVec1.getOpcode() == ISD::UNDEF) {
5869       InVec1 = Op1.getOperand(0);
5870       if (InVec1.getValueType() != VT)
5871         return SDValue();
5872     }
5873
5874     // Make sure that operands in input to each add/sub node always
5875     // come from a same pair of vectors.
5876     if (InVec0 != Op0.getOperand(0)) {
5877       if (ExpectedOpcode == ISD::FSUB)
5878         return SDValue();
5879
5880       // FADD is commutable. Try to commute the operands
5881       // and then test again.
5882       std::swap(Op0, Op1);
5883       if (InVec0 != Op0.getOperand(0))
5884         return SDValue();
5885     }
5886
5887     if (InVec1 != Op1.getOperand(0))
5888       return SDValue();
5889
5890     // Update the pair of expected opcodes.
5891     std::swap(ExpectedOpcode, NextExpectedOpcode);
5892   }
5893
5894   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5895   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5896       InVec1.getOpcode() != ISD::UNDEF)
5897     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5898
5899   return SDValue();
5900 }
5901
5902 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5903 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5904                                    const X86Subtarget *Subtarget,
5905                                    SelectionDAG &DAG) {
5906   EVT VT = BV->getValueType(0);
5907   unsigned NumElts = VT.getVectorNumElements();
5908   unsigned NumUndefsLO = 0;
5909   unsigned NumUndefsHI = 0;
5910   unsigned Half = NumElts/2;
5911
5912   // Count the number of UNDEF operands in the build_vector in input.
5913   for (unsigned i = 0, e = Half; i != e; ++i)
5914     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5915       NumUndefsLO++;
5916
5917   for (unsigned i = Half, e = NumElts; i != e; ++i)
5918     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5919       NumUndefsHI++;
5920
5921   // Early exit if this is either a build_vector of all UNDEFs or all the
5922   // operands but one are UNDEF.
5923   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5924     return SDValue();
5925
5926   SDLoc DL(BV);
5927   SDValue InVec0, InVec1;
5928   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5929     // Try to match an SSE3 float HADD/HSUB.
5930     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5931       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5932
5933     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5934       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5935   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5936     // Try to match an SSSE3 integer HADD/HSUB.
5937     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5938       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5939
5940     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5941       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5942   }
5943
5944   if (!Subtarget->hasAVX())
5945     return SDValue();
5946
5947   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5948     // Try to match an AVX horizontal add/sub of packed single/double
5949     // precision floating point values from 256-bit vectors.
5950     SDValue InVec2, InVec3;
5951     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5952         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5953         ((InVec0.getOpcode() == ISD::UNDEF ||
5954           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5955         ((InVec1.getOpcode() == ISD::UNDEF ||
5956           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5957       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5958
5959     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5960         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5961         ((InVec0.getOpcode() == ISD::UNDEF ||
5962           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5963         ((InVec1.getOpcode() == ISD::UNDEF ||
5964           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5965       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5966   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5967     // Try to match an AVX2 horizontal add/sub of signed integers.
5968     SDValue InVec2, InVec3;
5969     unsigned X86Opcode;
5970     bool CanFold = true;
5971
5972     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5973         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5974         ((InVec0.getOpcode() == ISD::UNDEF ||
5975           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5976         ((InVec1.getOpcode() == ISD::UNDEF ||
5977           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5978       X86Opcode = X86ISD::HADD;
5979     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5980         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5981         ((InVec0.getOpcode() == ISD::UNDEF ||
5982           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5983         ((InVec1.getOpcode() == ISD::UNDEF ||
5984           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5985       X86Opcode = X86ISD::HSUB;
5986     else
5987       CanFold = false;
5988
5989     if (CanFold) {
5990       // Fold this build_vector into a single horizontal add/sub.
5991       // Do this only if the target has AVX2.
5992       if (Subtarget->hasAVX2())
5993         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5994
5995       // Do not try to expand this build_vector into a pair of horizontal
5996       // add/sub if we can emit a pair of scalar add/sub.
5997       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5998         return SDValue();
5999
6000       // Convert this build_vector into a pair of horizontal binop followed by
6001       // a concat vector.
6002       bool isUndefLO = NumUndefsLO == Half;
6003       bool isUndefHI = NumUndefsHI == Half;
6004       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6005                                    isUndefLO, isUndefHI);
6006     }
6007   }
6008
6009   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6010        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6011     unsigned X86Opcode;
6012     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6013       X86Opcode = X86ISD::HADD;
6014     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6015       X86Opcode = X86ISD::HSUB;
6016     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6017       X86Opcode = X86ISD::FHADD;
6018     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6019       X86Opcode = X86ISD::FHSUB;
6020     else
6021       return SDValue();
6022
6023     // Don't try to expand this build_vector into a pair of horizontal add/sub
6024     // if we can simply emit a pair of scalar add/sub.
6025     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6026       return SDValue();
6027
6028     // Convert this build_vector into two horizontal add/sub followed by
6029     // a concat vector.
6030     bool isUndefLO = NumUndefsLO == Half;
6031     bool isUndefHI = NumUndefsHI == Half;
6032     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6033                                  isUndefLO, isUndefHI);
6034   }
6035
6036   return SDValue();
6037 }
6038
6039 SDValue
6040 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6041   SDLoc dl(Op);
6042
6043   MVT VT = Op.getSimpleValueType();
6044   MVT ExtVT = VT.getVectorElementType();
6045   unsigned NumElems = Op.getNumOperands();
6046
6047   // Generate vectors for predicate vectors.
6048   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6049     return LowerBUILD_VECTORvXi1(Op, DAG);
6050
6051   // Vectors containing all zeros can be matched by pxor and xorps later
6052   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6053     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6054     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6055     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6056       return Op;
6057
6058     return getZeroVector(VT, Subtarget, DAG, dl);
6059   }
6060
6061   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6062   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6063   // vpcmpeqd on 256-bit vectors.
6064   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6065     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6066       return Op;
6067
6068     if (!VT.is512BitVector())
6069       return getOnesVector(VT, Subtarget, DAG, dl);
6070   }
6071
6072   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6073   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6074     return AddSub;
6075   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6076     return HorizontalOp;
6077   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6078     return Broadcast;
6079
6080   unsigned EVTBits = ExtVT.getSizeInBits();
6081
6082   unsigned NumZero  = 0;
6083   unsigned NumNonZero = 0;
6084   unsigned NonZeros = 0;
6085   bool IsAllConstants = true;
6086   SmallSet<SDValue, 8> Values;
6087   for (unsigned i = 0; i < NumElems; ++i) {
6088     SDValue Elt = Op.getOperand(i);
6089     if (Elt.getOpcode() == ISD::UNDEF)
6090       continue;
6091     Values.insert(Elt);
6092     if (Elt.getOpcode() != ISD::Constant &&
6093         Elt.getOpcode() != ISD::ConstantFP)
6094       IsAllConstants = false;
6095     if (X86::isZeroNode(Elt))
6096       NumZero++;
6097     else {
6098       NonZeros |= (1 << i);
6099       NumNonZero++;
6100     }
6101   }
6102
6103   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6104   if (NumNonZero == 0)
6105     return DAG.getUNDEF(VT);
6106
6107   // Special case for single non-zero, non-undef, element.
6108   if (NumNonZero == 1) {
6109     unsigned Idx = countTrailingZeros(NonZeros);
6110     SDValue Item = Op.getOperand(Idx);
6111
6112     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6113     // the value are obviously zero, truncate the value to i32 and do the
6114     // insertion that way.  Only do this if the value is non-constant or if the
6115     // value is a constant being inserted into element 0.  It is cheaper to do
6116     // a constant pool load than it is to do a movd + shuffle.
6117     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6118         (!IsAllConstants || Idx == 0)) {
6119       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6120         // Handle SSE only.
6121         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6122         EVT VecVT = MVT::v4i32;
6123
6124         // Truncate the value (which may itself be a constant) to i32, and
6125         // convert it to a vector with movd (S2V+shuffle to zero extend).
6126         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6127         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6128         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6129                                       Item, Idx * 2, true, Subtarget, DAG));
6130       }
6131     }
6132
6133     // If we have a constant or non-constant insertion into the low element of
6134     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6135     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6136     // depending on what the source datatype is.
6137     if (Idx == 0) {
6138       if (NumZero == 0)
6139         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6140
6141       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6142           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6143         if (VT.is512BitVector()) {
6144           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6145           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6146                              Item, DAG.getIntPtrConstant(0, dl));
6147         }
6148         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6149                "Expected an SSE value type!");
6150         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6151         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6152         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6153       }
6154
6155       // We can't directly insert an i8 or i16 into a vector, so zero extend
6156       // it to i32 first.
6157       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6158         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6159         if (VT.is256BitVector()) {
6160           if (Subtarget->hasAVX()) {
6161             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6162             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6163           } else {
6164             // Without AVX, we need to extend to a 128-bit vector and then
6165             // insert into the 256-bit vector.
6166             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6167             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6168             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6169           }
6170         } else {
6171           assert(VT.is128BitVector() && "Expected an SSE value type!");
6172           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6173           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6174         }
6175         return DAG.getBitcast(VT, Item);
6176       }
6177     }
6178
6179     // Is it a vector logical left shift?
6180     if (NumElems == 2 && Idx == 1 &&
6181         X86::isZeroNode(Op.getOperand(0)) &&
6182         !X86::isZeroNode(Op.getOperand(1))) {
6183       unsigned NumBits = VT.getSizeInBits();
6184       return getVShift(true, VT,
6185                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6186                                    VT, Op.getOperand(1)),
6187                        NumBits/2, DAG, *this, dl);
6188     }
6189
6190     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6191       return SDValue();
6192
6193     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6194     // is a non-constant being inserted into an element other than the low one,
6195     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6196     // movd/movss) to move this into the low element, then shuffle it into
6197     // place.
6198     if (EVTBits == 32) {
6199       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6200       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6201     }
6202   }
6203
6204   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6205   if (Values.size() == 1) {
6206     if (EVTBits == 32) {
6207       // Instead of a shuffle like this:
6208       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6209       // Check if it's possible to issue this instead.
6210       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6211       unsigned Idx = countTrailingZeros(NonZeros);
6212       SDValue Item = Op.getOperand(Idx);
6213       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6214         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6215     }
6216     return SDValue();
6217   }
6218
6219   // A vector full of immediates; various special cases are already
6220   // handled, so this is best done with a single constant-pool load.
6221   if (IsAllConstants)
6222     return SDValue();
6223
6224   // For AVX-length vectors, see if we can use a vector load to get all of the
6225   // elements, otherwise build the individual 128-bit pieces and use
6226   // shuffles to put them in place.
6227   if (VT.is256BitVector() || VT.is512BitVector()) {
6228     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6229
6230     // Check for a build vector of consecutive loads.
6231     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6232       return LD;
6233
6234     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6235
6236     // Build both the lower and upper subvector.
6237     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6238                                 makeArrayRef(&V[0], NumElems/2));
6239     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6240                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6241
6242     // Recreate the wider vector with the lower and upper part.
6243     if (VT.is256BitVector())
6244       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6245     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6246   }
6247
6248   // Let legalizer expand 2-wide build_vectors.
6249   if (EVTBits == 64) {
6250     if (NumNonZero == 1) {
6251       // One half is zero or undef.
6252       unsigned Idx = countTrailingZeros(NonZeros);
6253       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6254                                  Op.getOperand(Idx));
6255       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6256     }
6257     return SDValue();
6258   }
6259
6260   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6261   if (EVTBits == 8 && NumElems == 16)
6262     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6263                                         Subtarget, *this))
6264       return V;
6265
6266   if (EVTBits == 16 && NumElems == 8)
6267     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6268                                       Subtarget, *this))
6269       return V;
6270
6271   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6272   if (EVTBits == 32 && NumElems == 4)
6273     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6274       return V;
6275
6276   // If element VT is == 32 bits, turn it into a number of shuffles.
6277   SmallVector<SDValue, 8> V(NumElems);
6278   if (NumElems == 4 && NumZero > 0) {
6279     for (unsigned i = 0; i < 4; ++i) {
6280       bool isZero = !(NonZeros & (1 << i));
6281       if (isZero)
6282         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6283       else
6284         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6285     }
6286
6287     for (unsigned i = 0; i < 2; ++i) {
6288       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6289         default: break;
6290         case 0:
6291           V[i] = V[i*2];  // Must be a zero vector.
6292           break;
6293         case 1:
6294           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6295           break;
6296         case 2:
6297           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6298           break;
6299         case 3:
6300           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6301           break;
6302       }
6303     }
6304
6305     bool Reverse1 = (NonZeros & 0x3) == 2;
6306     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6307     int MaskVec[] = {
6308       Reverse1 ? 1 : 0,
6309       Reverse1 ? 0 : 1,
6310       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6311       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6312     };
6313     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6314   }
6315
6316   if (Values.size() > 1 && VT.is128BitVector()) {
6317     // Check for a build vector of consecutive loads.
6318     for (unsigned i = 0; i < NumElems; ++i)
6319       V[i] = Op.getOperand(i);
6320
6321     // Check for elements which are consecutive loads.
6322     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6323       return LD;
6324
6325     // Check for a build vector from mostly shuffle plus few inserting.
6326     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6327       return Sh;
6328
6329     // For SSE 4.1, use insertps to put the high elements into the low element.
6330     if (Subtarget->hasSSE41()) {
6331       SDValue Result;
6332       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6333         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6334       else
6335         Result = DAG.getUNDEF(VT);
6336
6337       for (unsigned i = 1; i < NumElems; ++i) {
6338         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6339         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6340                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6341       }
6342       return Result;
6343     }
6344
6345     // Otherwise, expand into a number of unpckl*, start by extending each of
6346     // our (non-undef) elements to the full vector width with the element in the
6347     // bottom slot of the vector (which generates no code for SSE).
6348     for (unsigned i = 0; i < NumElems; ++i) {
6349       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6350         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6351       else
6352         V[i] = DAG.getUNDEF(VT);
6353     }
6354
6355     // Next, we iteratively mix elements, e.g. for v4f32:
6356     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6357     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6358     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6359     unsigned EltStride = NumElems >> 1;
6360     while (EltStride != 0) {
6361       for (unsigned i = 0; i < EltStride; ++i) {
6362         // If V[i+EltStride] is undef and this is the first round of mixing,
6363         // then it is safe to just drop this shuffle: V[i] is already in the
6364         // right place, the one element (since it's the first round) being
6365         // inserted as undef can be dropped.  This isn't safe for successive
6366         // rounds because they will permute elements within both vectors.
6367         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6368             EltStride == NumElems/2)
6369           continue;
6370
6371         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6372       }
6373       EltStride >>= 1;
6374     }
6375     return V[0];
6376   }
6377   return SDValue();
6378 }
6379
6380 // 256-bit AVX can use the vinsertf128 instruction
6381 // to create 256-bit vectors from two other 128-bit ones.
6382 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6383   SDLoc dl(Op);
6384   MVT ResVT = Op.getSimpleValueType();
6385
6386   assert((ResVT.is256BitVector() ||
6387           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6388
6389   SDValue V1 = Op.getOperand(0);
6390   SDValue V2 = Op.getOperand(1);
6391   unsigned NumElems = ResVT.getVectorNumElements();
6392   if (ResVT.is256BitVector())
6393     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6394
6395   if (Op.getNumOperands() == 4) {
6396     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6397                                 ResVT.getVectorNumElements()/2);
6398     SDValue V3 = Op.getOperand(2);
6399     SDValue V4 = Op.getOperand(3);
6400     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6401       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6402   }
6403   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6404 }
6405
6406 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6407                                        const X86Subtarget *Subtarget,
6408                                        SelectionDAG & DAG) {
6409   SDLoc dl(Op);
6410   MVT ResVT = Op.getSimpleValueType();
6411   unsigned NumOfOperands = Op.getNumOperands();
6412
6413   assert(isPowerOf2_32(NumOfOperands) &&
6414          "Unexpected number of operands in CONCAT_VECTORS");
6415
6416   if (NumOfOperands > 2) {
6417     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6418                                   ResVT.getVectorNumElements()/2);
6419     SmallVector<SDValue, 2> Ops;
6420     for (unsigned i = 0; i < NumOfOperands/2; i++)
6421       Ops.push_back(Op.getOperand(i));
6422     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6423     Ops.clear();
6424     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6425       Ops.push_back(Op.getOperand(i));
6426     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6427     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6428   }
6429
6430   SDValue V1 = Op.getOperand(0);
6431   SDValue V2 = Op.getOperand(1);
6432   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6433   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6434
6435   if (IsZeroV1 && IsZeroV2)
6436     return getZeroVector(ResVT, Subtarget, DAG, dl);
6437
6438   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6439   SDValue Undef = DAG.getUNDEF(ResVT);
6440   unsigned NumElems = ResVT.getVectorNumElements();
6441   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6442
6443   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6444   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6445   if (IsZeroV1)
6446     return V2;
6447
6448   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6449   // Zero the upper bits of V1
6450   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6451   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6452   if (IsZeroV2)
6453     return V1;
6454   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6455 }
6456
6457 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6458                                    const X86Subtarget *Subtarget,
6459                                    SelectionDAG &DAG) {
6460   MVT VT = Op.getSimpleValueType();
6461   if (VT.getVectorElementType() == MVT::i1)
6462     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6463
6464   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6465          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6466           Op.getNumOperands() == 4)));
6467
6468   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6469   // from two other 128-bit ones.
6470
6471   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6472   return LowerAVXCONCAT_VECTORS(Op, DAG);
6473 }
6474
6475
6476 //===----------------------------------------------------------------------===//
6477 // Vector shuffle lowering
6478 //
6479 // This is an experimental code path for lowering vector shuffles on x86. It is
6480 // designed to handle arbitrary vector shuffles and blends, gracefully
6481 // degrading performance as necessary. It works hard to recognize idiomatic
6482 // shuffles and lower them to optimal instruction patterns without leaving
6483 // a framework that allows reasonably efficient handling of all vector shuffle
6484 // patterns.
6485 //===----------------------------------------------------------------------===//
6486
6487 /// \brief Tiny helper function to identify a no-op mask.
6488 ///
6489 /// This is a somewhat boring predicate function. It checks whether the mask
6490 /// array input, which is assumed to be a single-input shuffle mask of the kind
6491 /// used by the X86 shuffle instructions (not a fully general
6492 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6493 /// in-place shuffle are 'no-op's.
6494 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6495   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6496     if (Mask[i] != -1 && Mask[i] != i)
6497       return false;
6498   return true;
6499 }
6500
6501 /// \brief Helper function to classify a mask as a single-input mask.
6502 ///
6503 /// This isn't a generic single-input test because in the vector shuffle
6504 /// lowering we canonicalize single inputs to be the first input operand. This
6505 /// means we can more quickly test for a single input by only checking whether
6506 /// an input from the second operand exists. We also assume that the size of
6507 /// mask corresponds to the size of the input vectors which isn't true in the
6508 /// fully general case.
6509 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6510   for (int M : Mask)
6511     if (M >= (int)Mask.size())
6512       return false;
6513   return true;
6514 }
6515
6516 /// \brief Test whether there are elements crossing 128-bit lanes in this
6517 /// shuffle mask.
6518 ///
6519 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6520 /// and we routinely test for these.
6521 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6522   int LaneSize = 128 / VT.getScalarSizeInBits();
6523   int Size = Mask.size();
6524   for (int i = 0; i < Size; ++i)
6525     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6526       return true;
6527   return false;
6528 }
6529
6530 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6531 ///
6532 /// This checks a shuffle mask to see if it is performing the same
6533 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6534 /// that it is also not lane-crossing. It may however involve a blend from the
6535 /// same lane of a second vector.
6536 ///
6537 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6538 /// non-trivial to compute in the face of undef lanes. The representation is
6539 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6540 /// entries from both V1 and V2 inputs to the wider mask.
6541 static bool
6542 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6543                                 SmallVectorImpl<int> &RepeatedMask) {
6544   int LaneSize = 128 / VT.getScalarSizeInBits();
6545   RepeatedMask.resize(LaneSize, -1);
6546   int Size = Mask.size();
6547   for (int i = 0; i < Size; ++i) {
6548     if (Mask[i] < 0)
6549       continue;
6550     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6551       // This entry crosses lanes, so there is no way to model this shuffle.
6552       return false;
6553
6554     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6555     if (RepeatedMask[i % LaneSize] == -1)
6556       // This is the first non-undef entry in this slot of a 128-bit lane.
6557       RepeatedMask[i % LaneSize] =
6558           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6559     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6560       // Found a mismatch with the repeated mask.
6561       return false;
6562   }
6563   return true;
6564 }
6565
6566 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6567 /// arguments.
6568 ///
6569 /// This is a fast way to test a shuffle mask against a fixed pattern:
6570 ///
6571 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6572 ///
6573 /// It returns true if the mask is exactly as wide as the argument list, and
6574 /// each element of the mask is either -1 (signifying undef) or the value given
6575 /// in the argument.
6576 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6577                                 ArrayRef<int> ExpectedMask) {
6578   if (Mask.size() != ExpectedMask.size())
6579     return false;
6580
6581   int Size = Mask.size();
6582
6583   // If the values are build vectors, we can look through them to find
6584   // equivalent inputs that make the shuffles equivalent.
6585   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6586   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6587
6588   for (int i = 0; i < Size; ++i)
6589     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6590       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6591       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6592       if (!MaskBV || !ExpectedBV ||
6593           MaskBV->getOperand(Mask[i] % Size) !=
6594               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6595         return false;
6596     }
6597
6598   return true;
6599 }
6600
6601 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6602 ///
6603 /// This helper function produces an 8-bit shuffle immediate corresponding to
6604 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6605 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6606 /// example.
6607 ///
6608 /// NB: We rely heavily on "undef" masks preserving the input lane.
6609 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6610                                           SelectionDAG &DAG) {
6611   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6612   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6613   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6614   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6615   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6616
6617   unsigned Imm = 0;
6618   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6619   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6620   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6621   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6622   return DAG.getConstant(Imm, DL, MVT::i8);
6623 }
6624
6625 /// \brief Compute whether each element of a shuffle is zeroable.
6626 ///
6627 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6628 /// Either it is an undef element in the shuffle mask, the element of the input
6629 /// referenced is undef, or the element of the input referenced is known to be
6630 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6631 /// as many lanes with this technique as possible to simplify the remaining
6632 /// shuffle.
6633 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6634                                                      SDValue V1, SDValue V2) {
6635   SmallBitVector Zeroable(Mask.size(), false);
6636
6637   while (V1.getOpcode() == ISD::BITCAST)
6638     V1 = V1->getOperand(0);
6639   while (V2.getOpcode() == ISD::BITCAST)
6640     V2 = V2->getOperand(0);
6641
6642   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6643   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6644
6645   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6646     int M = Mask[i];
6647     // Handle the easy cases.
6648     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6649       Zeroable[i] = true;
6650       continue;
6651     }
6652
6653     // If this is an index into a build_vector node (which has the same number
6654     // of elements), dig out the input value and use it.
6655     SDValue V = M < Size ? V1 : V2;
6656     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6657       continue;
6658
6659     SDValue Input = V.getOperand(M % Size);
6660     // The UNDEF opcode check really should be dead code here, but not quite
6661     // worth asserting on (it isn't invalid, just unexpected).
6662     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6663       Zeroable[i] = true;
6664   }
6665
6666   return Zeroable;
6667 }
6668
6669 // X86 has dedicated unpack instructions that can handle specific blend
6670 // operations: UNPCKH and UNPCKL.
6671 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6672                                            SDValue V1, SDValue V2,
6673                                            SelectionDAG &DAG) {
6674   int NumElts = VT.getVectorNumElements();
6675   bool Unpckl = true;
6676   bool Unpckh = true;
6677   bool UnpcklSwapped = true;
6678   bool UnpckhSwapped = true;
6679   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6680
6681   for (int i = 0; i < NumElts; ++i) {
6682     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6683
6684     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6685     int HiPos = LoPos + NumEltsInLane / 2;
6686     int LoPosSwapped = (LoPos + NumElts) % (NumElts * 2);
6687     int HiPosSwapped = (HiPos + NumElts) % (NumElts * 2);
6688
6689     if (Mask[i] == -1)
6690       continue;
6691     if (Mask[i] != LoPos)
6692       Unpckl = false;
6693     if (Mask[i] != HiPos)
6694       Unpckh = false;
6695     if (Mask[i] != LoPosSwapped)
6696       UnpcklSwapped = false;
6697     if (Mask[i] != HiPosSwapped)
6698       UnpckhSwapped = false;
6699     if (!Unpckl && !Unpckh && !UnpcklSwapped && !UnpckhSwapped)
6700       return SDValue();
6701   }
6702   if (Unpckl)
6703     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6704   if (Unpckh)
6705     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6706   if (UnpcklSwapped)
6707     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6708   if (UnpckhSwapped)
6709     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6710
6711   llvm_unreachable("Unexpected result of UNPCK mask analysis");
6712   return SDValue();
6713 }
6714
6715 /// \brief Try to emit a bitmask instruction for a shuffle.
6716 ///
6717 /// This handles cases where we can model a blend exactly as a bitmask due to
6718 /// one of the inputs being zeroable.
6719 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6720                                            SDValue V2, ArrayRef<int> Mask,
6721                                            SelectionDAG &DAG) {
6722   MVT EltVT = VT.getScalarType();
6723   int NumEltBits = EltVT.getSizeInBits();
6724   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6725   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6726   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6727                                     IntEltVT);
6728   if (EltVT.isFloatingPoint()) {
6729     Zero = DAG.getBitcast(EltVT, Zero);
6730     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6731   }
6732   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6733   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6734   SDValue V;
6735   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6736     if (Zeroable[i])
6737       continue;
6738     if (Mask[i] % Size != i)
6739       return SDValue(); // Not a blend.
6740     if (!V)
6741       V = Mask[i] < Size ? V1 : V2;
6742     else if (V != (Mask[i] < Size ? V1 : V2))
6743       return SDValue(); // Can only let one input through the mask.
6744
6745     VMaskOps[i] = AllOnes;
6746   }
6747   if (!V)
6748     return SDValue(); // No non-zeroable elements!
6749
6750   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6751   V = DAG.getNode(VT.isFloatingPoint()
6752                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6753                   DL, VT, V, VMask);
6754   return V;
6755 }
6756
6757 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6758 ///
6759 /// This is used as a fallback approach when first class blend instructions are
6760 /// unavailable. Currently it is only suitable for integer vectors, but could
6761 /// be generalized for floating point vectors if desirable.
6762 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6763                                             SDValue V2, ArrayRef<int> Mask,
6764                                             SelectionDAG &DAG) {
6765   assert(VT.isInteger() && "Only supports integer vector types!");
6766   MVT EltVT = VT.getScalarType();
6767   int NumEltBits = EltVT.getSizeInBits();
6768   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6769   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6770                                     EltVT);
6771   SmallVector<SDValue, 16> MaskOps;
6772   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6773     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6774       return SDValue(); // Shuffled input!
6775     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6776   }
6777
6778   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6779   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6780   // We have to cast V2 around.
6781   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6782   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6783                                       DAG.getBitcast(MaskVT, V1Mask),
6784                                       DAG.getBitcast(MaskVT, V2)));
6785   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6786 }
6787
6788 /// \brief Try to emit a blend instruction for a shuffle.
6789 ///
6790 /// This doesn't do any checks for the availability of instructions for blending
6791 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6792 /// be matched in the backend with the type given. What it does check for is
6793 /// that the shuffle mask is in fact a blend.
6794 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6795                                          SDValue V2, ArrayRef<int> Mask,
6796                                          const X86Subtarget *Subtarget,
6797                                          SelectionDAG &DAG) {
6798   unsigned BlendMask = 0;
6799   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6800     if (Mask[i] >= Size) {
6801       if (Mask[i] != i + Size)
6802         return SDValue(); // Shuffled V2 input!
6803       BlendMask |= 1u << i;
6804       continue;
6805     }
6806     if (Mask[i] >= 0 && Mask[i] != i)
6807       return SDValue(); // Shuffled V1 input!
6808   }
6809   switch (VT.SimpleTy) {
6810   case MVT::v2f64:
6811   case MVT::v4f32:
6812   case MVT::v4f64:
6813   case MVT::v8f32:
6814     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6815                        DAG.getConstant(BlendMask, DL, MVT::i8));
6816
6817   case MVT::v4i64:
6818   case MVT::v8i32:
6819     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6820     // FALLTHROUGH
6821   case MVT::v2i64:
6822   case MVT::v4i32:
6823     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6824     // that instruction.
6825     if (Subtarget->hasAVX2()) {
6826       // Scale the blend by the number of 32-bit dwords per element.
6827       int Scale =  VT.getScalarSizeInBits() / 32;
6828       BlendMask = 0;
6829       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6830         if (Mask[i] >= Size)
6831           for (int j = 0; j < Scale; ++j)
6832             BlendMask |= 1u << (i * Scale + j);
6833
6834       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6835       V1 = DAG.getBitcast(BlendVT, V1);
6836       V2 = DAG.getBitcast(BlendVT, V2);
6837       return DAG.getBitcast(
6838           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6839                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6840     }
6841     // FALLTHROUGH
6842   case MVT::v8i16: {
6843     // For integer shuffles we need to expand the mask and cast the inputs to
6844     // v8i16s prior to blending.
6845     int Scale = 8 / VT.getVectorNumElements();
6846     BlendMask = 0;
6847     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6848       if (Mask[i] >= Size)
6849         for (int j = 0; j < Scale; ++j)
6850           BlendMask |= 1u << (i * Scale + j);
6851
6852     V1 = DAG.getBitcast(MVT::v8i16, V1);
6853     V2 = DAG.getBitcast(MVT::v8i16, V2);
6854     return DAG.getBitcast(VT,
6855                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6856                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6857   }
6858
6859   case MVT::v16i16: {
6860     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6861     SmallVector<int, 8> RepeatedMask;
6862     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6863       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6864       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6865       BlendMask = 0;
6866       for (int i = 0; i < 8; ++i)
6867         if (RepeatedMask[i] >= 16)
6868           BlendMask |= 1u << i;
6869       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6870                          DAG.getConstant(BlendMask, DL, MVT::i8));
6871     }
6872   }
6873     // FALLTHROUGH
6874   case MVT::v16i8:
6875   case MVT::v32i8: {
6876     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6877            "256-bit byte-blends require AVX2 support!");
6878
6879     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6880     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6881       return Masked;
6882
6883     // Scale the blend by the number of bytes per element.
6884     int Scale = VT.getScalarSizeInBits() / 8;
6885
6886     // This form of blend is always done on bytes. Compute the byte vector
6887     // type.
6888     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6889
6890     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6891     // mix of LLVM's code generator and the x86 backend. We tell the code
6892     // generator that boolean values in the elements of an x86 vector register
6893     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6894     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6895     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6896     // of the element (the remaining are ignored) and 0 in that high bit would
6897     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6898     // the LLVM model for boolean values in vector elements gets the relevant
6899     // bit set, it is set backwards and over constrained relative to x86's
6900     // actual model.
6901     SmallVector<SDValue, 32> VSELECTMask;
6902     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6903       for (int j = 0; j < Scale; ++j)
6904         VSELECTMask.push_back(
6905             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6906                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6907                                           MVT::i8));
6908
6909     V1 = DAG.getBitcast(BlendVT, V1);
6910     V2 = DAG.getBitcast(BlendVT, V2);
6911     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6912                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6913                                                       BlendVT, VSELECTMask),
6914                                           V1, V2));
6915   }
6916
6917   default:
6918     llvm_unreachable("Not a supported integer vector type!");
6919   }
6920 }
6921
6922 /// \brief Try to lower as a blend of elements from two inputs followed by
6923 /// a single-input permutation.
6924 ///
6925 /// This matches the pattern where we can blend elements from two inputs and
6926 /// then reduce the shuffle to a single-input permutation.
6927 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6928                                                    SDValue V2,
6929                                                    ArrayRef<int> Mask,
6930                                                    SelectionDAG &DAG) {
6931   // We build up the blend mask while checking whether a blend is a viable way
6932   // to reduce the shuffle.
6933   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6934   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6935
6936   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6937     if (Mask[i] < 0)
6938       continue;
6939
6940     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6941
6942     if (BlendMask[Mask[i] % Size] == -1)
6943       BlendMask[Mask[i] % Size] = Mask[i];
6944     else if (BlendMask[Mask[i] % Size] != Mask[i])
6945       return SDValue(); // Can't blend in the needed input!
6946
6947     PermuteMask[i] = Mask[i] % Size;
6948   }
6949
6950   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6951   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6952 }
6953
6954 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6955 /// blends and permutes.
6956 ///
6957 /// This matches the extremely common pattern for handling combined
6958 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6959 /// operations. It will try to pick the best arrangement of shuffles and
6960 /// blends.
6961 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6962                                                           SDValue V1,
6963                                                           SDValue V2,
6964                                                           ArrayRef<int> Mask,
6965                                                           SelectionDAG &DAG) {
6966   // Shuffle the input elements into the desired positions in V1 and V2 and
6967   // blend them together.
6968   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6969   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6970   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6971   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6972     if (Mask[i] >= 0 && Mask[i] < Size) {
6973       V1Mask[i] = Mask[i];
6974       BlendMask[i] = i;
6975     } else if (Mask[i] >= Size) {
6976       V2Mask[i] = Mask[i] - Size;
6977       BlendMask[i] = i + Size;
6978     }
6979
6980   // Try to lower with the simpler initial blend strategy unless one of the
6981   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6982   // shuffle may be able to fold with a load or other benefit. However, when
6983   // we'll have to do 2x as many shuffles in order to achieve this, blending
6984   // first is a better strategy.
6985   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6986     if (SDValue BlendPerm =
6987             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6988       return BlendPerm;
6989
6990   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6991   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6992   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6993 }
6994
6995 /// \brief Try to lower a vector shuffle as a byte rotation.
6996 ///
6997 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6998 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6999 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7000 /// try to generically lower a vector shuffle through such an pattern. It
7001 /// does not check for the profitability of lowering either as PALIGNR or
7002 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7003 /// This matches shuffle vectors that look like:
7004 ///
7005 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7006 ///
7007 /// Essentially it concatenates V1 and V2, shifts right by some number of
7008 /// elements, and takes the low elements as the result. Note that while this is
7009 /// specified as a *right shift* because x86 is little-endian, it is a *left
7010 /// rotate* of the vector lanes.
7011 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7012                                               SDValue V2,
7013                                               ArrayRef<int> Mask,
7014                                               const X86Subtarget *Subtarget,
7015                                               SelectionDAG &DAG) {
7016   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7017
7018   int NumElts = Mask.size();
7019   int NumLanes = VT.getSizeInBits() / 128;
7020   int NumLaneElts = NumElts / NumLanes;
7021
7022   // We need to detect various ways of spelling a rotation:
7023   //   [11, 12, 13, 14, 15,  0,  1,  2]
7024   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7025   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7026   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7027   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7028   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7029   int Rotation = 0;
7030   SDValue Lo, Hi;
7031   for (int l = 0; l < NumElts; l += NumLaneElts) {
7032     for (int i = 0; i < NumLaneElts; ++i) {
7033       if (Mask[l + i] == -1)
7034         continue;
7035       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7036
7037       // Get the mod-Size index and lane correct it.
7038       int LaneIdx = (Mask[l + i] % NumElts) - l;
7039       // Make sure it was in this lane.
7040       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7041         return SDValue();
7042
7043       // Determine where a rotated vector would have started.
7044       int StartIdx = i - LaneIdx;
7045       if (StartIdx == 0)
7046         // The identity rotation isn't interesting, stop.
7047         return SDValue();
7048
7049       // If we found the tail of a vector the rotation must be the missing
7050       // front. If we found the head of a vector, it must be how much of the
7051       // head.
7052       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7053
7054       if (Rotation == 0)
7055         Rotation = CandidateRotation;
7056       else if (Rotation != CandidateRotation)
7057         // The rotations don't match, so we can't match this mask.
7058         return SDValue();
7059
7060       // Compute which value this mask is pointing at.
7061       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7062
7063       // Compute which of the two target values this index should be assigned
7064       // to. This reflects whether the high elements are remaining or the low
7065       // elements are remaining.
7066       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7067
7068       // Either set up this value if we've not encountered it before, or check
7069       // that it remains consistent.
7070       if (!TargetV)
7071         TargetV = MaskV;
7072       else if (TargetV != MaskV)
7073         // This may be a rotation, but it pulls from the inputs in some
7074         // unsupported interleaving.
7075         return SDValue();
7076     }
7077   }
7078
7079   // Check that we successfully analyzed the mask, and normalize the results.
7080   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7081   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7082   if (!Lo)
7083     Lo = Hi;
7084   else if (!Hi)
7085     Hi = Lo;
7086
7087   // The actual rotate instruction rotates bytes, so we need to scale the
7088   // rotation based on how many bytes are in the vector lane.
7089   int Scale = 16 / NumLaneElts;
7090
7091   // SSSE3 targets can use the palignr instruction.
7092   if (Subtarget->hasSSSE3()) {
7093     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7094     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7095     Lo = DAG.getBitcast(AlignVT, Lo);
7096     Hi = DAG.getBitcast(AlignVT, Hi);
7097
7098     return DAG.getBitcast(
7099         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7100                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7101   }
7102
7103   assert(VT.getSizeInBits() == 128 &&
7104          "Rotate-based lowering only supports 128-bit lowering!");
7105   assert(Mask.size() <= 16 &&
7106          "Can shuffle at most 16 bytes in a 128-bit vector!");
7107
7108   // Default SSE2 implementation
7109   int LoByteShift = 16 - Rotation * Scale;
7110   int HiByteShift = Rotation * Scale;
7111
7112   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7113   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7114   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7115
7116   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7117                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7118   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7119                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7120   return DAG.getBitcast(VT,
7121                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7122 }
7123
7124 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7125 ///
7126 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7127 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7128 /// matches elements from one of the input vectors shuffled to the left or
7129 /// right with zeroable elements 'shifted in'. It handles both the strictly
7130 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7131 /// quad word lane.
7132 ///
7133 /// PSHL : (little-endian) left bit shift.
7134 /// [ zz, 0, zz,  2 ]
7135 /// [ -1, 4, zz, -1 ]
7136 /// PSRL : (little-endian) right bit shift.
7137 /// [  1, zz,  3, zz]
7138 /// [ -1, -1,  7, zz]
7139 /// PSLLDQ : (little-endian) left byte shift
7140 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7141 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7142 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7143 /// PSRLDQ : (little-endian) right byte shift
7144 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7145 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7146 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7147 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7148                                          SDValue V2, ArrayRef<int> Mask,
7149                                          SelectionDAG &DAG) {
7150   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7151
7152   int Size = Mask.size();
7153   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7154
7155   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7156     for (int i = 0; i < Size; i += Scale)
7157       for (int j = 0; j < Shift; ++j)
7158         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7159           return false;
7160
7161     return true;
7162   };
7163
7164   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7165     for (int i = 0; i != Size; i += Scale) {
7166       unsigned Pos = Left ? i + Shift : i;
7167       unsigned Low = Left ? i : i + Shift;
7168       unsigned Len = Scale - Shift;
7169       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7170                                       Low + (V == V1 ? 0 : Size)))
7171         return SDValue();
7172     }
7173
7174     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7175     bool ByteShift = ShiftEltBits > 64;
7176     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7177                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7178     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7179
7180     // Normalize the scale for byte shifts to still produce an i64 element
7181     // type.
7182     Scale = ByteShift ? Scale / 2 : Scale;
7183
7184     // We need to round trip through the appropriate type for the shift.
7185     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7186     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7187     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7188            "Illegal integer vector type");
7189     V = DAG.getBitcast(ShiftVT, V);
7190
7191     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7192                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7193     return DAG.getBitcast(VT, V);
7194   };
7195
7196   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7197   // keep doubling the size of the integer elements up to that. We can
7198   // then shift the elements of the integer vector by whole multiples of
7199   // their width within the elements of the larger integer vector. Test each
7200   // multiple to see if we can find a match with the moved element indices
7201   // and that the shifted in elements are all zeroable.
7202   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7203     for (int Shift = 1; Shift != Scale; ++Shift)
7204       for (bool Left : {true, false})
7205         if (CheckZeros(Shift, Scale, Left))
7206           for (SDValue V : {V1, V2})
7207             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7208               return Match;
7209
7210   // no match
7211   return SDValue();
7212 }
7213
7214 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7215 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7216                                            SDValue V2, ArrayRef<int> Mask,
7217                                            SelectionDAG &DAG) {
7218   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7219   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7220
7221   int Size = Mask.size();
7222   int HalfSize = Size / 2;
7223   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7224
7225   // Upper half must be undefined.
7226   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7227     return SDValue();
7228
7229   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7230   // Remainder of lower half result is zero and upper half is all undef.
7231   auto LowerAsEXTRQ = [&]() {
7232     // Determine the extraction length from the part of the
7233     // lower half that isn't zeroable.
7234     int Len = HalfSize;
7235     for (; Len >= 0; --Len)
7236       if (!Zeroable[Len - 1])
7237         break;
7238     assert(Len > 0 && "Zeroable shuffle mask");
7239
7240     // Attempt to match first Len sequential elements from the lower half.
7241     SDValue Src;
7242     int Idx = -1;
7243     for (int i = 0; i != Len; ++i) {
7244       int M = Mask[i];
7245       if (M < 0)
7246         continue;
7247       SDValue &V = (M < Size ? V1 : V2);
7248       M = M % Size;
7249
7250       // All mask elements must be in the lower half.
7251       if (M > HalfSize)
7252         return SDValue();
7253
7254       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7255         Src = V;
7256         Idx = M - i;
7257         continue;
7258       }
7259       return SDValue();
7260     }
7261
7262     if (Idx < 0)
7263       return SDValue();
7264
7265     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7266     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7267     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7268     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7269                        DAG.getConstant(BitLen, DL, MVT::i8),
7270                        DAG.getConstant(BitIdx, DL, MVT::i8));
7271   };
7272
7273   if (SDValue ExtrQ = LowerAsEXTRQ())
7274     return ExtrQ;
7275
7276   // INSERTQ: Extract lowest Len elements from lower half of second source and
7277   // insert over first source, starting at Idx.
7278   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7279   auto LowerAsInsertQ = [&]() {
7280     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7281       SDValue Base;
7282
7283       // Attempt to match first source from mask before insertion point.
7284       if (isUndefInRange(Mask, 0, Idx)) {
7285         /* EMPTY */
7286       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7287         Base = V1;
7288       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7289         Base = V2;
7290       } else {
7291         continue;
7292       }
7293
7294       // Extend the extraction length looking to match both the insertion of
7295       // the second source and the remaining elements of the first.
7296       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7297         SDValue Insert;
7298         int Len = Hi - Idx;
7299
7300         // Match insertion.
7301         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7302           Insert = V1;
7303         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7304           Insert = V2;
7305         } else {
7306           continue;
7307         }
7308
7309         // Match the remaining elements of the lower half.
7310         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7311           /* EMPTY */
7312         } else if ((!Base || (Base == V1)) &&
7313                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7314           Base = V1;
7315         } else if ((!Base || (Base == V2)) &&
7316                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7317                                               Size + Hi)) {
7318           Base = V2;
7319         } else {
7320           continue;
7321         }
7322
7323         // We may not have a base (first source) - this can safely be undefined.
7324         if (!Base)
7325           Base = DAG.getUNDEF(VT);
7326
7327         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7328         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7329         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7330                            DAG.getConstant(BitLen, DL, MVT::i8),
7331                            DAG.getConstant(BitIdx, DL, MVT::i8));
7332       }
7333     }
7334
7335     return SDValue();
7336   };
7337
7338   if (SDValue InsertQ = LowerAsInsertQ())
7339     return InsertQ;
7340
7341   return SDValue();
7342 }
7343
7344 /// \brief Lower a vector shuffle as a zero or any extension.
7345 ///
7346 /// Given a specific number of elements, element bit width, and extension
7347 /// stride, produce either a zero or any extension based on the available
7348 /// features of the subtarget. The extended elements are consecutive and
7349 /// begin and can start from an offseted element index in the input; to
7350 /// avoid excess shuffling the offset must either being in the bottom lane
7351 /// or at the start of a higher lane. All extended elements must be from
7352 /// the same lane.
7353 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7354     SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7355     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7356   assert(Scale > 1 && "Need a scale to extend.");
7357   int EltBits = VT.getScalarSizeInBits();
7358   int NumElements = VT.getVectorNumElements();
7359   int NumEltsPerLane = 128 / EltBits;
7360   int OffsetLane = Offset / NumEltsPerLane;
7361   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7362          "Only 8, 16, and 32 bit elements can be extended.");
7363   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7364   assert(0 <= Offset && "Extension offset must be positive.");
7365   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7366          "Extension offset must be in the first lane or start an upper lane.");
7367
7368   // Check that an index is in same lane as the base offset.
7369   auto SafeOffset = [&](int Idx) {
7370     return OffsetLane == (Idx / NumEltsPerLane);
7371   };
7372
7373   // Shift along an input so that the offset base moves to the first element.
7374   auto ShuffleOffset = [&](SDValue V) {
7375     if (!Offset)
7376       return V;
7377
7378     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7379     for (int i = 0; i * Scale < NumElements; ++i) {
7380       int SrcIdx = i + Offset;
7381       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7382     }
7383     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7384   };
7385
7386   // Found a valid zext mask! Try various lowering strategies based on the
7387   // input type and available ISA extensions.
7388   if (Subtarget->hasSSE41()) {
7389     // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7390     // PUNPCK will catch this in a later shuffle match.
7391     if (Offset && Scale == 2 && VT.getSizeInBits() == 128)
7392       return SDValue();
7393     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7394                                  NumElements / Scale);
7395     InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7396     return DAG.getBitcast(VT, InputV);
7397   }
7398
7399   assert(VT.getSizeInBits() == 128 && "Only 128-bit vectors can be extended.");
7400
7401   // For any extends we can cheat for larger element sizes and use shuffle
7402   // instructions that can fold with a load and/or copy.
7403   if (AnyExt && EltBits == 32) {
7404     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7405                          -1};
7406     return DAG.getBitcast(
7407         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7408                         DAG.getBitcast(MVT::v4i32, InputV),
7409                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7410   }
7411   if (AnyExt && EltBits == 16 && Scale > 2) {
7412     int PSHUFDMask[4] = {Offset / 2, -1,
7413                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7414     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7415                          DAG.getBitcast(MVT::v4i32, InputV),
7416                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7417     int PSHUFWMask[4] = {1, -1, -1, -1};
7418     unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7419     return DAG.getBitcast(
7420         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7421                         DAG.getBitcast(MVT::v8i16, InputV),
7422                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7423   }
7424
7425   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7426   // to 64-bits.
7427   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7428     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7429     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7430
7431     int LoIdx = Offset * EltBits;
7432     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7433                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7434                                          DAG.getConstant(EltBits, DL, MVT::i8),
7435                                          DAG.getConstant(LoIdx, DL, MVT::i8)));
7436
7437     if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7438         !SafeOffset(Offset + 1))
7439       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7440
7441     int HiIdx = (Offset + 1) * EltBits;
7442     SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7443                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7444                                          DAG.getConstant(EltBits, DL, MVT::i8),
7445                                          DAG.getConstant(HiIdx, DL, MVT::i8)));
7446     return DAG.getNode(ISD::BITCAST, DL, VT,
7447                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7448   }
7449
7450   // If this would require more than 2 unpack instructions to expand, use
7451   // pshufb when available. We can only use more than 2 unpack instructions
7452   // when zero extending i8 elements which also makes it easier to use pshufb.
7453   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7454     assert(NumElements == 16 && "Unexpected byte vector width!");
7455     SDValue PSHUFBMask[16];
7456     for (int i = 0; i < 16; ++i) {
7457       int Idx = Offset + (i / Scale);
7458       PSHUFBMask[i] = DAG.getConstant(
7459           (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7460     }
7461     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7462     return DAG.getBitcast(VT,
7463                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7464                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7465                                                   MVT::v16i8, PSHUFBMask)));
7466   }
7467
7468   // If we are extending from an (odd)offset, shuffle them by 1 element.
7469   if (Offset & 1) {
7470     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7471     for (int i = 1; i < NumElements; ++i)
7472       ShMask[i - 1] = i;
7473     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7474     Offset--;
7475   }
7476
7477   // Otherwise emit a sequence of unpacks.
7478   do {
7479     unsigned UnpackLoHi = X86ISD::UNPCKL;
7480     if (Offset >= (NumElements / 2)) {
7481       UnpackLoHi = X86ISD::UNPCKH;
7482       Offset -= (NumElements / 2);
7483     }
7484
7485     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7486     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7487                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7488     InputV = DAG.getBitcast(InputVT, InputV);
7489     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7490     Scale /= 2;
7491     EltBits *= 2;
7492     NumElements /= 2;
7493   } while (Scale > 1);
7494   return DAG.getBitcast(VT, InputV);
7495 }
7496
7497 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7498 ///
7499 /// This routine will try to do everything in its power to cleverly lower
7500 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7501 /// check for the profitability of this lowering,  it tries to aggressively
7502 /// match this pattern. It will use all of the micro-architectural details it
7503 /// can to emit an efficient lowering. It handles both blends with all-zero
7504 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7505 /// masking out later).
7506 ///
7507 /// The reason we have dedicated lowering for zext-style shuffles is that they
7508 /// are both incredibly common and often quite performance sensitive.
7509 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7510     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7511     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7512   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7513
7514   int Bits = VT.getSizeInBits();
7515   int NumLanes = Bits / 128;
7516   int NumElements = VT.getVectorNumElements();
7517   int NumEltsPerLane = NumElements / NumLanes;
7518   assert(VT.getScalarSizeInBits() <= 32 &&
7519          "Exceeds 32-bit integer zero extension limit");
7520   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7521
7522   // Define a helper function to check a particular ext-scale and lower to it if
7523   // valid.
7524   auto Lower = [&](int Scale) -> SDValue {
7525     SDValue InputV;
7526     bool AnyExt = true;
7527     int Offset = 0;
7528     int Matches = 0;
7529     for (int i = 0; i < NumElements; ++i) {
7530       int M = Mask[i];
7531       if (M == -1)
7532         continue; // Valid anywhere but doesn't tell us anything.
7533       if (i % Scale != 0) {
7534         // Each of the extended elements need to be zeroable.
7535         if (!Zeroable[i])
7536           return SDValue();
7537
7538         // We no longer are in the anyext case.
7539         AnyExt = false;
7540         continue;
7541       }
7542
7543       // Each of the base elements needs to be consecutive indices into the
7544       // same input vector.
7545       SDValue V = M < NumElements ? V1 : V2;
7546       M = M % NumElements;
7547       if (!InputV) {
7548         InputV = V;
7549         Offset = M - (i / Scale);
7550       } else if (InputV != V)
7551         return SDValue(); // Flip-flopping inputs.
7552
7553       // Offset must start in the lowest 128-bit lane or at the start of an
7554       // upper lane.
7555       // FIXME: Is it ever worth allowing a negative base offset?
7556       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7557             (Offset % NumEltsPerLane) == 0))
7558         return SDValue();
7559
7560       // If we are offsetting, all referenced entries must come from the same
7561       // lane.
7562       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7563         return SDValue();
7564
7565       if ((M % NumElements) != (Offset + (i / Scale)))
7566         return SDValue(); // Non-consecutive strided elements.
7567       Matches++;
7568     }
7569
7570     // If we fail to find an input, we have a zero-shuffle which should always
7571     // have already been handled.
7572     // FIXME: Maybe handle this here in case during blending we end up with one?
7573     if (!InputV)
7574       return SDValue();
7575
7576     // If we are offsetting, don't extend if we only match a single input, we
7577     // can always do better by using a basic PSHUF or PUNPCK.
7578     if (Offset != 0 && Matches < 2)
7579       return SDValue();
7580
7581     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7582         DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7583   };
7584
7585   // The widest scale possible for extending is to a 64-bit integer.
7586   assert(Bits % 64 == 0 &&
7587          "The number of bits in a vector must be divisible by 64 on x86!");
7588   int NumExtElements = Bits / 64;
7589
7590   // Each iteration, try extending the elements half as much, but into twice as
7591   // many elements.
7592   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7593     assert(NumElements % NumExtElements == 0 &&
7594            "The input vector size must be divisible by the extended size.");
7595     if (SDValue V = Lower(NumElements / NumExtElements))
7596       return V;
7597   }
7598
7599   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7600   if (Bits != 128)
7601     return SDValue();
7602
7603   // Returns one of the source operands if the shuffle can be reduced to a
7604   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7605   auto CanZExtLowHalf = [&]() {
7606     for (int i = NumElements / 2; i != NumElements; ++i)
7607       if (!Zeroable[i])
7608         return SDValue();
7609     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7610       return V1;
7611     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7612       return V2;
7613     return SDValue();
7614   };
7615
7616   if (SDValue V = CanZExtLowHalf()) {
7617     V = DAG.getBitcast(MVT::v2i64, V);
7618     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7619     return DAG.getBitcast(VT, V);
7620   }
7621
7622   // No viable ext lowering found.
7623   return SDValue();
7624 }
7625
7626 /// \brief Try to get a scalar value for a specific element of a vector.
7627 ///
7628 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7629 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7630                                               SelectionDAG &DAG) {
7631   MVT VT = V.getSimpleValueType();
7632   MVT EltVT = VT.getVectorElementType();
7633   while (V.getOpcode() == ISD::BITCAST)
7634     V = V.getOperand(0);
7635   // If the bitcasts shift the element size, we can't extract an equivalent
7636   // element from it.
7637   MVT NewVT = V.getSimpleValueType();
7638   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7639     return SDValue();
7640
7641   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7642       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7643     // Ensure the scalar operand is the same size as the destination.
7644     // FIXME: Add support for scalar truncation where possible.
7645     SDValue S = V.getOperand(Idx);
7646     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7647       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7648   }
7649
7650   return SDValue();
7651 }
7652
7653 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7654 ///
7655 /// This is particularly important because the set of instructions varies
7656 /// significantly based on whether the operand is a load or not.
7657 static bool isShuffleFoldableLoad(SDValue V) {
7658   while (V.getOpcode() == ISD::BITCAST)
7659     V = V.getOperand(0);
7660
7661   return ISD::isNON_EXTLoad(V.getNode());
7662 }
7663
7664 /// \brief Try to lower insertion of a single element into a zero vector.
7665 ///
7666 /// This is a common pattern that we have especially efficient patterns to lower
7667 /// across all subtarget feature sets.
7668 static SDValue lowerVectorShuffleAsElementInsertion(
7669     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7670     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7671   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7672   MVT ExtVT = VT;
7673   MVT EltVT = VT.getVectorElementType();
7674
7675   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7676                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7677                 Mask.begin();
7678   bool IsV1Zeroable = true;
7679   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7680     if (i != V2Index && !Zeroable[i]) {
7681       IsV1Zeroable = false;
7682       break;
7683     }
7684
7685   // Check for a single input from a SCALAR_TO_VECTOR node.
7686   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7687   // all the smarts here sunk into that routine. However, the current
7688   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7689   // vector shuffle lowering is dead.
7690   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7691                                                DAG);
7692   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7693     // We need to zext the scalar if it is smaller than an i32.
7694     V2S = DAG.getBitcast(EltVT, V2S);
7695     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7696       // Using zext to expand a narrow element won't work for non-zero
7697       // insertions.
7698       if (!IsV1Zeroable)
7699         return SDValue();
7700
7701       // Zero-extend directly to i32.
7702       ExtVT = MVT::v4i32;
7703       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7704     }
7705     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7706   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7707              EltVT == MVT::i16) {
7708     // Either not inserting from the low element of the input or the input
7709     // element size is too small to use VZEXT_MOVL to clear the high bits.
7710     return SDValue();
7711   }
7712
7713   if (!IsV1Zeroable) {
7714     // If V1 can't be treated as a zero vector we have fewer options to lower
7715     // this. We can't support integer vectors or non-zero targets cheaply, and
7716     // the V1 elements can't be permuted in any way.
7717     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7718     if (!VT.isFloatingPoint() || V2Index != 0)
7719       return SDValue();
7720     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7721     V1Mask[V2Index] = -1;
7722     if (!isNoopShuffleMask(V1Mask))
7723       return SDValue();
7724     // This is essentially a special case blend operation, but if we have
7725     // general purpose blend operations, they are always faster. Bail and let
7726     // the rest of the lowering handle these as blends.
7727     if (Subtarget->hasSSE41())
7728       return SDValue();
7729
7730     // Otherwise, use MOVSD or MOVSS.
7731     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7732            "Only two types of floating point element types to handle!");
7733     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7734                        ExtVT, V1, V2);
7735   }
7736
7737   // This lowering only works for the low element with floating point vectors.
7738   if (VT.isFloatingPoint() && V2Index != 0)
7739     return SDValue();
7740
7741   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7742   if (ExtVT != VT)
7743     V2 = DAG.getBitcast(VT, V2);
7744
7745   if (V2Index != 0) {
7746     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7747     // the desired position. Otherwise it is more efficient to do a vector
7748     // shift left. We know that we can do a vector shift left because all
7749     // the inputs are zero.
7750     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7751       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7752       V2Shuffle[V2Index] = 0;
7753       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7754     } else {
7755       V2 = DAG.getBitcast(MVT::v2i64, V2);
7756       V2 = DAG.getNode(
7757           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7758           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7759                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7760                               DAG.getDataLayout(), VT)));
7761       V2 = DAG.getBitcast(VT, V2);
7762     }
7763   }
7764   return V2;
7765 }
7766
7767 /// \brief Try to lower broadcast of a single element.
7768 ///
7769 /// For convenience, this code also bundles all of the subtarget feature set
7770 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7771 /// a convenient way to factor it out.
7772 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7773                                              ArrayRef<int> Mask,
7774                                              const X86Subtarget *Subtarget,
7775                                              SelectionDAG &DAG) {
7776   if (!Subtarget->hasAVX())
7777     return SDValue();
7778   if (VT.isInteger() && !Subtarget->hasAVX2())
7779     return SDValue();
7780
7781   // Check that the mask is a broadcast.
7782   int BroadcastIdx = -1;
7783   for (int M : Mask)
7784     if (M >= 0 && BroadcastIdx == -1)
7785       BroadcastIdx = M;
7786     else if (M >= 0 && M != BroadcastIdx)
7787       return SDValue();
7788
7789   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7790                                             "a sorted mask where the broadcast "
7791                                             "comes from V1.");
7792
7793   // Go up the chain of (vector) values to find a scalar load that we can
7794   // combine with the broadcast.
7795   for (;;) {
7796     switch (V.getOpcode()) {
7797     case ISD::CONCAT_VECTORS: {
7798       int OperandSize = Mask.size() / V.getNumOperands();
7799       V = V.getOperand(BroadcastIdx / OperandSize);
7800       BroadcastIdx %= OperandSize;
7801       continue;
7802     }
7803
7804     case ISD::INSERT_SUBVECTOR: {
7805       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7806       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7807       if (!ConstantIdx)
7808         break;
7809
7810       int BeginIdx = (int)ConstantIdx->getZExtValue();
7811       int EndIdx =
7812           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7813       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7814         BroadcastIdx -= BeginIdx;
7815         V = VInner;
7816       } else {
7817         V = VOuter;
7818       }
7819       continue;
7820     }
7821     }
7822     break;
7823   }
7824
7825   // Check if this is a broadcast of a scalar. We special case lowering
7826   // for scalars so that we can more effectively fold with loads.
7827   // First, look through bitcast: if the original value has a larger element
7828   // type than the shuffle, the broadcast element is in essence truncated.
7829   // Make that explicit to ease folding.
7830   if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7831     EVT EltVT = VT.getVectorElementType();
7832     SDValue V0 = V.getOperand(0);
7833     EVT V0VT = V0.getValueType();
7834
7835     if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7836         ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7837          (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7838       V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7839       BroadcastIdx = 0;
7840     }
7841   }
7842
7843   // Also check the simpler case, where we can directly reuse the scalar.
7844   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7845       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7846     V = V.getOperand(BroadcastIdx);
7847
7848     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7849     // Only AVX2 has register broadcasts.
7850     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7851       return SDValue();
7852   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7853     // We can't broadcast from a vector register without AVX2, and we can only
7854     // broadcast from the zero-element of a vector register.
7855     return SDValue();
7856   }
7857
7858   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7859 }
7860
7861 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7862 // INSERTPS when the V1 elements are already in the correct locations
7863 // because otherwise we can just always use two SHUFPS instructions which
7864 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7865 // perform INSERTPS if a single V1 element is out of place and all V2
7866 // elements are zeroable.
7867 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7868                                             ArrayRef<int> Mask,
7869                                             SelectionDAG &DAG) {
7870   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7871   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7872   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7873   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7874
7875   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7876
7877   unsigned ZMask = 0;
7878   int V1DstIndex = -1;
7879   int V2DstIndex = -1;
7880   bool V1UsedInPlace = false;
7881
7882   for (int i = 0; i < 4; ++i) {
7883     // Synthesize a zero mask from the zeroable elements (includes undefs).
7884     if (Zeroable[i]) {
7885       ZMask |= 1 << i;
7886       continue;
7887     }
7888
7889     // Flag if we use any V1 inputs in place.
7890     if (i == Mask[i]) {
7891       V1UsedInPlace = true;
7892       continue;
7893     }
7894
7895     // We can only insert a single non-zeroable element.
7896     if (V1DstIndex != -1 || V2DstIndex != -1)
7897       return SDValue();
7898
7899     if (Mask[i] < 4) {
7900       // V1 input out of place for insertion.
7901       V1DstIndex = i;
7902     } else {
7903       // V2 input for insertion.
7904       V2DstIndex = i;
7905     }
7906   }
7907
7908   // Don't bother if we have no (non-zeroable) element for insertion.
7909   if (V1DstIndex == -1 && V2DstIndex == -1)
7910     return SDValue();
7911
7912   // Determine element insertion src/dst indices. The src index is from the
7913   // start of the inserted vector, not the start of the concatenated vector.
7914   unsigned V2SrcIndex = 0;
7915   if (V1DstIndex != -1) {
7916     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7917     // and don't use the original V2 at all.
7918     V2SrcIndex = Mask[V1DstIndex];
7919     V2DstIndex = V1DstIndex;
7920     V2 = V1;
7921   } else {
7922     V2SrcIndex = Mask[V2DstIndex] - 4;
7923   }
7924
7925   // If no V1 inputs are used in place, then the result is created only from
7926   // the zero mask and the V2 insertion - so remove V1 dependency.
7927   if (!V1UsedInPlace)
7928     V1 = DAG.getUNDEF(MVT::v4f32);
7929
7930   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7931   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7932
7933   // Insert the V2 element into the desired position.
7934   SDLoc DL(Op);
7935   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7936                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7937 }
7938
7939 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7940 /// UNPCK instruction.
7941 ///
7942 /// This specifically targets cases where we end up with alternating between
7943 /// the two inputs, and so can permute them into something that feeds a single
7944 /// UNPCK instruction. Note that this routine only targets integer vectors
7945 /// because for floating point vectors we have a generalized SHUFPS lowering
7946 /// strategy that handles everything that doesn't *exactly* match an unpack,
7947 /// making this clever lowering unnecessary.
7948 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
7949                                                     SDValue V1, SDValue V2,
7950                                                     ArrayRef<int> Mask,
7951                                                     SelectionDAG &DAG) {
7952   assert(!VT.isFloatingPoint() &&
7953          "This routine only supports integer vectors.");
7954   assert(!isSingleInputShuffleMask(Mask) &&
7955          "This routine should only be used when blending two inputs.");
7956   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7957
7958   int Size = Mask.size();
7959
7960   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7961     return M >= 0 && M % Size < Size / 2;
7962   });
7963   int NumHiInputs = std::count_if(
7964       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7965
7966   bool UnpackLo = NumLoInputs >= NumHiInputs;
7967
7968   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7969     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7970     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7971
7972     for (int i = 0; i < Size; ++i) {
7973       if (Mask[i] < 0)
7974         continue;
7975
7976       // Each element of the unpack contains Scale elements from this mask.
7977       int UnpackIdx = i / Scale;
7978
7979       // We only handle the case where V1 feeds the first slots of the unpack.
7980       // We rely on canonicalization to ensure this is the case.
7981       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7982         return SDValue();
7983
7984       // Setup the mask for this input. The indexing is tricky as we have to
7985       // handle the unpack stride.
7986       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7987       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7988           Mask[i] % Size;
7989     }
7990
7991     // If we will have to shuffle both inputs to use the unpack, check whether
7992     // we can just unpack first and shuffle the result. If so, skip this unpack.
7993     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7994         !isNoopShuffleMask(V2Mask))
7995       return SDValue();
7996
7997     // Shuffle the inputs into place.
7998     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7999     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8000
8001     // Cast the inputs to the type we will use to unpack them.
8002     V1 = DAG.getBitcast(UnpackVT, V1);
8003     V2 = DAG.getBitcast(UnpackVT, V2);
8004
8005     // Unpack the inputs and cast the result back to the desired type.
8006     return DAG.getBitcast(
8007         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8008                         UnpackVT, V1, V2));
8009   };
8010
8011   // We try each unpack from the largest to the smallest to try and find one
8012   // that fits this mask.
8013   int OrigNumElements = VT.getVectorNumElements();
8014   int OrigScalarSize = VT.getScalarSizeInBits();
8015   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8016     int Scale = ScalarSize / OrigScalarSize;
8017     int NumElements = OrigNumElements / Scale;
8018     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8019     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8020       return Unpack;
8021   }
8022
8023   // If none of the unpack-rooted lowerings worked (or were profitable) try an
8024   // initial unpack.
8025   if (NumLoInputs == 0 || NumHiInputs == 0) {
8026     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8027            "We have to have *some* inputs!");
8028     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8029
8030     // FIXME: We could consider the total complexity of the permute of each
8031     // possible unpacking. Or at the least we should consider how many
8032     // half-crossings are created.
8033     // FIXME: We could consider commuting the unpacks.
8034
8035     SmallVector<int, 32> PermMask;
8036     PermMask.assign(Size, -1);
8037     for (int i = 0; i < Size; ++i) {
8038       if (Mask[i] < 0)
8039         continue;
8040
8041       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8042
8043       PermMask[i] =
8044           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8045     }
8046     return DAG.getVectorShuffle(
8047         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8048                             DL, VT, V1, V2),
8049         DAG.getUNDEF(VT), PermMask);
8050   }
8051
8052   return SDValue();
8053 }
8054
8055 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8056 ///
8057 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8058 /// support for floating point shuffles but not integer shuffles. These
8059 /// instructions will incur a domain crossing penalty on some chips though so
8060 /// it is better to avoid lowering through this for integer vectors where
8061 /// possible.
8062 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8063                                        const X86Subtarget *Subtarget,
8064                                        SelectionDAG &DAG) {
8065   SDLoc DL(Op);
8066   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8067   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8068   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8069   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8070   ArrayRef<int> Mask = SVOp->getMask();
8071   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8072
8073   if (isSingleInputShuffleMask(Mask)) {
8074     // Use low duplicate instructions for masks that match their pattern.
8075     if (Subtarget->hasSSE3())
8076       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8077         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8078
8079     // Straight shuffle of a single input vector. Simulate this by using the
8080     // single input as both of the "inputs" to this instruction..
8081     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8082
8083     if (Subtarget->hasAVX()) {
8084       // If we have AVX, we can use VPERMILPS which will allow folding a load
8085       // into the shuffle.
8086       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8087                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8088     }
8089
8090     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8091                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8092   }
8093   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8094   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8095
8096   // If we have a single input, insert that into V1 if we can do so cheaply.
8097   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8098     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8099             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8100       return Insertion;
8101     // Try inverting the insertion since for v2 masks it is easy to do and we
8102     // can't reliably sort the mask one way or the other.
8103     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8104                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8105     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8106             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8107       return Insertion;
8108   }
8109
8110   // Try to use one of the special instruction patterns to handle two common
8111   // blend patterns if a zero-blend above didn't work.
8112   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8113       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8114     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8115       // We can either use a special instruction to load over the low double or
8116       // to move just the low double.
8117       return DAG.getNode(
8118           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8119           DL, MVT::v2f64, V2,
8120           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8121
8122   if (Subtarget->hasSSE41())
8123     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8124                                                   Subtarget, DAG))
8125       return Blend;
8126
8127   // Use dedicated unpack instructions for masks that match their pattern.
8128   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8129     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
8130   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8131     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
8132
8133   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8134   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8135                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8136 }
8137
8138 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8139 ///
8140 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8141 /// the integer unit to minimize domain crossing penalties. However, for blends
8142 /// it falls back to the floating point shuffle operation with appropriate bit
8143 /// casting.
8144 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8145                                        const X86Subtarget *Subtarget,
8146                                        SelectionDAG &DAG) {
8147   SDLoc DL(Op);
8148   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8149   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8150   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8151   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8152   ArrayRef<int> Mask = SVOp->getMask();
8153   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8154
8155   if (isSingleInputShuffleMask(Mask)) {
8156     // Check for being able to broadcast a single element.
8157     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8158                                                           Mask, Subtarget, DAG))
8159       return Broadcast;
8160
8161     // Straight shuffle of a single input vector. For everything from SSE2
8162     // onward this has a single fast instruction with no scary immediates.
8163     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8164     V1 = DAG.getBitcast(MVT::v4i32, V1);
8165     int WidenedMask[4] = {
8166         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8167         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8168     return DAG.getBitcast(
8169         MVT::v2i64,
8170         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8171                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8172   }
8173   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8174   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8175   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8176   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8177
8178   // If we have a blend of two PACKUS operations an the blend aligns with the
8179   // low and half halves, we can just merge the PACKUS operations. This is
8180   // particularly important as it lets us merge shuffles that this routine itself
8181   // creates.
8182   auto GetPackNode = [](SDValue V) {
8183     while (V.getOpcode() == ISD::BITCAST)
8184       V = V.getOperand(0);
8185
8186     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8187   };
8188   if (SDValue V1Pack = GetPackNode(V1))
8189     if (SDValue V2Pack = GetPackNode(V2))
8190       return DAG.getBitcast(MVT::v2i64,
8191                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8192                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8193                                                      : V1Pack.getOperand(1),
8194                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8195                                                      : V2Pack.getOperand(1)));
8196
8197   // Try to use shift instructions.
8198   if (SDValue Shift =
8199           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8200     return Shift;
8201
8202   // When loading a scalar and then shuffling it into a vector we can often do
8203   // the insertion cheaply.
8204   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8205           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8206     return Insertion;
8207   // Try inverting the insertion since for v2 masks it is easy to do and we
8208   // can't reliably sort the mask one way or the other.
8209   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8210   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8211           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8212     return Insertion;
8213
8214   // We have different paths for blend lowering, but they all must use the
8215   // *exact* same predicate.
8216   bool IsBlendSupported = Subtarget->hasSSE41();
8217   if (IsBlendSupported)
8218     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8219                                                   Subtarget, DAG))
8220       return Blend;
8221
8222   // Use dedicated unpack instructions for masks that match their pattern.
8223   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8224     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8225   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8226     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8227
8228   // Try to use byte rotation instructions.
8229   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8230   if (Subtarget->hasSSSE3())
8231     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8232             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8233       return Rotate;
8234
8235   // If we have direct support for blends, we should lower by decomposing into
8236   // a permute. That will be faster than the domain cross.
8237   if (IsBlendSupported)
8238     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8239                                                       Mask, DAG);
8240
8241   // We implement this with SHUFPD which is pretty lame because it will likely
8242   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8243   // However, all the alternatives are still more cycles and newer chips don't
8244   // have this problem. It would be really nice if x86 had better shuffles here.
8245   V1 = DAG.getBitcast(MVT::v2f64, V1);
8246   V2 = DAG.getBitcast(MVT::v2f64, V2);
8247   return DAG.getBitcast(MVT::v2i64,
8248                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8249 }
8250
8251 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8252 ///
8253 /// This is used to disable more specialized lowerings when the shufps lowering
8254 /// will happen to be efficient.
8255 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8256   // This routine only handles 128-bit shufps.
8257   assert(Mask.size() == 4 && "Unsupported mask size!");
8258
8259   // To lower with a single SHUFPS we need to have the low half and high half
8260   // each requiring a single input.
8261   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8262     return false;
8263   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8264     return false;
8265
8266   return true;
8267 }
8268
8269 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8270 ///
8271 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8272 /// It makes no assumptions about whether this is the *best* lowering, it simply
8273 /// uses it.
8274 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8275                                             ArrayRef<int> Mask, SDValue V1,
8276                                             SDValue V2, SelectionDAG &DAG) {
8277   SDValue LowV = V1, HighV = V2;
8278   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8279
8280   int NumV2Elements =
8281       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8282
8283   if (NumV2Elements == 1) {
8284     int V2Index =
8285         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8286         Mask.begin();
8287
8288     // Compute the index adjacent to V2Index and in the same half by toggling
8289     // the low bit.
8290     int V2AdjIndex = V2Index ^ 1;
8291
8292     if (Mask[V2AdjIndex] == -1) {
8293       // Handles all the cases where we have a single V2 element and an undef.
8294       // This will only ever happen in the high lanes because we commute the
8295       // vector otherwise.
8296       if (V2Index < 2)
8297         std::swap(LowV, HighV);
8298       NewMask[V2Index] -= 4;
8299     } else {
8300       // Handle the case where the V2 element ends up adjacent to a V1 element.
8301       // To make this work, blend them together as the first step.
8302       int V1Index = V2AdjIndex;
8303       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8304       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8305                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8306
8307       // Now proceed to reconstruct the final blend as we have the necessary
8308       // high or low half formed.
8309       if (V2Index < 2) {
8310         LowV = V2;
8311         HighV = V1;
8312       } else {
8313         HighV = V2;
8314       }
8315       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8316       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8317     }
8318   } else if (NumV2Elements == 2) {
8319     if (Mask[0] < 4 && Mask[1] < 4) {
8320       // Handle the easy case where we have V1 in the low lanes and V2 in the
8321       // high lanes.
8322       NewMask[2] -= 4;
8323       NewMask[3] -= 4;
8324     } else if (Mask[2] < 4 && Mask[3] < 4) {
8325       // We also handle the reversed case because this utility may get called
8326       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8327       // arrange things in the right direction.
8328       NewMask[0] -= 4;
8329       NewMask[1] -= 4;
8330       HighV = V1;
8331       LowV = V2;
8332     } else {
8333       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8334       // trying to place elements directly, just blend them and set up the final
8335       // shuffle to place them.
8336
8337       // The first two blend mask elements are for V1, the second two are for
8338       // V2.
8339       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8340                           Mask[2] < 4 ? Mask[2] : Mask[3],
8341                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8342                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8343       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8344                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8345
8346       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8347       // a blend.
8348       LowV = HighV = V1;
8349       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8350       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8351       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8352       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8353     }
8354   }
8355   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8356                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8357 }
8358
8359 /// \brief Lower 4-lane 32-bit floating point shuffles.
8360 ///
8361 /// Uses instructions exclusively from the floating point unit to minimize
8362 /// domain crossing penalties, as these are sufficient to implement all v4f32
8363 /// shuffles.
8364 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8365                                        const X86Subtarget *Subtarget,
8366                                        SelectionDAG &DAG) {
8367   SDLoc DL(Op);
8368   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8369   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8370   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8371   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8372   ArrayRef<int> Mask = SVOp->getMask();
8373   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8374
8375   int NumV2Elements =
8376       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8377
8378   if (NumV2Elements == 0) {
8379     // Check for being able to broadcast a single element.
8380     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8381                                                           Mask, Subtarget, DAG))
8382       return Broadcast;
8383
8384     // Use even/odd duplicate instructions for masks that match their pattern.
8385     if (Subtarget->hasSSE3()) {
8386       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8387         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8388       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8389         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8390     }
8391
8392     if (Subtarget->hasAVX()) {
8393       // If we have AVX, we can use VPERMILPS which will allow folding a load
8394       // into the shuffle.
8395       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8396                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8397     }
8398
8399     // Otherwise, use a straight shuffle of a single input vector. We pass the
8400     // input vector to both operands to simulate this with a SHUFPS.
8401     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8402                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8403   }
8404
8405   // There are special ways we can lower some single-element blends. However, we
8406   // have custom ways we can lower more complex single-element blends below that
8407   // we defer to if both this and BLENDPS fail to match, so restrict this to
8408   // when the V2 input is targeting element 0 of the mask -- that is the fast
8409   // case here.
8410   if (NumV2Elements == 1 && Mask[0] >= 4)
8411     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8412                                                          Mask, Subtarget, DAG))
8413       return V;
8414
8415   if (Subtarget->hasSSE41()) {
8416     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8417                                                   Subtarget, DAG))
8418       return Blend;
8419
8420     // Use INSERTPS if we can complete the shuffle efficiently.
8421     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8422       return V;
8423
8424     if (!isSingleSHUFPSMask(Mask))
8425       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8426               DL, MVT::v4f32, V1, V2, Mask, DAG))
8427         return BlendPerm;
8428   }
8429
8430   // Use dedicated unpack instructions for masks that match their pattern.
8431   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8432     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8433   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8434     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8435   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8436     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8437   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8438     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8439
8440   // Otherwise fall back to a SHUFPS lowering strategy.
8441   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8442 }
8443
8444 /// \brief Lower 4-lane i32 vector shuffles.
8445 ///
8446 /// We try to handle these with integer-domain shuffles where we can, but for
8447 /// blends we use the floating point domain blend instructions.
8448 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8449                                        const X86Subtarget *Subtarget,
8450                                        SelectionDAG &DAG) {
8451   SDLoc DL(Op);
8452   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8453   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8454   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8455   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8456   ArrayRef<int> Mask = SVOp->getMask();
8457   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8458
8459   // Whenever we can lower this as a zext, that instruction is strictly faster
8460   // than any alternative. It also allows us to fold memory operands into the
8461   // shuffle in many cases.
8462   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8463                                                          Mask, Subtarget, DAG))
8464     return ZExt;
8465
8466   int NumV2Elements =
8467       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8468
8469   if (NumV2Elements == 0) {
8470     // Check for being able to broadcast a single element.
8471     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8472                                                           Mask, Subtarget, DAG))
8473       return Broadcast;
8474
8475     // Straight shuffle of a single input vector. For everything from SSE2
8476     // onward this has a single fast instruction with no scary immediates.
8477     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8478     // but we aren't actually going to use the UNPCK instruction because doing
8479     // so prevents folding a load into this instruction or making a copy.
8480     const int UnpackLoMask[] = {0, 0, 1, 1};
8481     const int UnpackHiMask[] = {2, 2, 3, 3};
8482     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8483       Mask = UnpackLoMask;
8484     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8485       Mask = UnpackHiMask;
8486
8487     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8488                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8489   }
8490
8491   // Try to use shift instructions.
8492   if (SDValue Shift =
8493           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8494     return Shift;
8495
8496   // There are special ways we can lower some single-element blends.
8497   if (NumV2Elements == 1)
8498     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8499                                                          Mask, Subtarget, DAG))
8500       return V;
8501
8502   // We have different paths for blend lowering, but they all must use the
8503   // *exact* same predicate.
8504   bool IsBlendSupported = Subtarget->hasSSE41();
8505   if (IsBlendSupported)
8506     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8507                                                   Subtarget, DAG))
8508       return Blend;
8509
8510   if (SDValue Masked =
8511           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8512     return Masked;
8513
8514   // Use dedicated unpack instructions for masks that match their pattern.
8515   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8516     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8517   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8518     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8519   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8520     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8521   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8522     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8523
8524   // Try to use byte rotation instructions.
8525   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8526   if (Subtarget->hasSSSE3())
8527     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8528             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8529       return Rotate;
8530
8531   // If we have direct support for blends, we should lower by decomposing into
8532   // a permute. That will be faster than the domain cross.
8533   if (IsBlendSupported)
8534     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8535                                                       Mask, DAG);
8536
8537   // Try to lower by permuting the inputs into an unpack instruction.
8538   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8539                                                             V2, Mask, DAG))
8540     return Unpack;
8541
8542   // We implement this with SHUFPS because it can blend from two vectors.
8543   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8544   // up the inputs, bypassing domain shift penalties that we would encur if we
8545   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8546   // relevant.
8547   return DAG.getBitcast(
8548       MVT::v4i32,
8549       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8550                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8551 }
8552
8553 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8554 /// shuffle lowering, and the most complex part.
8555 ///
8556 /// The lowering strategy is to try to form pairs of input lanes which are
8557 /// targeted at the same half of the final vector, and then use a dword shuffle
8558 /// to place them onto the right half, and finally unpack the paired lanes into
8559 /// their final position.
8560 ///
8561 /// The exact breakdown of how to form these dword pairs and align them on the
8562 /// correct sides is really tricky. See the comments within the function for
8563 /// more of the details.
8564 ///
8565 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8566 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8567 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8568 /// vector, form the analogous 128-bit 8-element Mask.
8569 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8570     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8571     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8572   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8573   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8574
8575   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8576   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8577   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8578
8579   SmallVector<int, 4> LoInputs;
8580   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8581                [](int M) { return M >= 0; });
8582   std::sort(LoInputs.begin(), LoInputs.end());
8583   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8584   SmallVector<int, 4> HiInputs;
8585   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8586                [](int M) { return M >= 0; });
8587   std::sort(HiInputs.begin(), HiInputs.end());
8588   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8589   int NumLToL =
8590       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8591   int NumHToL = LoInputs.size() - NumLToL;
8592   int NumLToH =
8593       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8594   int NumHToH = HiInputs.size() - NumLToH;
8595   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8596   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8597   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8598   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8599
8600   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8601   // such inputs we can swap two of the dwords across the half mark and end up
8602   // with <=2 inputs to each half in each half. Once there, we can fall through
8603   // to the generic code below. For example:
8604   //
8605   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8606   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8607   //
8608   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8609   // and an existing 2-into-2 on the other half. In this case we may have to
8610   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8611   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8612   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8613   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8614   // half than the one we target for fixing) will be fixed when we re-enter this
8615   // path. We will also combine away any sequence of PSHUFD instructions that
8616   // result into a single instruction. Here is an example of the tricky case:
8617   //
8618   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8619   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8620   //
8621   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8622   //
8623   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8624   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8625   //
8626   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8627   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8628   //
8629   // The result is fine to be handled by the generic logic.
8630   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8631                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8632                           int AOffset, int BOffset) {
8633     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8634            "Must call this with A having 3 or 1 inputs from the A half.");
8635     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8636            "Must call this with B having 1 or 3 inputs from the B half.");
8637     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8638            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8639
8640     bool ThreeAInputs = AToAInputs.size() == 3;
8641
8642     // Compute the index of dword with only one word among the three inputs in
8643     // a half by taking the sum of the half with three inputs and subtracting
8644     // the sum of the actual three inputs. The difference is the remaining
8645     // slot.
8646     int ADWord, BDWord;
8647     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8648     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8649     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8650     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8651     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8652     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8653     int TripleNonInputIdx =
8654         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8655     TripleDWord = TripleNonInputIdx / 2;
8656
8657     // We use xor with one to compute the adjacent DWord to whichever one the
8658     // OneInput is in.
8659     OneInputDWord = (OneInput / 2) ^ 1;
8660
8661     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8662     // and BToA inputs. If there is also such a problem with the BToB and AToB
8663     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8664     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8665     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8666     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8667       // Compute how many inputs will be flipped by swapping these DWords. We
8668       // need
8669       // to balance this to ensure we don't form a 3-1 shuffle in the other
8670       // half.
8671       int NumFlippedAToBInputs =
8672           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8673           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8674       int NumFlippedBToBInputs =
8675           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8676           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8677       if ((NumFlippedAToBInputs == 1 &&
8678            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8679           (NumFlippedBToBInputs == 1 &&
8680            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8681         // We choose whether to fix the A half or B half based on whether that
8682         // half has zero flipped inputs. At zero, we may not be able to fix it
8683         // with that half. We also bias towards fixing the B half because that
8684         // will more commonly be the high half, and we have to bias one way.
8685         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8686                                                        ArrayRef<int> Inputs) {
8687           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8688           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8689                                          PinnedIdx ^ 1) != Inputs.end();
8690           // Determine whether the free index is in the flipped dword or the
8691           // unflipped dword based on where the pinned index is. We use this bit
8692           // in an xor to conditionally select the adjacent dword.
8693           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8694           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8695                                              FixFreeIdx) != Inputs.end();
8696           if (IsFixIdxInput == IsFixFreeIdxInput)
8697             FixFreeIdx += 1;
8698           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8699                                         FixFreeIdx) != Inputs.end();
8700           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8701                  "We need to be changing the number of flipped inputs!");
8702           int PSHUFHalfMask[] = {0, 1, 2, 3};
8703           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8704           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8705                           MVT::v8i16, V,
8706                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8707
8708           for (int &M : Mask)
8709             if (M != -1 && M == FixIdx)
8710               M = FixFreeIdx;
8711             else if (M != -1 && M == FixFreeIdx)
8712               M = FixIdx;
8713         };
8714         if (NumFlippedBToBInputs != 0) {
8715           int BPinnedIdx =
8716               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8717           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8718         } else {
8719           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8720           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8721           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8722         }
8723       }
8724     }
8725
8726     int PSHUFDMask[] = {0, 1, 2, 3};
8727     PSHUFDMask[ADWord] = BDWord;
8728     PSHUFDMask[BDWord] = ADWord;
8729     V = DAG.getBitcast(
8730         VT,
8731         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8732                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8733
8734     // Adjust the mask to match the new locations of A and B.
8735     for (int &M : Mask)
8736       if (M != -1 && M/2 == ADWord)
8737         M = 2 * BDWord + M % 2;
8738       else if (M != -1 && M/2 == BDWord)
8739         M = 2 * ADWord + M % 2;
8740
8741     // Recurse back into this routine to re-compute state now that this isn't
8742     // a 3 and 1 problem.
8743     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8744                                                      DAG);
8745   };
8746   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8747     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8748   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8749     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8750
8751   // At this point there are at most two inputs to the low and high halves from
8752   // each half. That means the inputs can always be grouped into dwords and
8753   // those dwords can then be moved to the correct half with a dword shuffle.
8754   // We use at most one low and one high word shuffle to collect these paired
8755   // inputs into dwords, and finally a dword shuffle to place them.
8756   int PSHUFLMask[4] = {-1, -1, -1, -1};
8757   int PSHUFHMask[4] = {-1, -1, -1, -1};
8758   int PSHUFDMask[4] = {-1, -1, -1, -1};
8759
8760   // First fix the masks for all the inputs that are staying in their
8761   // original halves. This will then dictate the targets of the cross-half
8762   // shuffles.
8763   auto fixInPlaceInputs =
8764       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8765                     MutableArrayRef<int> SourceHalfMask,
8766                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8767     if (InPlaceInputs.empty())
8768       return;
8769     if (InPlaceInputs.size() == 1) {
8770       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8771           InPlaceInputs[0] - HalfOffset;
8772       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8773       return;
8774     }
8775     if (IncomingInputs.empty()) {
8776       // Just fix all of the in place inputs.
8777       for (int Input : InPlaceInputs) {
8778         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8779         PSHUFDMask[Input / 2] = Input / 2;
8780       }
8781       return;
8782     }
8783
8784     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8785     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8786         InPlaceInputs[0] - HalfOffset;
8787     // Put the second input next to the first so that they are packed into
8788     // a dword. We find the adjacent index by toggling the low bit.
8789     int AdjIndex = InPlaceInputs[0] ^ 1;
8790     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8791     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8792     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8793   };
8794   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8795   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8796
8797   // Now gather the cross-half inputs and place them into a free dword of
8798   // their target half.
8799   // FIXME: This operation could almost certainly be simplified dramatically to
8800   // look more like the 3-1 fixing operation.
8801   auto moveInputsToRightHalf = [&PSHUFDMask](
8802       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8803       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8804       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8805       int DestOffset) {
8806     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8807       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8808     };
8809     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8810                                                int Word) {
8811       int LowWord = Word & ~1;
8812       int HighWord = Word | 1;
8813       return isWordClobbered(SourceHalfMask, LowWord) ||
8814              isWordClobbered(SourceHalfMask, HighWord);
8815     };
8816
8817     if (IncomingInputs.empty())
8818       return;
8819
8820     if (ExistingInputs.empty()) {
8821       // Map any dwords with inputs from them into the right half.
8822       for (int Input : IncomingInputs) {
8823         // If the source half mask maps over the inputs, turn those into
8824         // swaps and use the swapped lane.
8825         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8826           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8827             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8828                 Input - SourceOffset;
8829             // We have to swap the uses in our half mask in one sweep.
8830             for (int &M : HalfMask)
8831               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8832                 M = Input;
8833               else if (M == Input)
8834                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8835           } else {
8836             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8837                        Input - SourceOffset &&
8838                    "Previous placement doesn't match!");
8839           }
8840           // Note that this correctly re-maps both when we do a swap and when
8841           // we observe the other side of the swap above. We rely on that to
8842           // avoid swapping the members of the input list directly.
8843           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8844         }
8845
8846         // Map the input's dword into the correct half.
8847         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8848           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8849         else
8850           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8851                      Input / 2 &&
8852                  "Previous placement doesn't match!");
8853       }
8854
8855       // And just directly shift any other-half mask elements to be same-half
8856       // as we will have mirrored the dword containing the element into the
8857       // same position within that half.
8858       for (int &M : HalfMask)
8859         if (M >= SourceOffset && M < SourceOffset + 4) {
8860           M = M - SourceOffset + DestOffset;
8861           assert(M >= 0 && "This should never wrap below zero!");
8862         }
8863       return;
8864     }
8865
8866     // Ensure we have the input in a viable dword of its current half. This
8867     // is particularly tricky because the original position may be clobbered
8868     // by inputs being moved and *staying* in that half.
8869     if (IncomingInputs.size() == 1) {
8870       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8871         int InputFixed = std::find(std::begin(SourceHalfMask),
8872                                    std::end(SourceHalfMask), -1) -
8873                          std::begin(SourceHalfMask) + SourceOffset;
8874         SourceHalfMask[InputFixed - SourceOffset] =
8875             IncomingInputs[0] - SourceOffset;
8876         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8877                      InputFixed);
8878         IncomingInputs[0] = InputFixed;
8879       }
8880     } else if (IncomingInputs.size() == 2) {
8881       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8882           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8883         // We have two non-adjacent or clobbered inputs we need to extract from
8884         // the source half. To do this, we need to map them into some adjacent
8885         // dword slot in the source mask.
8886         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8887                               IncomingInputs[1] - SourceOffset};
8888
8889         // If there is a free slot in the source half mask adjacent to one of
8890         // the inputs, place the other input in it. We use (Index XOR 1) to
8891         // compute an adjacent index.
8892         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8893             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8894           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8895           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8896           InputsFixed[1] = InputsFixed[0] ^ 1;
8897         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8898                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8899           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8900           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8901           InputsFixed[0] = InputsFixed[1] ^ 1;
8902         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8903                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8904           // The two inputs are in the same DWord but it is clobbered and the
8905           // adjacent DWord isn't used at all. Move both inputs to the free
8906           // slot.
8907           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8908           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8909           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8910           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8911         } else {
8912           // The only way we hit this point is if there is no clobbering
8913           // (because there are no off-half inputs to this half) and there is no
8914           // free slot adjacent to one of the inputs. In this case, we have to
8915           // swap an input with a non-input.
8916           for (int i = 0; i < 4; ++i)
8917             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8918                    "We can't handle any clobbers here!");
8919           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8920                  "Cannot have adjacent inputs here!");
8921
8922           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8923           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8924
8925           // We also have to update the final source mask in this case because
8926           // it may need to undo the above swap.
8927           for (int &M : FinalSourceHalfMask)
8928             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8929               M = InputsFixed[1] + SourceOffset;
8930             else if (M == InputsFixed[1] + SourceOffset)
8931               M = (InputsFixed[0] ^ 1) + SourceOffset;
8932
8933           InputsFixed[1] = InputsFixed[0] ^ 1;
8934         }
8935
8936         // Point everything at the fixed inputs.
8937         for (int &M : HalfMask)
8938           if (M == IncomingInputs[0])
8939             M = InputsFixed[0] + SourceOffset;
8940           else if (M == IncomingInputs[1])
8941             M = InputsFixed[1] + SourceOffset;
8942
8943         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8944         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8945       }
8946     } else {
8947       llvm_unreachable("Unhandled input size!");
8948     }
8949
8950     // Now hoist the DWord down to the right half.
8951     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8952     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8953     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8954     for (int &M : HalfMask)
8955       for (int Input : IncomingInputs)
8956         if (M == Input)
8957           M = FreeDWord * 2 + Input % 2;
8958   };
8959   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8960                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8961   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8962                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8963
8964   // Now enact all the shuffles we've computed to move the inputs into their
8965   // target half.
8966   if (!isNoopShuffleMask(PSHUFLMask))
8967     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8968                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8969   if (!isNoopShuffleMask(PSHUFHMask))
8970     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8971                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8972   if (!isNoopShuffleMask(PSHUFDMask))
8973     V = DAG.getBitcast(
8974         VT,
8975         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8976                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8977
8978   // At this point, each half should contain all its inputs, and we can then
8979   // just shuffle them into their final position.
8980   assert(std::count_if(LoMask.begin(), LoMask.end(),
8981                        [](int M) { return M >= 4; }) == 0 &&
8982          "Failed to lift all the high half inputs to the low mask!");
8983   assert(std::count_if(HiMask.begin(), HiMask.end(),
8984                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8985          "Failed to lift all the low half inputs to the high mask!");
8986
8987   // Do a half shuffle for the low mask.
8988   if (!isNoopShuffleMask(LoMask))
8989     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8990                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8991
8992   // Do a half shuffle with the high mask after shifting its values down.
8993   for (int &M : HiMask)
8994     if (M >= 0)
8995       M -= 4;
8996   if (!isNoopShuffleMask(HiMask))
8997     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8998                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8999
9000   return V;
9001 }
9002
9003 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9004 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9005                                           SDValue V2, ArrayRef<int> Mask,
9006                                           SelectionDAG &DAG, bool &V1InUse,
9007                                           bool &V2InUse) {
9008   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9009   SDValue V1Mask[16];
9010   SDValue V2Mask[16];
9011   V1InUse = false;
9012   V2InUse = false;
9013
9014   int Size = Mask.size();
9015   int Scale = 16 / Size;
9016   for (int i = 0; i < 16; ++i) {
9017     if (Mask[i / Scale] == -1) {
9018       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9019     } else {
9020       const int ZeroMask = 0x80;
9021       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9022                                           : ZeroMask;
9023       int V2Idx = Mask[i / Scale] < Size
9024                       ? ZeroMask
9025                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
9026       if (Zeroable[i / Scale])
9027         V1Idx = V2Idx = ZeroMask;
9028       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9029       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9030       V1InUse |= (ZeroMask != V1Idx);
9031       V2InUse |= (ZeroMask != V2Idx);
9032     }
9033   }
9034
9035   if (V1InUse)
9036     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9037                      DAG.getBitcast(MVT::v16i8, V1),
9038                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9039   if (V2InUse)
9040     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9041                      DAG.getBitcast(MVT::v16i8, V2),
9042                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9043
9044   // If we need shuffled inputs from both, blend the two.
9045   SDValue V;
9046   if (V1InUse && V2InUse)
9047     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9048   else
9049     V = V1InUse ? V1 : V2;
9050
9051   // Cast the result back to the correct type.
9052   return DAG.getBitcast(VT, V);
9053 }
9054
9055 /// \brief Generic lowering of 8-lane i16 shuffles.
9056 ///
9057 /// This handles both single-input shuffles and combined shuffle/blends with
9058 /// two inputs. The single input shuffles are immediately delegated to
9059 /// a dedicated lowering routine.
9060 ///
9061 /// The blends are lowered in one of three fundamental ways. If there are few
9062 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9063 /// of the input is significantly cheaper when lowered as an interleaving of
9064 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9065 /// halves of the inputs separately (making them have relatively few inputs)
9066 /// and then concatenate them.
9067 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9068                                        const X86Subtarget *Subtarget,
9069                                        SelectionDAG &DAG) {
9070   SDLoc DL(Op);
9071   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9072   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9073   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9074   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9075   ArrayRef<int> OrigMask = SVOp->getMask();
9076   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9077                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9078   MutableArrayRef<int> Mask(MaskStorage);
9079
9080   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9081
9082   // Whenever we can lower this as a zext, that instruction is strictly faster
9083   // than any alternative.
9084   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9085           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9086     return ZExt;
9087
9088   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9089   (void)isV1;
9090   auto isV2 = [](int M) { return M >= 8; };
9091
9092   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9093
9094   if (NumV2Inputs == 0) {
9095     // Check for being able to broadcast a single element.
9096     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9097                                                           Mask, Subtarget, DAG))
9098       return Broadcast;
9099
9100     // Try to use shift instructions.
9101     if (SDValue Shift =
9102             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9103       return Shift;
9104
9105     // Use dedicated unpack instructions for masks that match their pattern.
9106     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
9107       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
9108     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
9109       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
9110
9111     // Try to use byte rotation instructions.
9112     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9113                                                         Mask, Subtarget, DAG))
9114       return Rotate;
9115
9116     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9117                                                      Subtarget, DAG);
9118   }
9119
9120   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9121          "All single-input shuffles should be canonicalized to be V1-input "
9122          "shuffles.");
9123
9124   // Try to use shift instructions.
9125   if (SDValue Shift =
9126           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9127     return Shift;
9128
9129   // See if we can use SSE4A Extraction / Insertion.
9130   if (Subtarget->hasSSE4A())
9131     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9132       return V;
9133
9134   // There are special ways we can lower some single-element blends.
9135   if (NumV2Inputs == 1)
9136     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9137                                                          Mask, Subtarget, DAG))
9138       return V;
9139
9140   // We have different paths for blend lowering, but they all must use the
9141   // *exact* same predicate.
9142   bool IsBlendSupported = Subtarget->hasSSE41();
9143   if (IsBlendSupported)
9144     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9145                                                   Subtarget, DAG))
9146       return Blend;
9147
9148   if (SDValue Masked =
9149           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9150     return Masked;
9151
9152   // Use dedicated unpack instructions for masks that match their pattern.
9153   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
9154     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9155   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
9156     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9157
9158   // Try to use byte rotation instructions.
9159   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9160           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9161     return Rotate;
9162
9163   if (SDValue BitBlend =
9164           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9165     return BitBlend;
9166
9167   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9168                                                             V2, Mask, DAG))
9169     return Unpack;
9170
9171   // If we can't directly blend but can use PSHUFB, that will be better as it
9172   // can both shuffle and set up the inefficient blend.
9173   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9174     bool V1InUse, V2InUse;
9175     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9176                                       V1InUse, V2InUse);
9177   }
9178
9179   // We can always bit-blend if we have to so the fallback strategy is to
9180   // decompose into single-input permutes and blends.
9181   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9182                                                       Mask, DAG);
9183 }
9184
9185 /// \brief Check whether a compaction lowering can be done by dropping even
9186 /// elements and compute how many times even elements must be dropped.
9187 ///
9188 /// This handles shuffles which take every Nth element where N is a power of
9189 /// two. Example shuffle masks:
9190 ///
9191 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9192 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9193 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9194 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9195 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9196 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9197 ///
9198 /// Any of these lanes can of course be undef.
9199 ///
9200 /// This routine only supports N <= 3.
9201 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9202 /// for larger N.
9203 ///
9204 /// \returns N above, or the number of times even elements must be dropped if
9205 /// there is such a number. Otherwise returns zero.
9206 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9207   // Figure out whether we're looping over two inputs or just one.
9208   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9209
9210   // The modulus for the shuffle vector entries is based on whether this is
9211   // a single input or not.
9212   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9213   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9214          "We should only be called with masks with a power-of-2 size!");
9215
9216   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9217
9218   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9219   // and 2^3 simultaneously. This is because we may have ambiguity with
9220   // partially undef inputs.
9221   bool ViableForN[3] = {true, true, true};
9222
9223   for (int i = 0, e = Mask.size(); i < e; ++i) {
9224     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9225     // want.
9226     if (Mask[i] == -1)
9227       continue;
9228
9229     bool IsAnyViable = false;
9230     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9231       if (ViableForN[j]) {
9232         uint64_t N = j + 1;
9233
9234         // The shuffle mask must be equal to (i * 2^N) % M.
9235         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9236           IsAnyViable = true;
9237         else
9238           ViableForN[j] = false;
9239       }
9240     // Early exit if we exhaust the possible powers of two.
9241     if (!IsAnyViable)
9242       break;
9243   }
9244
9245   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9246     if (ViableForN[j])
9247       return j + 1;
9248
9249   // Return 0 as there is no viable power of two.
9250   return 0;
9251 }
9252
9253 /// \brief Generic lowering of v16i8 shuffles.
9254 ///
9255 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9256 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9257 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9258 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9259 /// back together.
9260 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9261                                        const X86Subtarget *Subtarget,
9262                                        SelectionDAG &DAG) {
9263   SDLoc DL(Op);
9264   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9265   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9266   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9267   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9268   ArrayRef<int> Mask = SVOp->getMask();
9269   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9270
9271   // Try to use shift instructions.
9272   if (SDValue Shift =
9273           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9274     return Shift;
9275
9276   // Try to use byte rotation instructions.
9277   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9278           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9279     return Rotate;
9280
9281   // Try to use a zext lowering.
9282   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9283           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9284     return ZExt;
9285
9286   // See if we can use SSE4A Extraction / Insertion.
9287   if (Subtarget->hasSSE4A())
9288     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9289       return V;
9290
9291   int NumV2Elements =
9292       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9293
9294   // For single-input shuffles, there are some nicer lowering tricks we can use.
9295   if (NumV2Elements == 0) {
9296     // Check for being able to broadcast a single element.
9297     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9298                                                           Mask, Subtarget, DAG))
9299       return Broadcast;
9300
9301     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9302     // Notably, this handles splat and partial-splat shuffles more efficiently.
9303     // However, it only makes sense if the pre-duplication shuffle simplifies
9304     // things significantly. Currently, this means we need to be able to
9305     // express the pre-duplication shuffle as an i16 shuffle.
9306     //
9307     // FIXME: We should check for other patterns which can be widened into an
9308     // i16 shuffle as well.
9309     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9310       for (int i = 0; i < 16; i += 2)
9311         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9312           return false;
9313
9314       return true;
9315     };
9316     auto tryToWidenViaDuplication = [&]() -> SDValue {
9317       if (!canWidenViaDuplication(Mask))
9318         return SDValue();
9319       SmallVector<int, 4> LoInputs;
9320       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9321                    [](int M) { return M >= 0 && M < 8; });
9322       std::sort(LoInputs.begin(), LoInputs.end());
9323       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9324                      LoInputs.end());
9325       SmallVector<int, 4> HiInputs;
9326       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9327                    [](int M) { return M >= 8; });
9328       std::sort(HiInputs.begin(), HiInputs.end());
9329       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9330                      HiInputs.end());
9331
9332       bool TargetLo = LoInputs.size() >= HiInputs.size();
9333       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9334       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9335
9336       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9337       SmallDenseMap<int, int, 8> LaneMap;
9338       for (int I : InPlaceInputs) {
9339         PreDupI16Shuffle[I/2] = I/2;
9340         LaneMap[I] = I;
9341       }
9342       int j = TargetLo ? 0 : 4, je = j + 4;
9343       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9344         // Check if j is already a shuffle of this input. This happens when
9345         // there are two adjacent bytes after we move the low one.
9346         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9347           // If we haven't yet mapped the input, search for a slot into which
9348           // we can map it.
9349           while (j < je && PreDupI16Shuffle[j] != -1)
9350             ++j;
9351
9352           if (j == je)
9353             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9354             return SDValue();
9355
9356           // Map this input with the i16 shuffle.
9357           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9358         }
9359
9360         // Update the lane map based on the mapping we ended up with.
9361         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9362       }
9363       V1 = DAG.getBitcast(
9364           MVT::v16i8,
9365           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9366                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9367
9368       // Unpack the bytes to form the i16s that will be shuffled into place.
9369       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9370                        MVT::v16i8, V1, V1);
9371
9372       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9373       for (int i = 0; i < 16; ++i)
9374         if (Mask[i] != -1) {
9375           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9376           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9377           if (PostDupI16Shuffle[i / 2] == -1)
9378             PostDupI16Shuffle[i / 2] = MappedMask;
9379           else
9380             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9381                    "Conflicting entrties in the original shuffle!");
9382         }
9383       return DAG.getBitcast(
9384           MVT::v16i8,
9385           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9386                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9387     };
9388     if (SDValue V = tryToWidenViaDuplication())
9389       return V;
9390   }
9391
9392   if (SDValue Masked =
9393           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9394     return Masked;
9395
9396   // Use dedicated unpack instructions for masks that match their pattern.
9397   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9398                                          0, 16, 1, 17, 2, 18, 3, 19,
9399                                          // High half.
9400                                          4, 20, 5, 21, 6, 22, 7, 23}))
9401     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9402   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9403                                          8, 24, 9, 25, 10, 26, 11, 27,
9404                                          // High half.
9405                                          12, 28, 13, 29, 14, 30, 15, 31}))
9406     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9407
9408   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9409   // with PSHUFB. It is important to do this before we attempt to generate any
9410   // blends but after all of the single-input lowerings. If the single input
9411   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9412   // want to preserve that and we can DAG combine any longer sequences into
9413   // a PSHUFB in the end. But once we start blending from multiple inputs,
9414   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9415   // and there are *very* few patterns that would actually be faster than the
9416   // PSHUFB approach because of its ability to zero lanes.
9417   //
9418   // FIXME: The only exceptions to the above are blends which are exact
9419   // interleavings with direct instructions supporting them. We currently don't
9420   // handle those well here.
9421   if (Subtarget->hasSSSE3()) {
9422     bool V1InUse = false;
9423     bool V2InUse = false;
9424
9425     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9426                                                 DAG, V1InUse, V2InUse);
9427
9428     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9429     // do so. This avoids using them to handle blends-with-zero which is
9430     // important as a single pshufb is significantly faster for that.
9431     if (V1InUse && V2InUse) {
9432       if (Subtarget->hasSSE41())
9433         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9434                                                       Mask, Subtarget, DAG))
9435           return Blend;
9436
9437       // We can use an unpack to do the blending rather than an or in some
9438       // cases. Even though the or may be (very minorly) more efficient, we
9439       // preference this lowering because there are common cases where part of
9440       // the complexity of the shuffles goes away when we do the final blend as
9441       // an unpack.
9442       // FIXME: It might be worth trying to detect if the unpack-feeding
9443       // shuffles will both be pshufb, in which case we shouldn't bother with
9444       // this.
9445       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9446               DL, MVT::v16i8, V1, V2, Mask, DAG))
9447         return Unpack;
9448     }
9449
9450     return PSHUFB;
9451   }
9452
9453   // There are special ways we can lower some single-element blends.
9454   if (NumV2Elements == 1)
9455     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9456                                                          Mask, Subtarget, DAG))
9457       return V;
9458
9459   if (SDValue BitBlend =
9460           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9461     return BitBlend;
9462
9463   // Check whether a compaction lowering can be done. This handles shuffles
9464   // which take every Nth element for some even N. See the helper function for
9465   // details.
9466   //
9467   // We special case these as they can be particularly efficiently handled with
9468   // the PACKUSB instruction on x86 and they show up in common patterns of
9469   // rearranging bytes to truncate wide elements.
9470   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9471     // NumEvenDrops is the power of two stride of the elements. Another way of
9472     // thinking about it is that we need to drop the even elements this many
9473     // times to get the original input.
9474     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9475
9476     // First we need to zero all the dropped bytes.
9477     assert(NumEvenDrops <= 3 &&
9478            "No support for dropping even elements more than 3 times.");
9479     // We use the mask type to pick which bytes are preserved based on how many
9480     // elements are dropped.
9481     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9482     SDValue ByteClearMask = DAG.getBitcast(
9483         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9484     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9485     if (!IsSingleInput)
9486       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9487
9488     // Now pack things back together.
9489     V1 = DAG.getBitcast(MVT::v8i16, V1);
9490     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9491     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9492     for (int i = 1; i < NumEvenDrops; ++i) {
9493       Result = DAG.getBitcast(MVT::v8i16, Result);
9494       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9495     }
9496
9497     return Result;
9498   }
9499
9500   // Handle multi-input cases by blending single-input shuffles.
9501   if (NumV2Elements > 0)
9502     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9503                                                       Mask, DAG);
9504
9505   // The fallback path for single-input shuffles widens this into two v8i16
9506   // vectors with unpacks, shuffles those, and then pulls them back together
9507   // with a pack.
9508   SDValue V = V1;
9509
9510   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9511   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9512   for (int i = 0; i < 16; ++i)
9513     if (Mask[i] >= 0)
9514       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9515
9516   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9517
9518   SDValue VLoHalf, VHiHalf;
9519   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9520   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9521   // i16s.
9522   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9523                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9524       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9525                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9526     // Use a mask to drop the high bytes.
9527     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9528     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9529                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9530
9531     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9532     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9533
9534     // Squash the masks to point directly into VLoHalf.
9535     for (int &M : LoBlendMask)
9536       if (M >= 0)
9537         M /= 2;
9538     for (int &M : HiBlendMask)
9539       if (M >= 0)
9540         M /= 2;
9541   } else {
9542     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9543     // VHiHalf so that we can blend them as i16s.
9544     VLoHalf = DAG.getBitcast(
9545         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9546     VHiHalf = DAG.getBitcast(
9547         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9548   }
9549
9550   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9551   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9552
9553   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9554 }
9555
9556 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9557 ///
9558 /// This routine breaks down the specific type of 128-bit shuffle and
9559 /// dispatches to the lowering routines accordingly.
9560 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9561                                         MVT VT, const X86Subtarget *Subtarget,
9562                                         SelectionDAG &DAG) {
9563   switch (VT.SimpleTy) {
9564   case MVT::v2i64:
9565     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9566   case MVT::v2f64:
9567     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9568   case MVT::v4i32:
9569     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9570   case MVT::v4f32:
9571     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9572   case MVT::v8i16:
9573     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9574   case MVT::v16i8:
9575     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9576
9577   default:
9578     llvm_unreachable("Unimplemented!");
9579   }
9580 }
9581
9582 /// \brief Helper function to test whether a shuffle mask could be
9583 /// simplified by widening the elements being shuffled.
9584 ///
9585 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9586 /// leaves it in an unspecified state.
9587 ///
9588 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9589 /// shuffle masks. The latter have the special property of a '-2' representing
9590 /// a zero-ed lane of a vector.
9591 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9592                                     SmallVectorImpl<int> &WidenedMask) {
9593   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9594     // If both elements are undef, its trivial.
9595     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9596       WidenedMask.push_back(SM_SentinelUndef);
9597       continue;
9598     }
9599
9600     // Check for an undef mask and a mask value properly aligned to fit with
9601     // a pair of values. If we find such a case, use the non-undef mask's value.
9602     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9603       WidenedMask.push_back(Mask[i + 1] / 2);
9604       continue;
9605     }
9606     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9607       WidenedMask.push_back(Mask[i] / 2);
9608       continue;
9609     }
9610
9611     // When zeroing, we need to spread the zeroing across both lanes to widen.
9612     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9613       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9614           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9615         WidenedMask.push_back(SM_SentinelZero);
9616         continue;
9617       }
9618       return false;
9619     }
9620
9621     // Finally check if the two mask values are adjacent and aligned with
9622     // a pair.
9623     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9624       WidenedMask.push_back(Mask[i] / 2);
9625       continue;
9626     }
9627
9628     // Otherwise we can't safely widen the elements used in this shuffle.
9629     return false;
9630   }
9631   assert(WidenedMask.size() == Mask.size() / 2 &&
9632          "Incorrect size of mask after widening the elements!");
9633
9634   return true;
9635 }
9636
9637 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9638 ///
9639 /// This routine just extracts two subvectors, shuffles them independently, and
9640 /// then concatenates them back together. This should work effectively with all
9641 /// AVX vector shuffle types.
9642 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9643                                           SDValue V2, ArrayRef<int> Mask,
9644                                           SelectionDAG &DAG) {
9645   assert(VT.getSizeInBits() >= 256 &&
9646          "Only for 256-bit or wider vector shuffles!");
9647   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9648   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9649
9650   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9651   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9652
9653   int NumElements = VT.getVectorNumElements();
9654   int SplitNumElements = NumElements / 2;
9655   MVT ScalarVT = VT.getScalarType();
9656   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9657
9658   // Rather than splitting build-vectors, just build two narrower build
9659   // vectors. This helps shuffling with splats and zeros.
9660   auto SplitVector = [&](SDValue V) {
9661     while (V.getOpcode() == ISD::BITCAST)
9662       V = V->getOperand(0);
9663
9664     MVT OrigVT = V.getSimpleValueType();
9665     int OrigNumElements = OrigVT.getVectorNumElements();
9666     int OrigSplitNumElements = OrigNumElements / 2;
9667     MVT OrigScalarVT = OrigVT.getScalarType();
9668     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9669
9670     SDValue LoV, HiV;
9671
9672     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9673     if (!BV) {
9674       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9675                         DAG.getIntPtrConstant(0, DL));
9676       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9677                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9678     } else {
9679
9680       SmallVector<SDValue, 16> LoOps, HiOps;
9681       for (int i = 0; i < OrigSplitNumElements; ++i) {
9682         LoOps.push_back(BV->getOperand(i));
9683         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9684       }
9685       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9686       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9687     }
9688     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9689                           DAG.getBitcast(SplitVT, HiV));
9690   };
9691
9692   SDValue LoV1, HiV1, LoV2, HiV2;
9693   std::tie(LoV1, HiV1) = SplitVector(V1);
9694   std::tie(LoV2, HiV2) = SplitVector(V2);
9695
9696   // Now create two 4-way blends of these half-width vectors.
9697   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9698     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9699     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9700     for (int i = 0; i < SplitNumElements; ++i) {
9701       int M = HalfMask[i];
9702       if (M >= NumElements) {
9703         if (M >= NumElements + SplitNumElements)
9704           UseHiV2 = true;
9705         else
9706           UseLoV2 = true;
9707         V2BlendMask.push_back(M - NumElements);
9708         V1BlendMask.push_back(-1);
9709         BlendMask.push_back(SplitNumElements + i);
9710       } else if (M >= 0) {
9711         if (M >= SplitNumElements)
9712           UseHiV1 = true;
9713         else
9714           UseLoV1 = true;
9715         V2BlendMask.push_back(-1);
9716         V1BlendMask.push_back(M);
9717         BlendMask.push_back(i);
9718       } else {
9719         V2BlendMask.push_back(-1);
9720         V1BlendMask.push_back(-1);
9721         BlendMask.push_back(-1);
9722       }
9723     }
9724
9725     // Because the lowering happens after all combining takes place, we need to
9726     // manually combine these blend masks as much as possible so that we create
9727     // a minimal number of high-level vector shuffle nodes.
9728
9729     // First try just blending the halves of V1 or V2.
9730     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9731       return DAG.getUNDEF(SplitVT);
9732     if (!UseLoV2 && !UseHiV2)
9733       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9734     if (!UseLoV1 && !UseHiV1)
9735       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9736
9737     SDValue V1Blend, V2Blend;
9738     if (UseLoV1 && UseHiV1) {
9739       V1Blend =
9740         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9741     } else {
9742       // We only use half of V1 so map the usage down into the final blend mask.
9743       V1Blend = UseLoV1 ? LoV1 : HiV1;
9744       for (int i = 0; i < SplitNumElements; ++i)
9745         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9746           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9747     }
9748     if (UseLoV2 && UseHiV2) {
9749       V2Blend =
9750         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9751     } else {
9752       // We only use half of V2 so map the usage down into the final blend mask.
9753       V2Blend = UseLoV2 ? LoV2 : HiV2;
9754       for (int i = 0; i < SplitNumElements; ++i)
9755         if (BlendMask[i] >= SplitNumElements)
9756           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9757     }
9758     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9759   };
9760   SDValue Lo = HalfBlend(LoMask);
9761   SDValue Hi = HalfBlend(HiMask);
9762   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9763 }
9764
9765 /// \brief Either split a vector in halves or decompose the shuffles and the
9766 /// blend.
9767 ///
9768 /// This is provided as a good fallback for many lowerings of non-single-input
9769 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9770 /// between splitting the shuffle into 128-bit components and stitching those
9771 /// back together vs. extracting the single-input shuffles and blending those
9772 /// results.
9773 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9774                                                 SDValue V2, ArrayRef<int> Mask,
9775                                                 SelectionDAG &DAG) {
9776   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9777                                             "lower single-input shuffles as it "
9778                                             "could then recurse on itself.");
9779   int Size = Mask.size();
9780
9781   // If this can be modeled as a broadcast of two elements followed by a blend,
9782   // prefer that lowering. This is especially important because broadcasts can
9783   // often fold with memory operands.
9784   auto DoBothBroadcast = [&] {
9785     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9786     for (int M : Mask)
9787       if (M >= Size) {
9788         if (V2BroadcastIdx == -1)
9789           V2BroadcastIdx = M - Size;
9790         else if (M - Size != V2BroadcastIdx)
9791           return false;
9792       } else if (M >= 0) {
9793         if (V1BroadcastIdx == -1)
9794           V1BroadcastIdx = M;
9795         else if (M != V1BroadcastIdx)
9796           return false;
9797       }
9798     return true;
9799   };
9800   if (DoBothBroadcast())
9801     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9802                                                       DAG);
9803
9804   // If the inputs all stem from a single 128-bit lane of each input, then we
9805   // split them rather than blending because the split will decompose to
9806   // unusually few instructions.
9807   int LaneCount = VT.getSizeInBits() / 128;
9808   int LaneSize = Size / LaneCount;
9809   SmallBitVector LaneInputs[2];
9810   LaneInputs[0].resize(LaneCount, false);
9811   LaneInputs[1].resize(LaneCount, false);
9812   for (int i = 0; i < Size; ++i)
9813     if (Mask[i] >= 0)
9814       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9815   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9816     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9817
9818   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9819   // that the decomposed single-input shuffles don't end up here.
9820   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9821 }
9822
9823 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9824 /// a permutation and blend of those lanes.
9825 ///
9826 /// This essentially blends the out-of-lane inputs to each lane into the lane
9827 /// from a permuted copy of the vector. This lowering strategy results in four
9828 /// instructions in the worst case for a single-input cross lane shuffle which
9829 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9830 /// of. Special cases for each particular shuffle pattern should be handled
9831 /// prior to trying this lowering.
9832 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9833                                                        SDValue V1, SDValue V2,
9834                                                        ArrayRef<int> Mask,
9835                                                        SelectionDAG &DAG) {
9836   // FIXME: This should probably be generalized for 512-bit vectors as well.
9837   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9838   int LaneSize = Mask.size() / 2;
9839
9840   // If there are only inputs from one 128-bit lane, splitting will in fact be
9841   // less expensive. The flags track whether the given lane contains an element
9842   // that crosses to another lane.
9843   bool LaneCrossing[2] = {false, false};
9844   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9845     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9846       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9847   if (!LaneCrossing[0] || !LaneCrossing[1])
9848     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9849
9850   if (isSingleInputShuffleMask(Mask)) {
9851     SmallVector<int, 32> FlippedBlendMask;
9852     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9853       FlippedBlendMask.push_back(
9854           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9855                                   ? Mask[i]
9856                                   : Mask[i] % LaneSize +
9857                                         (i / LaneSize) * LaneSize + Size));
9858
9859     // Flip the vector, and blend the results which should now be in-lane. The
9860     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9861     // 5 for the high source. The value 3 selects the high half of source 2 and
9862     // the value 2 selects the low half of source 2. We only use source 2 to
9863     // allow folding it into a memory operand.
9864     unsigned PERMMask = 3 | 2 << 4;
9865     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9866                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9867     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9868   }
9869
9870   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9871   // will be handled by the above logic and a blend of the results, much like
9872   // other patterns in AVX.
9873   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9874 }
9875
9876 /// \brief Handle lowering 2-lane 128-bit shuffles.
9877 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9878                                         SDValue V2, ArrayRef<int> Mask,
9879                                         const X86Subtarget *Subtarget,
9880                                         SelectionDAG &DAG) {
9881   // TODO: If minimizing size and one of the inputs is a zero vector and the
9882   // the zero vector has only one use, we could use a VPERM2X128 to save the
9883   // instruction bytes needed to explicitly generate the zero vector.
9884
9885   // Blends are faster and handle all the non-lane-crossing cases.
9886   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9887                                                 Subtarget, DAG))
9888     return Blend;
9889
9890   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9891   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9892
9893   // If either input operand is a zero vector, use VPERM2X128 because its mask
9894   // allows us to replace the zero input with an implicit zero.
9895   if (!IsV1Zero && !IsV2Zero) {
9896     // Check for patterns which can be matched with a single insert of a 128-bit
9897     // subvector.
9898     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9899     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9900       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9901                                    VT.getVectorNumElements() / 2);
9902       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9903                                 DAG.getIntPtrConstant(0, DL));
9904       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9905                                 OnlyUsesV1 ? V1 : V2,
9906                                 DAG.getIntPtrConstant(0, DL));
9907       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9908     }
9909   }
9910
9911   // Otherwise form a 128-bit permutation. After accounting for undefs,
9912   // convert the 64-bit shuffle mask selection values into 128-bit
9913   // selection bits by dividing the indexes by 2 and shifting into positions
9914   // defined by a vperm2*128 instruction's immediate control byte.
9915
9916   // The immediate permute control byte looks like this:
9917   //    [1:0] - select 128 bits from sources for low half of destination
9918   //    [2]   - ignore
9919   //    [3]   - zero low half of destination
9920   //    [5:4] - select 128 bits from sources for high half of destination
9921   //    [6]   - ignore
9922   //    [7]   - zero high half of destination
9923
9924   int MaskLO = Mask[0];
9925   if (MaskLO == SM_SentinelUndef)
9926     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9927
9928   int MaskHI = Mask[2];
9929   if (MaskHI == SM_SentinelUndef)
9930     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9931
9932   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9933
9934   // If either input is a zero vector, replace it with an undef input.
9935   // Shuffle mask values <  4 are selecting elements of V1.
9936   // Shuffle mask values >= 4 are selecting elements of V2.
9937   // Adjust each half of the permute mask by clearing the half that was
9938   // selecting the zero vector and setting the zero mask bit.
9939   if (IsV1Zero) {
9940     V1 = DAG.getUNDEF(VT);
9941     if (MaskLO < 4)
9942       PermMask = (PermMask & 0xf0) | 0x08;
9943     if (MaskHI < 4)
9944       PermMask = (PermMask & 0x0f) | 0x80;
9945   }
9946   if (IsV2Zero) {
9947     V2 = DAG.getUNDEF(VT);
9948     if (MaskLO >= 4)
9949       PermMask = (PermMask & 0xf0) | 0x08;
9950     if (MaskHI >= 4)
9951       PermMask = (PermMask & 0x0f) | 0x80;
9952   }
9953
9954   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9955                      DAG.getConstant(PermMask, DL, MVT::i8));
9956 }
9957
9958 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9959 /// shuffling each lane.
9960 ///
9961 /// This will only succeed when the result of fixing the 128-bit lanes results
9962 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9963 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9964 /// the lane crosses early and then use simpler shuffles within each lane.
9965 ///
9966 /// FIXME: It might be worthwhile at some point to support this without
9967 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9968 /// in x86 only floating point has interesting non-repeating shuffles, and even
9969 /// those are still *marginally* more expensive.
9970 static SDValue lowerVectorShuffleByMerging128BitLanes(
9971     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9972     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9973   assert(!isSingleInputShuffleMask(Mask) &&
9974          "This is only useful with multiple inputs.");
9975
9976   int Size = Mask.size();
9977   int LaneSize = 128 / VT.getScalarSizeInBits();
9978   int NumLanes = Size / LaneSize;
9979   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9980
9981   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9982   // check whether the in-128-bit lane shuffles share a repeating pattern.
9983   SmallVector<int, 4> Lanes;
9984   Lanes.resize(NumLanes, -1);
9985   SmallVector<int, 4> InLaneMask;
9986   InLaneMask.resize(LaneSize, -1);
9987   for (int i = 0; i < Size; ++i) {
9988     if (Mask[i] < 0)
9989       continue;
9990
9991     int j = i / LaneSize;
9992
9993     if (Lanes[j] < 0) {
9994       // First entry we've seen for this lane.
9995       Lanes[j] = Mask[i] / LaneSize;
9996     } else if (Lanes[j] != Mask[i] / LaneSize) {
9997       // This doesn't match the lane selected previously!
9998       return SDValue();
9999     }
10000
10001     // Check that within each lane we have a consistent shuffle mask.
10002     int k = i % LaneSize;
10003     if (InLaneMask[k] < 0) {
10004       InLaneMask[k] = Mask[i] % LaneSize;
10005     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10006       // This doesn't fit a repeating in-lane mask.
10007       return SDValue();
10008     }
10009   }
10010
10011   // First shuffle the lanes into place.
10012   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10013                                 VT.getSizeInBits() / 64);
10014   SmallVector<int, 8> LaneMask;
10015   LaneMask.resize(NumLanes * 2, -1);
10016   for (int i = 0; i < NumLanes; ++i)
10017     if (Lanes[i] >= 0) {
10018       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10019       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10020     }
10021
10022   V1 = DAG.getBitcast(LaneVT, V1);
10023   V2 = DAG.getBitcast(LaneVT, V2);
10024   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10025
10026   // Cast it back to the type we actually want.
10027   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10028
10029   // Now do a simple shuffle that isn't lane crossing.
10030   SmallVector<int, 8> NewMask;
10031   NewMask.resize(Size, -1);
10032   for (int i = 0; i < Size; ++i)
10033     if (Mask[i] >= 0)
10034       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10035   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10036          "Must not introduce lane crosses at this point!");
10037
10038   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10039 }
10040
10041 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10042 /// given mask.
10043 ///
10044 /// This returns true if the elements from a particular input are already in the
10045 /// slot required by the given mask and require no permutation.
10046 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10047   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10048   int Size = Mask.size();
10049   for (int i = 0; i < Size; ++i)
10050     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10051       return false;
10052
10053   return true;
10054 }
10055
10056 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10057                                             ArrayRef<int> Mask, SDValue V1,
10058                                             SDValue V2, SelectionDAG &DAG) {
10059
10060   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
10061   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
10062   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10063   int NumElts = VT.getVectorNumElements();
10064   bool ShufpdMask = true;
10065   bool CommutableMask = true;
10066   unsigned Immediate = 0;
10067   for (int i = 0; i < NumElts; ++i) {
10068     if (Mask[i] < 0)
10069       continue;
10070     int Val = (i & 6) + NumElts * (i & 1);
10071     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10072     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10073       ShufpdMask = false;
10074     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10075       CommutableMask = false;
10076     Immediate |= (Mask[i] % 2) << i;
10077   }
10078   if (ShufpdMask)
10079     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10080                        DAG.getConstant(Immediate, DL, MVT::i8));
10081   if (CommutableMask)
10082     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10083                        DAG.getConstant(Immediate, DL, MVT::i8));
10084   return SDValue();
10085 }
10086
10087 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10088 ///
10089 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10090 /// isn't available.
10091 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10092                                        const X86Subtarget *Subtarget,
10093                                        SelectionDAG &DAG) {
10094   SDLoc DL(Op);
10095   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10096   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10097   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10098   ArrayRef<int> Mask = SVOp->getMask();
10099   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10100
10101   SmallVector<int, 4> WidenedMask;
10102   if (canWidenShuffleElements(Mask, WidenedMask))
10103     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10104                                     DAG);
10105
10106   if (isSingleInputShuffleMask(Mask)) {
10107     // Check for being able to broadcast a single element.
10108     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10109                                                           Mask, Subtarget, DAG))
10110       return Broadcast;
10111
10112     // Use low duplicate instructions for masks that match their pattern.
10113     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10114       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10115
10116     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10117       // Non-half-crossing single input shuffles can be lowerid with an
10118       // interleaved permutation.
10119       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10120                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10121       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10122                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10123     }
10124
10125     // With AVX2 we have direct support for this permutation.
10126     if (Subtarget->hasAVX2())
10127       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10128                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10129
10130     // Otherwise, fall back.
10131     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10132                                                    DAG);
10133   }
10134
10135   // X86 has dedicated unpack instructions that can handle specific blend
10136   // operations: UNPCKH and UNPCKL.
10137   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10138     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
10139   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10140     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
10141   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10142     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
10143   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10144     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
10145
10146   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10147                                                 Subtarget, DAG))
10148     return Blend;
10149
10150   // Check if the blend happens to exactly fit that of SHUFPD.
10151   if (SDValue Op =
10152       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10153     return Op;
10154
10155   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10156   // shuffle. However, if we have AVX2 and either inputs are already in place,
10157   // we will be able to shuffle even across lanes the other input in a single
10158   // instruction so skip this pattern.
10159   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10160                                  isShuffleMaskInputInPlace(1, Mask))))
10161     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10162             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10163       return Result;
10164
10165   // If we have AVX2 then we always want to lower with a blend because an v4 we
10166   // can fully permute the elements.
10167   if (Subtarget->hasAVX2())
10168     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10169                                                       Mask, DAG);
10170
10171   // Otherwise fall back on generic lowering.
10172   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10173 }
10174
10175 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10176 ///
10177 /// This routine is only called when we have AVX2 and thus a reasonable
10178 /// instruction set for v4i64 shuffling..
10179 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10180                                        const X86Subtarget *Subtarget,
10181                                        SelectionDAG &DAG) {
10182   SDLoc DL(Op);
10183   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10184   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10185   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10186   ArrayRef<int> Mask = SVOp->getMask();
10187   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10188   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10189
10190   SmallVector<int, 4> WidenedMask;
10191   if (canWidenShuffleElements(Mask, WidenedMask))
10192     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10193                                     DAG);
10194
10195   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10196                                                 Subtarget, DAG))
10197     return Blend;
10198
10199   // Check for being able to broadcast a single element.
10200   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10201                                                         Mask, Subtarget, DAG))
10202     return Broadcast;
10203
10204   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10205   // use lower latency instructions that will operate on both 128-bit lanes.
10206   SmallVector<int, 2> RepeatedMask;
10207   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10208     if (isSingleInputShuffleMask(Mask)) {
10209       int PSHUFDMask[] = {-1, -1, -1, -1};
10210       for (int i = 0; i < 2; ++i)
10211         if (RepeatedMask[i] >= 0) {
10212           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10213           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10214         }
10215       return DAG.getBitcast(
10216           MVT::v4i64,
10217           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10218                       DAG.getBitcast(MVT::v8i32, V1),
10219                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10220     }
10221   }
10222
10223   // AVX2 provides a direct instruction for permuting a single input across
10224   // lanes.
10225   if (isSingleInputShuffleMask(Mask))
10226     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10227                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10228
10229   // Try to use shift instructions.
10230   if (SDValue Shift =
10231           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10232     return Shift;
10233
10234   // Use dedicated unpack instructions for masks that match their pattern.
10235   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10236     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
10237   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10238     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
10239   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10240     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
10241   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10242     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
10243
10244   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10245   // shuffle. However, if we have AVX2 and either inputs are already in place,
10246   // we will be able to shuffle even across lanes the other input in a single
10247   // instruction so skip this pattern.
10248   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10249                                  isShuffleMaskInputInPlace(1, Mask))))
10250     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10251             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10252       return Result;
10253
10254   // Otherwise fall back on generic blend lowering.
10255   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10256                                                     Mask, DAG);
10257 }
10258
10259 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10260 ///
10261 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10262 /// isn't available.
10263 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10264                                        const X86Subtarget *Subtarget,
10265                                        SelectionDAG &DAG) {
10266   SDLoc DL(Op);
10267   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10268   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10269   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10270   ArrayRef<int> Mask = SVOp->getMask();
10271   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10272
10273   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10274                                                 Subtarget, DAG))
10275     return Blend;
10276
10277   // Check for being able to broadcast a single element.
10278   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10279                                                         Mask, Subtarget, DAG))
10280     return Broadcast;
10281
10282   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10283   // options to efficiently lower the shuffle.
10284   SmallVector<int, 4> RepeatedMask;
10285   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10286     assert(RepeatedMask.size() == 4 &&
10287            "Repeated masks must be half the mask width!");
10288
10289     // Use even/odd duplicate instructions for masks that match their pattern.
10290     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10291       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10292     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10293       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10294
10295     if (isSingleInputShuffleMask(Mask))
10296       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10297                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10298
10299     // Use dedicated unpack instructions for masks that match their pattern.
10300     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10301       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10302     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10303       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10304     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10305       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10306     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10307       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10308
10309     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10310     // have already handled any direct blends. We also need to squash the
10311     // repeated mask into a simulated v4f32 mask.
10312     for (int i = 0; i < 4; ++i)
10313       if (RepeatedMask[i] >= 8)
10314         RepeatedMask[i] -= 4;
10315     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10316   }
10317
10318   // If we have a single input shuffle with different shuffle patterns in the
10319   // two 128-bit lanes use the variable mask to VPERMILPS.
10320   if (isSingleInputShuffleMask(Mask)) {
10321     SDValue VPermMask[8];
10322     for (int i = 0; i < 8; ++i)
10323       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10324                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10325     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10326       return DAG.getNode(
10327           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10328           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10329
10330     if (Subtarget->hasAVX2())
10331       return DAG.getNode(
10332           X86ISD::VPERMV, DL, MVT::v8f32,
10333           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10334                                                  MVT::v8i32, VPermMask)),
10335           V1);
10336
10337     // Otherwise, fall back.
10338     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10339                                                    DAG);
10340   }
10341
10342   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10343   // shuffle.
10344   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10345           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10346     return Result;
10347
10348   // If we have AVX2 then we always want to lower with a blend because at v8 we
10349   // can fully permute the elements.
10350   if (Subtarget->hasAVX2())
10351     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10352                                                       Mask, DAG);
10353
10354   // Otherwise fall back on generic lowering.
10355   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10356 }
10357
10358 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10359 ///
10360 /// This routine is only called when we have AVX2 and thus a reasonable
10361 /// instruction set for v8i32 shuffling..
10362 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10363                                        const X86Subtarget *Subtarget,
10364                                        SelectionDAG &DAG) {
10365   SDLoc DL(Op);
10366   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10367   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10368   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10369   ArrayRef<int> Mask = SVOp->getMask();
10370   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10371   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10372
10373   // Whenever we can lower this as a zext, that instruction is strictly faster
10374   // than any alternative. It also allows us to fold memory operands into the
10375   // shuffle in many cases.
10376   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10377                                                          Mask, Subtarget, DAG))
10378     return ZExt;
10379
10380   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10381                                                 Subtarget, DAG))
10382     return Blend;
10383
10384   // Check for being able to broadcast a single element.
10385   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10386                                                         Mask, Subtarget, DAG))
10387     return Broadcast;
10388
10389   // If the shuffle mask is repeated in each 128-bit lane we can use more
10390   // efficient instructions that mirror the shuffles across the two 128-bit
10391   // lanes.
10392   SmallVector<int, 4> RepeatedMask;
10393   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10394     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10395     if (isSingleInputShuffleMask(Mask))
10396       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10397                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10398
10399     // Use dedicated unpack instructions for masks that match their pattern.
10400     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10401       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10402     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10403       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10404     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10405       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10406     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10407       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10408   }
10409
10410   // Try to use shift instructions.
10411   if (SDValue Shift =
10412           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10413     return Shift;
10414
10415   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10416           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10417     return Rotate;
10418
10419   // If the shuffle patterns aren't repeated but it is a single input, directly
10420   // generate a cross-lane VPERMD instruction.
10421   if (isSingleInputShuffleMask(Mask)) {
10422     SDValue VPermMask[8];
10423     for (int i = 0; i < 8; ++i)
10424       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10425                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10426     return DAG.getNode(
10427         X86ISD::VPERMV, DL, MVT::v8i32,
10428         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10429   }
10430
10431   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10432   // shuffle.
10433   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10434           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10435     return Result;
10436
10437   // Otherwise fall back on generic blend lowering.
10438   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10439                                                     Mask, DAG);
10440 }
10441
10442 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10443 ///
10444 /// This routine is only called when we have AVX2 and thus a reasonable
10445 /// instruction set for v16i16 shuffling..
10446 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10447                                         const X86Subtarget *Subtarget,
10448                                         SelectionDAG &DAG) {
10449   SDLoc DL(Op);
10450   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10451   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10452   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10453   ArrayRef<int> Mask = SVOp->getMask();
10454   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10455   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10456
10457   // Whenever we can lower this as a zext, that instruction is strictly faster
10458   // than any alternative. It also allows us to fold memory operands into the
10459   // shuffle in many cases.
10460   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10461                                                          Mask, Subtarget, DAG))
10462     return ZExt;
10463
10464   // Check for being able to broadcast a single element.
10465   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10466                                                         Mask, Subtarget, DAG))
10467     return Broadcast;
10468
10469   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10470                                                 Subtarget, DAG))
10471     return Blend;
10472
10473   // Use dedicated unpack instructions for masks that match their pattern.
10474   if (isShuffleEquivalent(V1, V2, Mask,
10475                           {// First 128-bit lane:
10476                            0, 16, 1, 17, 2, 18, 3, 19,
10477                            // Second 128-bit lane:
10478                            8, 24, 9, 25, 10, 26, 11, 27}))
10479     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10480   if (isShuffleEquivalent(V1, V2, Mask,
10481                           {// First 128-bit lane:
10482                            4, 20, 5, 21, 6, 22, 7, 23,
10483                            // Second 128-bit lane:
10484                            12, 28, 13, 29, 14, 30, 15, 31}))
10485     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10486
10487   // Try to use shift instructions.
10488   if (SDValue Shift =
10489           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10490     return Shift;
10491
10492   // Try to use byte rotation instructions.
10493   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10494           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10495     return Rotate;
10496
10497   if (isSingleInputShuffleMask(Mask)) {
10498     // There are no generalized cross-lane shuffle operations available on i16
10499     // element types.
10500     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10501       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10502                                                      Mask, DAG);
10503
10504     SmallVector<int, 8> RepeatedMask;
10505     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10506       // As this is a single-input shuffle, the repeated mask should be
10507       // a strictly valid v8i16 mask that we can pass through to the v8i16
10508       // lowering to handle even the v16 case.
10509       return lowerV8I16GeneralSingleInputVectorShuffle(
10510           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10511     }
10512
10513     SDValue PSHUFBMask[32];
10514     for (int i = 0; i < 16; ++i) {
10515       if (Mask[i] == -1) {
10516         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10517         continue;
10518       }
10519
10520       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10521       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10522       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10523       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10524     }
10525     return DAG.getBitcast(MVT::v16i16,
10526                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10527                                       DAG.getBitcast(MVT::v32i8, V1),
10528                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10529                                                   MVT::v32i8, PSHUFBMask)));
10530   }
10531
10532   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10533   // shuffle.
10534   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10535           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10536     return Result;
10537
10538   // Otherwise fall back on generic lowering.
10539   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10540 }
10541
10542 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10543 ///
10544 /// This routine is only called when we have AVX2 and thus a reasonable
10545 /// instruction set for v32i8 shuffling..
10546 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10547                                        const X86Subtarget *Subtarget,
10548                                        SelectionDAG &DAG) {
10549   SDLoc DL(Op);
10550   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10551   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10552   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10553   ArrayRef<int> Mask = SVOp->getMask();
10554   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10555   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10556
10557   // Whenever we can lower this as a zext, that instruction is strictly faster
10558   // than any alternative. It also allows us to fold memory operands into the
10559   // shuffle in many cases.
10560   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10561                                                          Mask, Subtarget, DAG))
10562     return ZExt;
10563
10564   // Check for being able to broadcast a single element.
10565   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10566                                                         Mask, Subtarget, DAG))
10567     return Broadcast;
10568
10569   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10570                                                 Subtarget, DAG))
10571     return Blend;
10572
10573   // Use dedicated unpack instructions for masks that match their pattern.
10574   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10575   // 256-bit lanes.
10576   if (isShuffleEquivalent(
10577           V1, V2, Mask,
10578           {// First 128-bit lane:
10579            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10580            // Second 128-bit lane:
10581            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10582     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10583   if (isShuffleEquivalent(
10584           V1, V2, Mask,
10585           {// First 128-bit lane:
10586            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10587            // Second 128-bit lane:
10588            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10589     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10590
10591   // Try to use shift instructions.
10592   if (SDValue Shift =
10593           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10594     return Shift;
10595
10596   // Try to use byte rotation instructions.
10597   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10598           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10599     return Rotate;
10600
10601   if (isSingleInputShuffleMask(Mask)) {
10602     // There are no generalized cross-lane shuffle operations available on i8
10603     // element types.
10604     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10605       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10606                                                      Mask, DAG);
10607
10608     SDValue PSHUFBMask[32];
10609     for (int i = 0; i < 32; ++i)
10610       PSHUFBMask[i] =
10611           Mask[i] < 0
10612               ? DAG.getUNDEF(MVT::i8)
10613               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10614                                 MVT::i8);
10615
10616     return DAG.getNode(
10617         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10618         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10619   }
10620
10621   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10622   // shuffle.
10623   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10624           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10625     return Result;
10626
10627   // Otherwise fall back on generic lowering.
10628   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10629 }
10630
10631 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10632 ///
10633 /// This routine either breaks down the specific type of a 256-bit x86 vector
10634 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10635 /// together based on the available instructions.
10636 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10637                                         MVT VT, const X86Subtarget *Subtarget,
10638                                         SelectionDAG &DAG) {
10639   SDLoc DL(Op);
10640   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10641   ArrayRef<int> Mask = SVOp->getMask();
10642
10643   // If we have a single input to the zero element, insert that into V1 if we
10644   // can do so cheaply.
10645   int NumElts = VT.getVectorNumElements();
10646   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10647     return M >= NumElts;
10648   });
10649
10650   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10651     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10652                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10653       return Insertion;
10654
10655   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
10656   // can check for those subtargets here and avoid much of the subtarget
10657   // querying in the per-vector-type lowering routines. With AVX1 we have
10658   // essentially *zero* ability to manipulate a 256-bit vector with integer
10659   // types. Since we'll use floating point types there eventually, just
10660   // immediately cast everything to a float and operate entirely in that domain.
10661   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10662     int ElementBits = VT.getScalarSizeInBits();
10663     if (ElementBits < 32)
10664       // No floating point type available, decompose into 128-bit vectors.
10665       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10666
10667     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10668                                 VT.getVectorNumElements());
10669     V1 = DAG.getBitcast(FpVT, V1);
10670     V2 = DAG.getBitcast(FpVT, V2);
10671     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10672   }
10673
10674   switch (VT.SimpleTy) {
10675   case MVT::v4f64:
10676     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10677   case MVT::v4i64:
10678     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10679   case MVT::v8f32:
10680     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10681   case MVT::v8i32:
10682     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10683   case MVT::v16i16:
10684     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10685   case MVT::v32i8:
10686     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10687
10688   default:
10689     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10690   }
10691 }
10692
10693 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10694                                            ArrayRef<int> Mask, SDValue V1,
10695                                            SDValue V2, SelectionDAG &DAG) {
10696
10697   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10698
10699   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10700   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10701
10702   SmallVector<SDValue, 32>  VPermMask;
10703   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i)
10704     VPermMask.push_back(Mask[i] < 0 ? DAG.getUNDEF(MaskEltVT) :
10705                         DAG.getConstant(Mask[i], DL, MaskEltVT));
10706   SDValue MaskNode = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVecVT,
10707                                  VPermMask);
10708   if (isSingleInputShuffleMask(Mask))
10709     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10710
10711   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10712 }
10713
10714 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10715 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10716                                        const X86Subtarget *Subtarget,
10717                                        SelectionDAG &DAG) {
10718   SDLoc DL(Op);
10719   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10720   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10721   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10722   ArrayRef<int> Mask = SVOp->getMask();
10723   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10724
10725   if (SDValue Unpck =
10726           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
10727     return Unpck;
10728
10729   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10730 }
10731
10732 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10733 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10734                                        const X86Subtarget *Subtarget,
10735                                        SelectionDAG &DAG) {
10736   SDLoc DL(Op);
10737   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10738   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10739   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10740   ArrayRef<int> Mask = SVOp->getMask();
10741   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10742
10743   if (SDValue Unpck =
10744           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
10745     return Unpck;
10746
10747   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
10748 }
10749
10750 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10751 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10752                                        const X86Subtarget *Subtarget,
10753                                        SelectionDAG &DAG) {
10754   SDLoc DL(Op);
10755   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10756   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10757   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10758   ArrayRef<int> Mask = SVOp->getMask();
10759   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10760
10761   if (SDValue Unpck =
10762           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
10763     return Unpck;
10764
10765   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
10766 }
10767
10768 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10769 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10770                                        const X86Subtarget *Subtarget,
10771                                        SelectionDAG &DAG) {
10772   SDLoc DL(Op);
10773   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10774   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10775   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10776   ArrayRef<int> Mask = SVOp->getMask();
10777   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10778
10779   if (SDValue Unpck =
10780           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
10781     return Unpck;
10782
10783   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
10784 }
10785
10786 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10787 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10788                                         const X86Subtarget *Subtarget,
10789                                         SelectionDAG &DAG) {
10790   SDLoc DL(Op);
10791   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10792   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10793   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10794   ArrayRef<int> Mask = SVOp->getMask();
10795   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10796   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10797
10798   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
10799 }
10800
10801 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10802 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10803                                        const X86Subtarget *Subtarget,
10804                                        SelectionDAG &DAG) {
10805   SDLoc DL(Op);
10806   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10807   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10808   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10809   ArrayRef<int> Mask = SVOp->getMask();
10810   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10811   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10812
10813   // FIXME: Implement direct support for this type!
10814   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10815 }
10816
10817 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10818 ///
10819 /// This routine either breaks down the specific type of a 512-bit x86 vector
10820 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10821 /// together based on the available instructions.
10822 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10823                                         MVT VT, const X86Subtarget *Subtarget,
10824                                         SelectionDAG &DAG) {
10825   SDLoc DL(Op);
10826   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10827   ArrayRef<int> Mask = SVOp->getMask();
10828   assert(Subtarget->hasAVX512() &&
10829          "Cannot lower 512-bit vectors w/ basic ISA!");
10830
10831   // Check for being able to broadcast a single element.
10832   if (SDValue Broadcast =
10833           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10834     return Broadcast;
10835
10836   // Dispatch to each element type for lowering. If we don't have supprot for
10837   // specific element type shuffles at 512 bits, immediately split them and
10838   // lower them. Each lowering routine of a given type is allowed to assume that
10839   // the requisite ISA extensions for that element type are available.
10840   switch (VT.SimpleTy) {
10841   case MVT::v8f64:
10842     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10843   case MVT::v16f32:
10844     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10845   case MVT::v8i64:
10846     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10847   case MVT::v16i32:
10848     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10849   case MVT::v32i16:
10850     if (Subtarget->hasBWI())
10851       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10852     break;
10853   case MVT::v64i8:
10854     if (Subtarget->hasBWI())
10855       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10856     break;
10857
10858   default:
10859     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10860   }
10861
10862   // Otherwise fall back on splitting.
10863   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10864 }
10865
10866 // Lower vXi1 vector shuffles.
10867 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
10868 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
10869 // vector, shuffle and then truncate it back.
10870 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10871                                       MVT VT, const X86Subtarget *Subtarget,
10872                                       SelectionDAG &DAG) {
10873   SDLoc DL(Op);
10874   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10875   ArrayRef<int> Mask = SVOp->getMask();
10876   assert(Subtarget->hasAVX512() &&
10877          "Cannot lower 512-bit vectors w/o basic ISA!");
10878   EVT ExtVT;
10879   switch (VT.SimpleTy) {
10880   default:
10881     assert(false && "Expected a vector of i1 elements");
10882     break;
10883   case MVT::v2i1:
10884     ExtVT = MVT::v2i64;
10885     break;
10886   case MVT::v4i1:
10887     ExtVT = MVT::v4i32;
10888     break;
10889   case MVT::v8i1:
10890     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
10891     break;
10892   case MVT::v16i1:
10893     ExtVT = MVT::v16i32;
10894     break;
10895   case MVT::v32i1:
10896     ExtVT = MVT::v32i16;
10897     break;
10898   case MVT::v64i1:
10899     ExtVT = MVT::v64i8;
10900     break;
10901   }
10902
10903   if (ISD::isBuildVectorAllZeros(V1.getNode()))
10904     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10905   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
10906     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10907   else
10908     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
10909
10910   if (V2.isUndef())
10911     V2 = DAG.getUNDEF(ExtVT);
10912   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
10913     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10914   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
10915     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10916   else
10917     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
10918   return DAG.getNode(ISD::TRUNCATE, DL, VT,
10919                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
10920 }
10921 /// \brief Top-level lowering for x86 vector shuffles.
10922 ///
10923 /// This handles decomposition, canonicalization, and lowering of all x86
10924 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10925 /// above in helper routines. The canonicalization attempts to widen shuffles
10926 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10927 /// s.t. only one of the two inputs needs to be tested, etc.
10928 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10929                                   SelectionDAG &DAG) {
10930   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10931   ArrayRef<int> Mask = SVOp->getMask();
10932   SDValue V1 = Op.getOperand(0);
10933   SDValue V2 = Op.getOperand(1);
10934   MVT VT = Op.getSimpleValueType();
10935   int NumElements = VT.getVectorNumElements();
10936   SDLoc dl(Op);
10937   bool Is1BitVector = (VT.getScalarType() == MVT::i1);
10938
10939   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
10940          "Can't lower MMX shuffles");
10941
10942   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10943   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10944   if (V1IsUndef && V2IsUndef)
10945     return DAG.getUNDEF(VT);
10946
10947   // When we create a shuffle node we put the UNDEF node to second operand,
10948   // but in some cases the first operand may be transformed to UNDEF.
10949   // In this case we should just commute the node.
10950   if (V1IsUndef)
10951     return DAG.getCommutedVectorShuffle(*SVOp);
10952
10953   // Check for non-undef masks pointing at an undef vector and make the masks
10954   // undef as well. This makes it easier to match the shuffle based solely on
10955   // the mask.
10956   if (V2IsUndef)
10957     for (int M : Mask)
10958       if (M >= NumElements) {
10959         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10960         for (int &M : NewMask)
10961           if (M >= NumElements)
10962             M = -1;
10963         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10964       }
10965
10966   // We actually see shuffles that are entirely re-arrangements of a set of
10967   // zero inputs. This mostly happens while decomposing complex shuffles into
10968   // simple ones. Directly lower these as a buildvector of zeros.
10969   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10970   if (Zeroable.all())
10971     return getZeroVector(VT, Subtarget, DAG, dl);
10972
10973   // Try to collapse shuffles into using a vector type with fewer elements but
10974   // wider element types. We cap this to not form integers or floating point
10975   // elements wider than 64 bits, but it might be interesting to form i128
10976   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10977   SmallVector<int, 16> WidenedMask;
10978   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
10979       canWidenShuffleElements(Mask, WidenedMask)) {
10980     MVT NewEltVT = VT.isFloatingPoint()
10981                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10982                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10983     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10984     // Make sure that the new vector type is legal. For example, v2f64 isn't
10985     // legal on SSE1.
10986     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10987       V1 = DAG.getBitcast(NewVT, V1);
10988       V2 = DAG.getBitcast(NewVT, V2);
10989       return DAG.getBitcast(
10990           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10991     }
10992   }
10993
10994   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10995   for (int M : SVOp->getMask())
10996     if (M < 0)
10997       ++NumUndefElements;
10998     else if (M < NumElements)
10999       ++NumV1Elements;
11000     else
11001       ++NumV2Elements;
11002
11003   // Commute the shuffle as needed such that more elements come from V1 than
11004   // V2. This allows us to match the shuffle pattern strictly on how many
11005   // elements come from V1 without handling the symmetric cases.
11006   if (NumV2Elements > NumV1Elements)
11007     return DAG.getCommutedVectorShuffle(*SVOp);
11008
11009   // When the number of V1 and V2 elements are the same, try to minimize the
11010   // number of uses of V2 in the low half of the vector. When that is tied,
11011   // ensure that the sum of indices for V1 is equal to or lower than the sum
11012   // indices for V2. When those are equal, try to ensure that the number of odd
11013   // indices for V1 is lower than the number of odd indices for V2.
11014   if (NumV1Elements == NumV2Elements) {
11015     int LowV1Elements = 0, LowV2Elements = 0;
11016     for (int M : SVOp->getMask().slice(0, NumElements / 2))
11017       if (M >= NumElements)
11018         ++LowV2Elements;
11019       else if (M >= 0)
11020         ++LowV1Elements;
11021     if (LowV2Elements > LowV1Elements) {
11022       return DAG.getCommutedVectorShuffle(*SVOp);
11023     } else if (LowV2Elements == LowV1Elements) {
11024       int SumV1Indices = 0, SumV2Indices = 0;
11025       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11026         if (SVOp->getMask()[i] >= NumElements)
11027           SumV2Indices += i;
11028         else if (SVOp->getMask()[i] >= 0)
11029           SumV1Indices += i;
11030       if (SumV2Indices < SumV1Indices) {
11031         return DAG.getCommutedVectorShuffle(*SVOp);
11032       } else if (SumV2Indices == SumV1Indices) {
11033         int NumV1OddIndices = 0, NumV2OddIndices = 0;
11034         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11035           if (SVOp->getMask()[i] >= NumElements)
11036             NumV2OddIndices += i % 2;
11037           else if (SVOp->getMask()[i] >= 0)
11038             NumV1OddIndices += i % 2;
11039         if (NumV2OddIndices < NumV1OddIndices)
11040           return DAG.getCommutedVectorShuffle(*SVOp);
11041       }
11042     }
11043   }
11044
11045   // For each vector width, delegate to a specialized lowering routine.
11046   if (VT.getSizeInBits() == 128)
11047     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11048
11049   if (VT.getSizeInBits() == 256)
11050     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11051
11052   if (VT.getSizeInBits() == 512)
11053     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11054
11055   if (Is1BitVector)
11056     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11057   llvm_unreachable("Unimplemented!");
11058 }
11059
11060 // This function assumes its argument is a BUILD_VECTOR of constants or
11061 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11062 // true.
11063 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11064                                     unsigned &MaskValue) {
11065   MaskValue = 0;
11066   unsigned NumElems = BuildVector->getNumOperands();
11067   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11068   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11069   unsigned NumElemsInLane = NumElems / NumLanes;
11070
11071   // Blend for v16i16 should be symmetric for the both lanes.
11072   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11073     SDValue EltCond = BuildVector->getOperand(i);
11074     SDValue SndLaneEltCond =
11075         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11076
11077     int Lane1Cond = -1, Lane2Cond = -1;
11078     if (isa<ConstantSDNode>(EltCond))
11079       Lane1Cond = !isZero(EltCond);
11080     if (isa<ConstantSDNode>(SndLaneEltCond))
11081       Lane2Cond = !isZero(SndLaneEltCond);
11082
11083     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11084       // Lane1Cond != 0, means we want the first argument.
11085       // Lane1Cond == 0, means we want the second argument.
11086       // The encoding of this argument is 0 for the first argument, 1
11087       // for the second. Therefore, invert the condition.
11088       MaskValue |= !Lane1Cond << i;
11089     else if (Lane1Cond < 0)
11090       MaskValue |= !Lane2Cond << i;
11091     else
11092       return false;
11093   }
11094   return true;
11095 }
11096
11097 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11098 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11099                                            const X86Subtarget *Subtarget,
11100                                            SelectionDAG &DAG) {
11101   SDValue Cond = Op.getOperand(0);
11102   SDValue LHS = Op.getOperand(1);
11103   SDValue RHS = Op.getOperand(2);
11104   SDLoc dl(Op);
11105   MVT VT = Op.getSimpleValueType();
11106
11107   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11108     return SDValue();
11109   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11110
11111   // Only non-legal VSELECTs reach this lowering, convert those into generic
11112   // shuffles and re-use the shuffle lowering path for blends.
11113   SmallVector<int, 32> Mask;
11114   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11115     SDValue CondElt = CondBV->getOperand(i);
11116     Mask.push_back(
11117         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
11118   }
11119   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11120 }
11121
11122 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11123   // A vselect where all conditions and data are constants can be optimized into
11124   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11125   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11126       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11127       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11128     return SDValue();
11129
11130   // Try to lower this to a blend-style vector shuffle. This can handle all
11131   // constant condition cases.
11132   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11133     return BlendOp;
11134
11135   // Variable blends are only legal from SSE4.1 onward.
11136   if (!Subtarget->hasSSE41())
11137     return SDValue();
11138
11139   // Only some types will be legal on some subtargets. If we can emit a legal
11140   // VSELECT-matching blend, return Op, and but if we need to expand, return
11141   // a null value.
11142   switch (Op.getSimpleValueType().SimpleTy) {
11143   default:
11144     // Most of the vector types have blends past SSE4.1.
11145     return Op;
11146
11147   case MVT::v32i8:
11148     // The byte blends for AVX vectors were introduced only in AVX2.
11149     if (Subtarget->hasAVX2())
11150       return Op;
11151
11152     return SDValue();
11153
11154   case MVT::v8i16:
11155   case MVT::v16i16:
11156     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11157     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11158       return Op;
11159
11160     // FIXME: We should custom lower this by fixing the condition and using i8
11161     // blends.
11162     return SDValue();
11163   }
11164 }
11165
11166 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11167   MVT VT = Op.getSimpleValueType();
11168   SDLoc dl(Op);
11169
11170   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11171     return SDValue();
11172
11173   if (VT.getSizeInBits() == 8) {
11174     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11175                                   Op.getOperand(0), Op.getOperand(1));
11176     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11177                                   DAG.getValueType(VT));
11178     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11179   }
11180
11181   if (VT.getSizeInBits() == 16) {
11182     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11183     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11184     if (Idx == 0)
11185       return DAG.getNode(
11186           ISD::TRUNCATE, dl, MVT::i16,
11187           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11188                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11189                       Op.getOperand(1)));
11190     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11191                                   Op.getOperand(0), Op.getOperand(1));
11192     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11193                                   DAG.getValueType(VT));
11194     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11195   }
11196
11197   if (VT == MVT::f32) {
11198     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11199     // the result back to FR32 register. It's only worth matching if the
11200     // result has a single use which is a store or a bitcast to i32.  And in
11201     // the case of a store, it's not worth it if the index is a constant 0,
11202     // because a MOVSSmr can be used instead, which is smaller and faster.
11203     if (!Op.hasOneUse())
11204       return SDValue();
11205     SDNode *User = *Op.getNode()->use_begin();
11206     if ((User->getOpcode() != ISD::STORE ||
11207          (isa<ConstantSDNode>(Op.getOperand(1)) &&
11208           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11209         (User->getOpcode() != ISD::BITCAST ||
11210          User->getValueType(0) != MVT::i32))
11211       return SDValue();
11212     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11213                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11214                                   Op.getOperand(1));
11215     return DAG.getBitcast(MVT::f32, Extract);
11216   }
11217
11218   if (VT == MVT::i32 || VT == MVT::i64) {
11219     // ExtractPS/pextrq works with constant index.
11220     if (isa<ConstantSDNode>(Op.getOperand(1)))
11221       return Op;
11222   }
11223   return SDValue();
11224 }
11225
11226 /// Extract one bit from mask vector, like v16i1 or v8i1.
11227 /// AVX-512 feature.
11228 SDValue
11229 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11230   SDValue Vec = Op.getOperand(0);
11231   SDLoc dl(Vec);
11232   MVT VecVT = Vec.getSimpleValueType();
11233   SDValue Idx = Op.getOperand(1);
11234   MVT EltVT = Op.getSimpleValueType();
11235
11236   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11237   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11238          "Unexpected vector type in ExtractBitFromMaskVector");
11239
11240   // variable index can't be handled in mask registers,
11241   // extend vector to VR512
11242   if (!isa<ConstantSDNode>(Idx)) {
11243     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11244     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11245     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11246                               ExtVT.getVectorElementType(), Ext, Idx);
11247     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11248   }
11249
11250   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11251   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11252   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11253     rc = getRegClassFor(MVT::v16i1);
11254   unsigned MaxSift = rc->getSize()*8 - 1;
11255   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11256                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11257   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11258                     DAG.getConstant(MaxSift, dl, MVT::i8));
11259   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11260                        DAG.getIntPtrConstant(0, dl));
11261 }
11262
11263 SDValue
11264 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11265                                            SelectionDAG &DAG) const {
11266   SDLoc dl(Op);
11267   SDValue Vec = Op.getOperand(0);
11268   MVT VecVT = Vec.getSimpleValueType();
11269   SDValue Idx = Op.getOperand(1);
11270
11271   if (Op.getSimpleValueType() == MVT::i1)
11272     return ExtractBitFromMaskVector(Op, DAG);
11273
11274   if (!isa<ConstantSDNode>(Idx)) {
11275     if (VecVT.is512BitVector() ||
11276         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11277          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11278
11279       MVT MaskEltVT =
11280         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11281       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11282                                     MaskEltVT.getSizeInBits());
11283
11284       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11285       auto PtrVT = getPointerTy(DAG.getDataLayout());
11286       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11287                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11288                                  DAG.getConstant(0, dl, PtrVT));
11289       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11290       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11291                          DAG.getConstant(0, dl, PtrVT));
11292     }
11293     return SDValue();
11294   }
11295
11296   // If this is a 256-bit vector result, first extract the 128-bit vector and
11297   // then extract the element from the 128-bit vector.
11298   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11299
11300     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11301     // Get the 128-bit vector.
11302     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11303     MVT EltVT = VecVT.getVectorElementType();
11304
11305     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11306
11307     //if (IdxVal >= NumElems/2)
11308     //  IdxVal -= NumElems/2;
11309     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
11310     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11311                        DAG.getConstant(IdxVal, dl, MVT::i32));
11312   }
11313
11314   assert(VecVT.is128BitVector() && "Unexpected vector length");
11315
11316   if (Subtarget->hasSSE41())
11317     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11318       return Res;
11319
11320   MVT VT = Op.getSimpleValueType();
11321   // TODO: handle v16i8.
11322   if (VT.getSizeInBits() == 16) {
11323     SDValue Vec = Op.getOperand(0);
11324     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11325     if (Idx == 0)
11326       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11327                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11328                                      DAG.getBitcast(MVT::v4i32, Vec),
11329                                      Op.getOperand(1)));
11330     // Transform it so it match pextrw which produces a 32-bit result.
11331     MVT EltVT = MVT::i32;
11332     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11333                                   Op.getOperand(0), Op.getOperand(1));
11334     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11335                                   DAG.getValueType(VT));
11336     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11337   }
11338
11339   if (VT.getSizeInBits() == 32) {
11340     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11341     if (Idx == 0)
11342       return Op;
11343
11344     // SHUFPS the element to the lowest double word, then movss.
11345     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11346     MVT VVT = Op.getOperand(0).getSimpleValueType();
11347     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11348                                        DAG.getUNDEF(VVT), Mask);
11349     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11350                        DAG.getIntPtrConstant(0, dl));
11351   }
11352
11353   if (VT.getSizeInBits() == 64) {
11354     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11355     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11356     //        to match extract_elt for f64.
11357     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11358     if (Idx == 0)
11359       return Op;
11360
11361     // UNPCKHPD the element to the lowest double word, then movsd.
11362     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11363     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11364     int Mask[2] = { 1, -1 };
11365     MVT VVT = Op.getOperand(0).getSimpleValueType();
11366     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11367                                        DAG.getUNDEF(VVT), Mask);
11368     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11369                        DAG.getIntPtrConstant(0, dl));
11370   }
11371
11372   return SDValue();
11373 }
11374
11375 /// Insert one bit to mask vector, like v16i1 or v8i1.
11376 /// AVX-512 feature.
11377 SDValue
11378 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11379   SDLoc dl(Op);
11380   SDValue Vec = Op.getOperand(0);
11381   SDValue Elt = Op.getOperand(1);
11382   SDValue Idx = Op.getOperand(2);
11383   MVT VecVT = Vec.getSimpleValueType();
11384
11385   if (!isa<ConstantSDNode>(Idx)) {
11386     // Non constant index. Extend source and destination,
11387     // insert element and then truncate the result.
11388     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11389     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11390     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11391       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11392       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11393     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11394   }
11395
11396   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11397   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11398   if (IdxVal)
11399     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11400                            DAG.getConstant(IdxVal, dl, MVT::i8));
11401   if (Vec.getOpcode() == ISD::UNDEF)
11402     return EltInVec;
11403   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11404 }
11405
11406 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11407                                                   SelectionDAG &DAG) const {
11408   MVT VT = Op.getSimpleValueType();
11409   MVT EltVT = VT.getVectorElementType();
11410
11411   if (EltVT == MVT::i1)
11412     return InsertBitToMaskVector(Op, DAG);
11413
11414   SDLoc dl(Op);
11415   SDValue N0 = Op.getOperand(0);
11416   SDValue N1 = Op.getOperand(1);
11417   SDValue N2 = Op.getOperand(2);
11418   if (!isa<ConstantSDNode>(N2))
11419     return SDValue();
11420   auto *N2C = cast<ConstantSDNode>(N2);
11421   unsigned IdxVal = N2C->getZExtValue();
11422
11423   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11424   // into that, and then insert the subvector back into the result.
11425   if (VT.is256BitVector() || VT.is512BitVector()) {
11426     // With a 256-bit vector, we can insert into the zero element efficiently
11427     // using a blend if we have AVX or AVX2 and the right data type.
11428     if (VT.is256BitVector() && IdxVal == 0) {
11429       // TODO: It is worthwhile to cast integer to floating point and back
11430       // and incur a domain crossing penalty if that's what we'll end up
11431       // doing anyway after extracting to a 128-bit vector.
11432       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11433           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11434         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11435         N2 = DAG.getIntPtrConstant(1, dl);
11436         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11437       }
11438     }
11439
11440     // Get the desired 128-bit vector chunk.
11441     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11442
11443     // Insert the element into the desired chunk.
11444     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11445     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11446
11447     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11448                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11449
11450     // Insert the changed part back into the bigger vector
11451     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11452   }
11453   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11454
11455   if (Subtarget->hasSSE41()) {
11456     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11457       unsigned Opc;
11458       if (VT == MVT::v8i16) {
11459         Opc = X86ISD::PINSRW;
11460       } else {
11461         assert(VT == MVT::v16i8);
11462         Opc = X86ISD::PINSRB;
11463       }
11464
11465       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11466       // argument.
11467       if (N1.getValueType() != MVT::i32)
11468         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11469       if (N2.getValueType() != MVT::i32)
11470         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11471       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11472     }
11473
11474     if (EltVT == MVT::f32) {
11475       // Bits [7:6] of the constant are the source select. This will always be
11476       //   zero here. The DAG Combiner may combine an extract_elt index into
11477       //   these bits. For example (insert (extract, 3), 2) could be matched by
11478       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11479       // Bits [5:4] of the constant are the destination select. This is the
11480       //   value of the incoming immediate.
11481       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11482       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11483
11484       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11485       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11486         // If this is an insertion of 32-bits into the low 32-bits of
11487         // a vector, we prefer to generate a blend with immediate rather
11488         // than an insertps. Blends are simpler operations in hardware and so
11489         // will always have equal or better performance than insertps.
11490         // But if optimizing for size and there's a load folding opportunity,
11491         // generate insertps because blendps does not have a 32-bit memory
11492         // operand form.
11493         N2 = DAG.getIntPtrConstant(1, dl);
11494         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11495         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11496       }
11497       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11498       // Create this as a scalar to vector..
11499       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11500       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11501     }
11502
11503     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11504       // PINSR* works with constant index.
11505       return Op;
11506     }
11507   }
11508
11509   if (EltVT == MVT::i8)
11510     return SDValue();
11511
11512   if (EltVT.getSizeInBits() == 16) {
11513     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11514     // as its second argument.
11515     if (N1.getValueType() != MVT::i32)
11516       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11517     if (N2.getValueType() != MVT::i32)
11518       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11519     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11520   }
11521   return SDValue();
11522 }
11523
11524 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11525   SDLoc dl(Op);
11526   MVT OpVT = Op.getSimpleValueType();
11527
11528   // If this is a 256-bit vector result, first insert into a 128-bit
11529   // vector and then insert into the 256-bit vector.
11530   if (!OpVT.is128BitVector()) {
11531     // Insert into a 128-bit vector.
11532     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11533     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11534                                  OpVT.getVectorNumElements() / SizeFactor);
11535
11536     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11537
11538     // Insert the 128-bit vector.
11539     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11540   }
11541
11542   if (OpVT == MVT::v1i64 &&
11543       Op.getOperand(0).getValueType() == MVT::i64)
11544     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11545
11546   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11547   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11548   return DAG.getBitcast(
11549       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11550 }
11551
11552 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11553 // a simple subregister reference or explicit instructions to grab
11554 // upper bits of a vector.
11555 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11556                                       SelectionDAG &DAG) {
11557   SDLoc dl(Op);
11558   SDValue In =  Op.getOperand(0);
11559   SDValue Idx = Op.getOperand(1);
11560   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11561   MVT ResVT   = Op.getSimpleValueType();
11562   MVT InVT    = In.getSimpleValueType();
11563
11564   if (Subtarget->hasFp256()) {
11565     if (ResVT.is128BitVector() &&
11566         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11567         isa<ConstantSDNode>(Idx)) {
11568       return Extract128BitVector(In, IdxVal, DAG, dl);
11569     }
11570     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11571         isa<ConstantSDNode>(Idx)) {
11572       return Extract256BitVector(In, IdxVal, DAG, dl);
11573     }
11574   }
11575   return SDValue();
11576 }
11577
11578 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11579 // simple superregister reference or explicit instructions to insert
11580 // the upper bits of a vector.
11581 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11582                                      SelectionDAG &DAG) {
11583   if (!Subtarget->hasAVX())
11584     return SDValue();
11585
11586   SDLoc dl(Op);
11587   SDValue Vec = Op.getOperand(0);
11588   SDValue SubVec = Op.getOperand(1);
11589   SDValue Idx = Op.getOperand(2);
11590
11591   if (!isa<ConstantSDNode>(Idx))
11592     return SDValue();
11593
11594   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11595   MVT OpVT = Op.getSimpleValueType();
11596   MVT SubVecVT = SubVec.getSimpleValueType();
11597
11598   // Fold two 16-byte subvector loads into one 32-byte load:
11599   // (insert_subvector (insert_subvector undef, (load addr), 0),
11600   //                   (load addr + 16), Elts/2)
11601   // --> load32 addr
11602   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11603       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11604       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11605     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11606     if (Idx2 && Idx2->getZExtValue() == 0) {
11607       SDValue SubVec2 = Vec.getOperand(1);
11608       // If needed, look through a bitcast to get to the load.
11609       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11610         SubVec2 = SubVec2.getOperand(0);
11611
11612       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11613         bool Fast;
11614         unsigned Alignment = FirstLd->getAlignment();
11615         unsigned AS = FirstLd->getAddressSpace();
11616         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11617         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11618                                     OpVT, AS, Alignment, &Fast) && Fast) {
11619           SDValue Ops[] = { SubVec2, SubVec };
11620           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11621             return Ld;
11622         }
11623       }
11624     }
11625   }
11626
11627   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11628       SubVecVT.is128BitVector())
11629     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11630
11631   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11632     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11633
11634   if (OpVT.getVectorElementType() == MVT::i1) {
11635     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11636       return Op;
11637     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11638     SDValue Undef = DAG.getUNDEF(OpVT);
11639     unsigned NumElems = OpVT.getVectorNumElements();
11640     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11641
11642     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11643       // Zero upper bits of the Vec
11644       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11645       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11646
11647       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11648                                  SubVec, ZeroIdx);
11649       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11650       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11651     }
11652     if (IdxVal == 0) {
11653       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11654                                  SubVec, ZeroIdx);
11655       // Zero upper bits of the Vec2
11656       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11657       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11658       // Zero lower bits of the Vec
11659       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11660       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11661       // Merge them together
11662       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11663     }
11664   }
11665   return SDValue();
11666 }
11667
11668 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11669 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11670 // one of the above mentioned nodes. It has to be wrapped because otherwise
11671 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11672 // be used to form addressing mode. These wrapped nodes will be selected
11673 // into MOV32ri.
11674 SDValue
11675 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11676   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11677
11678   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11679   // global base reg.
11680   unsigned char OpFlag = 0;
11681   unsigned WrapperKind = X86ISD::Wrapper;
11682   CodeModel::Model M = DAG.getTarget().getCodeModel();
11683
11684   if (Subtarget->isPICStyleRIPRel() &&
11685       (M == CodeModel::Small || M == CodeModel::Kernel))
11686     WrapperKind = X86ISD::WrapperRIP;
11687   else if (Subtarget->isPICStyleGOT())
11688     OpFlag = X86II::MO_GOTOFF;
11689   else if (Subtarget->isPICStyleStubPIC())
11690     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11691
11692   auto PtrVT = getPointerTy(DAG.getDataLayout());
11693   SDValue Result = DAG.getTargetConstantPool(
11694       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11695   SDLoc DL(CP);
11696   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11697   // With PIC, the address is actually $g + Offset.
11698   if (OpFlag) {
11699     Result =
11700         DAG.getNode(ISD::ADD, DL, PtrVT,
11701                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11702   }
11703
11704   return Result;
11705 }
11706
11707 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11708   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11709
11710   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11711   // global base reg.
11712   unsigned char OpFlag = 0;
11713   unsigned WrapperKind = X86ISD::Wrapper;
11714   CodeModel::Model M = DAG.getTarget().getCodeModel();
11715
11716   if (Subtarget->isPICStyleRIPRel() &&
11717       (M == CodeModel::Small || M == CodeModel::Kernel))
11718     WrapperKind = X86ISD::WrapperRIP;
11719   else if (Subtarget->isPICStyleGOT())
11720     OpFlag = X86II::MO_GOTOFF;
11721   else if (Subtarget->isPICStyleStubPIC())
11722     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11723
11724   auto PtrVT = getPointerTy(DAG.getDataLayout());
11725   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11726   SDLoc DL(JT);
11727   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11728
11729   // With PIC, the address is actually $g + Offset.
11730   if (OpFlag)
11731     Result =
11732         DAG.getNode(ISD::ADD, DL, PtrVT,
11733                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11734
11735   return Result;
11736 }
11737
11738 SDValue
11739 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11740   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11741
11742   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11743   // global base reg.
11744   unsigned char OpFlag = 0;
11745   unsigned WrapperKind = X86ISD::Wrapper;
11746   CodeModel::Model M = DAG.getTarget().getCodeModel();
11747
11748   if (Subtarget->isPICStyleRIPRel() &&
11749       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11750     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11751       OpFlag = X86II::MO_GOTPCREL;
11752     WrapperKind = X86ISD::WrapperRIP;
11753   } else if (Subtarget->isPICStyleGOT()) {
11754     OpFlag = X86II::MO_GOT;
11755   } else if (Subtarget->isPICStyleStubPIC()) {
11756     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11757   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11758     OpFlag = X86II::MO_DARWIN_NONLAZY;
11759   }
11760
11761   auto PtrVT = getPointerTy(DAG.getDataLayout());
11762   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11763
11764   SDLoc DL(Op);
11765   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11766
11767   // With PIC, the address is actually $g + Offset.
11768   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11769       !Subtarget->is64Bit()) {
11770     Result =
11771         DAG.getNode(ISD::ADD, DL, PtrVT,
11772                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11773   }
11774
11775   // For symbols that require a load from a stub to get the address, emit the
11776   // load.
11777   if (isGlobalStubReference(OpFlag))
11778     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11779                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11780                          false, false, false, 0);
11781
11782   return Result;
11783 }
11784
11785 SDValue
11786 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11787   // Create the TargetBlockAddressAddress node.
11788   unsigned char OpFlags =
11789     Subtarget->ClassifyBlockAddressReference();
11790   CodeModel::Model M = DAG.getTarget().getCodeModel();
11791   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11792   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11793   SDLoc dl(Op);
11794   auto PtrVT = getPointerTy(DAG.getDataLayout());
11795   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11796
11797   if (Subtarget->isPICStyleRIPRel() &&
11798       (M == CodeModel::Small || M == CodeModel::Kernel))
11799     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11800   else
11801     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11802
11803   // With PIC, the address is actually $g + Offset.
11804   if (isGlobalRelativeToPICBase(OpFlags)) {
11805     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11806                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11807   }
11808
11809   return Result;
11810 }
11811
11812 SDValue
11813 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11814                                       int64_t Offset, SelectionDAG &DAG) const {
11815   // Create the TargetGlobalAddress node, folding in the constant
11816   // offset if it is legal.
11817   unsigned char OpFlags =
11818       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11819   CodeModel::Model M = DAG.getTarget().getCodeModel();
11820   auto PtrVT = getPointerTy(DAG.getDataLayout());
11821   SDValue Result;
11822   if (OpFlags == X86II::MO_NO_FLAG &&
11823       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11824     // A direct static reference to a global.
11825     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11826     Offset = 0;
11827   } else {
11828     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11829   }
11830
11831   if (Subtarget->isPICStyleRIPRel() &&
11832       (M == CodeModel::Small || M == CodeModel::Kernel))
11833     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11834   else
11835     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11836
11837   // With PIC, the address is actually $g + Offset.
11838   if (isGlobalRelativeToPICBase(OpFlags)) {
11839     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11840                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11841   }
11842
11843   // For globals that require a load from a stub to get the address, emit the
11844   // load.
11845   if (isGlobalStubReference(OpFlags))
11846     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11847                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11848                          false, false, false, 0);
11849
11850   // If there was a non-zero offset that we didn't fold, create an explicit
11851   // addition for it.
11852   if (Offset != 0)
11853     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11854                          DAG.getConstant(Offset, dl, PtrVT));
11855
11856   return Result;
11857 }
11858
11859 SDValue
11860 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11861   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11862   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11863   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11864 }
11865
11866 static SDValue
11867 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11868            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11869            unsigned char OperandFlags, bool LocalDynamic = false) {
11870   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11871   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11872   SDLoc dl(GA);
11873   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11874                                            GA->getValueType(0),
11875                                            GA->getOffset(),
11876                                            OperandFlags);
11877
11878   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11879                                            : X86ISD::TLSADDR;
11880
11881   if (InFlag) {
11882     SDValue Ops[] = { Chain,  TGA, *InFlag };
11883     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11884   } else {
11885     SDValue Ops[]  = { Chain, TGA };
11886     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11887   }
11888
11889   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11890   MFI->setAdjustsStack(true);
11891   MFI->setHasCalls(true);
11892
11893   SDValue Flag = Chain.getValue(1);
11894   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11895 }
11896
11897 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11898 static SDValue
11899 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11900                                 const EVT PtrVT) {
11901   SDValue InFlag;
11902   SDLoc dl(GA);  // ? function entry point might be better
11903   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11904                                    DAG.getNode(X86ISD::GlobalBaseReg,
11905                                                SDLoc(), PtrVT), InFlag);
11906   InFlag = Chain.getValue(1);
11907
11908   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11909 }
11910
11911 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11912 static SDValue
11913 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11914                                 const EVT PtrVT) {
11915   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11916                     X86::RAX, X86II::MO_TLSGD);
11917 }
11918
11919 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11920                                            SelectionDAG &DAG,
11921                                            const EVT PtrVT,
11922                                            bool is64Bit) {
11923   SDLoc dl(GA);
11924
11925   // Get the start address of the TLS block for this module.
11926   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11927       .getInfo<X86MachineFunctionInfo>();
11928   MFI->incNumLocalDynamicTLSAccesses();
11929
11930   SDValue Base;
11931   if (is64Bit) {
11932     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11933                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11934   } else {
11935     SDValue InFlag;
11936     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11937         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11938     InFlag = Chain.getValue(1);
11939     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11940                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11941   }
11942
11943   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11944   // of Base.
11945
11946   // Build x@dtpoff.
11947   unsigned char OperandFlags = X86II::MO_DTPOFF;
11948   unsigned WrapperKind = X86ISD::Wrapper;
11949   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11950                                            GA->getValueType(0),
11951                                            GA->getOffset(), OperandFlags);
11952   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11953
11954   // Add x@dtpoff with the base.
11955   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11956 }
11957
11958 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11959 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11960                                    const EVT PtrVT, TLSModel::Model model,
11961                                    bool is64Bit, bool isPIC) {
11962   SDLoc dl(GA);
11963
11964   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11965   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11966                                                          is64Bit ? 257 : 256));
11967
11968   SDValue ThreadPointer =
11969       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11970                   MachinePointerInfo(Ptr), false, false, false, 0);
11971
11972   unsigned char OperandFlags = 0;
11973   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11974   // initialexec.
11975   unsigned WrapperKind = X86ISD::Wrapper;
11976   if (model == TLSModel::LocalExec) {
11977     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11978   } else if (model == TLSModel::InitialExec) {
11979     if (is64Bit) {
11980       OperandFlags = X86II::MO_GOTTPOFF;
11981       WrapperKind = X86ISD::WrapperRIP;
11982     } else {
11983       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11984     }
11985   } else {
11986     llvm_unreachable("Unexpected model");
11987   }
11988
11989   // emit "addl x@ntpoff,%eax" (local exec)
11990   // or "addl x@indntpoff,%eax" (initial exec)
11991   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11992   SDValue TGA =
11993       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11994                                  GA->getOffset(), OperandFlags);
11995   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11996
11997   if (model == TLSModel::InitialExec) {
11998     if (isPIC && !is64Bit) {
11999       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12000                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12001                            Offset);
12002     }
12003
12004     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12005                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12006                          false, false, false, 0);
12007   }
12008
12009   // The address of the thread local variable is the add of the thread
12010   // pointer with the offset of the variable.
12011   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12012 }
12013
12014 SDValue
12015 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12016
12017   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12018   const GlobalValue *GV = GA->getGlobal();
12019   auto PtrVT = getPointerTy(DAG.getDataLayout());
12020
12021   if (Subtarget->isTargetELF()) {
12022     if (DAG.getTarget().Options.EmulatedTLS)
12023       return LowerToTLSEmulatedModel(GA, DAG);
12024     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12025     switch (model) {
12026       case TLSModel::GeneralDynamic:
12027         if (Subtarget->is64Bit())
12028           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12029         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12030       case TLSModel::LocalDynamic:
12031         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12032                                            Subtarget->is64Bit());
12033       case TLSModel::InitialExec:
12034       case TLSModel::LocalExec:
12035         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12036                                    DAG.getTarget().getRelocationModel() ==
12037                                        Reloc::PIC_);
12038     }
12039     llvm_unreachable("Unknown TLS model.");
12040   }
12041
12042   if (Subtarget->isTargetDarwin()) {
12043     // Darwin only has one model of TLS.  Lower to that.
12044     unsigned char OpFlag = 0;
12045     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12046                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12047
12048     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12049     // global base reg.
12050     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12051                  !Subtarget->is64Bit();
12052     if (PIC32)
12053       OpFlag = X86II::MO_TLVP_PIC_BASE;
12054     else
12055       OpFlag = X86II::MO_TLVP;
12056     SDLoc DL(Op);
12057     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12058                                                 GA->getValueType(0),
12059                                                 GA->getOffset(), OpFlag);
12060     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12061
12062     // With PIC32, the address is actually $g + Offset.
12063     if (PIC32)
12064       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12065                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12066                            Offset);
12067
12068     // Lowering the machine isd will make sure everything is in the right
12069     // location.
12070     SDValue Chain = DAG.getEntryNode();
12071     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12072     SDValue Args[] = { Chain, Offset };
12073     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12074
12075     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12076     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12077     MFI->setAdjustsStack(true);
12078
12079     // And our return value (tls address) is in the standard call return value
12080     // location.
12081     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12082     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12083   }
12084
12085   if (Subtarget->isTargetKnownWindowsMSVC() ||
12086       Subtarget->isTargetWindowsGNU()) {
12087     // Just use the implicit TLS architecture
12088     // Need to generate someting similar to:
12089     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12090     //                                  ; from TEB
12091     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12092     //   mov     rcx, qword [rdx+rcx*8]
12093     //   mov     eax, .tls$:tlsvar
12094     //   [rax+rcx] contains the address
12095     // Windows 64bit: gs:0x58
12096     // Windows 32bit: fs:__tls_array
12097
12098     SDLoc dl(GA);
12099     SDValue Chain = DAG.getEntryNode();
12100
12101     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12102     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12103     // use its literal value of 0x2C.
12104     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12105                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12106                                                              256)
12107                                         : Type::getInt32PtrTy(*DAG.getContext(),
12108                                                               257));
12109
12110     SDValue TlsArray = Subtarget->is64Bit()
12111                            ? DAG.getIntPtrConstant(0x58, dl)
12112                            : (Subtarget->isTargetWindowsGNU()
12113                                   ? DAG.getIntPtrConstant(0x2C, dl)
12114                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12115
12116     SDValue ThreadPointer =
12117         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12118                     false, false, 0);
12119
12120     SDValue res;
12121     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12122       res = ThreadPointer;
12123     } else {
12124       // Load the _tls_index variable
12125       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12126       if (Subtarget->is64Bit())
12127         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12128                              MachinePointerInfo(), MVT::i32, false, false,
12129                              false, 0);
12130       else
12131         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12132                           false, false, 0);
12133
12134       auto &DL = DAG.getDataLayout();
12135       SDValue Scale =
12136           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12137       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12138
12139       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12140     }
12141
12142     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12143                       false, 0);
12144
12145     // Get the offset of start of .tls section
12146     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12147                                              GA->getValueType(0),
12148                                              GA->getOffset(), X86II::MO_SECREL);
12149     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12150
12151     // The address of the thread local variable is the add of the thread
12152     // pointer with the offset of the variable.
12153     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12154   }
12155
12156   llvm_unreachable("TLS not implemented for this target.");
12157 }
12158
12159 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12160 /// and take a 2 x i32 value to shift plus a shift amount.
12161 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12162   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12163   MVT VT = Op.getSimpleValueType();
12164   unsigned VTBits = VT.getSizeInBits();
12165   SDLoc dl(Op);
12166   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12167   SDValue ShOpLo = Op.getOperand(0);
12168   SDValue ShOpHi = Op.getOperand(1);
12169   SDValue ShAmt  = Op.getOperand(2);
12170   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12171   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12172   // during isel.
12173   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12174                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12175   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12176                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12177                        : DAG.getConstant(0, dl, VT);
12178
12179   SDValue Tmp2, Tmp3;
12180   if (Op.getOpcode() == ISD::SHL_PARTS) {
12181     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12182     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12183   } else {
12184     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12185     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12186   }
12187
12188   // If the shift amount is larger or equal than the width of a part we can't
12189   // rely on the results of shld/shrd. Insert a test and select the appropriate
12190   // values for large shift amounts.
12191   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12192                                 DAG.getConstant(VTBits, dl, MVT::i8));
12193   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12194                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12195
12196   SDValue Hi, Lo;
12197   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12198   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12199   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12200
12201   if (Op.getOpcode() == ISD::SHL_PARTS) {
12202     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12203     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12204   } else {
12205     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12206     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12207   }
12208
12209   SDValue Ops[2] = { Lo, Hi };
12210   return DAG.getMergeValues(Ops, dl);
12211 }
12212
12213 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12214                                            SelectionDAG &DAG) const {
12215   SDValue Src = Op.getOperand(0);
12216   MVT SrcVT = Src.getSimpleValueType();
12217   MVT VT = Op.getSimpleValueType();
12218   SDLoc dl(Op);
12219
12220   if (SrcVT.isVector()) {
12221     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12222       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12223                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12224                          DAG.getUNDEF(SrcVT)));
12225     }
12226     if (SrcVT.getVectorElementType() == MVT::i1) {
12227       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12228       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12229                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12230     }
12231     return SDValue();
12232   }
12233
12234   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12235          "Unknown SINT_TO_FP to lower!");
12236
12237   // These are really Legal; return the operand so the caller accepts it as
12238   // Legal.
12239   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12240     return Op;
12241   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12242       Subtarget->is64Bit()) {
12243     return Op;
12244   }
12245
12246   unsigned Size = SrcVT.getSizeInBits()/8;
12247   MachineFunction &MF = DAG.getMachineFunction();
12248   auto PtrVT = getPointerTy(MF.getDataLayout());
12249   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12250   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12251   SDValue Chain = DAG.getStore(
12252       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12253       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12254       false, 0);
12255   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12256 }
12257
12258 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12259                                      SDValue StackSlot,
12260                                      SelectionDAG &DAG) const {
12261   // Build the FILD
12262   SDLoc DL(Op);
12263   SDVTList Tys;
12264   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12265   if (useSSE)
12266     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12267   else
12268     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12269
12270   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12271
12272   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12273   MachineMemOperand *MMO;
12274   if (FI) {
12275     int SSFI = FI->getIndex();
12276     MMO = DAG.getMachineFunction().getMachineMemOperand(
12277         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12278         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12279   } else {
12280     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12281     StackSlot = StackSlot.getOperand(1);
12282   }
12283   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12284   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12285                                            X86ISD::FILD, DL,
12286                                            Tys, Ops, SrcVT, MMO);
12287
12288   if (useSSE) {
12289     Chain = Result.getValue(1);
12290     SDValue InFlag = Result.getValue(2);
12291
12292     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12293     // shouldn't be necessary except that RFP cannot be live across
12294     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12295     MachineFunction &MF = DAG.getMachineFunction();
12296     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12297     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12298     auto PtrVT = getPointerTy(MF.getDataLayout());
12299     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12300     Tys = DAG.getVTList(MVT::Other);
12301     SDValue Ops[] = {
12302       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12303     };
12304     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12305         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12306         MachineMemOperand::MOStore, SSFISize, SSFISize);
12307
12308     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12309                                     Ops, Op.getValueType(), MMO);
12310     Result = DAG.getLoad(
12311         Op.getValueType(), DL, Chain, StackSlot,
12312         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12313         false, false, false, 0);
12314   }
12315
12316   return Result;
12317 }
12318
12319 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12320 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12321                                                SelectionDAG &DAG) const {
12322   // This algorithm is not obvious. Here it is what we're trying to output:
12323   /*
12324      movq       %rax,  %xmm0
12325      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12326      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12327      #ifdef __SSE3__
12328        haddpd   %xmm0, %xmm0
12329      #else
12330        pshufd   $0x4e, %xmm0, %xmm1
12331        addpd    %xmm1, %xmm0
12332      #endif
12333   */
12334
12335   SDLoc dl(Op);
12336   LLVMContext *Context = DAG.getContext();
12337
12338   // Build some magic constants.
12339   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12340   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12341   auto PtrVT = getPointerTy(DAG.getDataLayout());
12342   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12343
12344   SmallVector<Constant*,2> CV1;
12345   CV1.push_back(
12346     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12347                                       APInt(64, 0x4330000000000000ULL))));
12348   CV1.push_back(
12349     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12350                                       APInt(64, 0x4530000000000000ULL))));
12351   Constant *C1 = ConstantVector::get(CV1);
12352   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12353
12354   // Load the 64-bit value into an XMM register.
12355   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12356                             Op.getOperand(0));
12357   SDValue CLod0 =
12358       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12359                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12360                   false, false, false, 16);
12361   SDValue Unpck1 =
12362       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12363
12364   SDValue CLod1 =
12365       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12366                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12367                   false, false, false, 16);
12368   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12369   // TODO: Are there any fast-math-flags to propagate here?
12370   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12371   SDValue Result;
12372
12373   if (Subtarget->hasSSE3()) {
12374     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12375     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12376   } else {
12377     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12378     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12379                                            S2F, 0x4E, DAG);
12380     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12381                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12382   }
12383
12384   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12385                      DAG.getIntPtrConstant(0, dl));
12386 }
12387
12388 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12389 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12390                                                SelectionDAG &DAG) const {
12391   SDLoc dl(Op);
12392   // FP constant to bias correct the final result.
12393   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12394                                    MVT::f64);
12395
12396   // Load the 32-bit value into an XMM register.
12397   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12398                              Op.getOperand(0));
12399
12400   // Zero out the upper parts of the register.
12401   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12402
12403   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12404                      DAG.getBitcast(MVT::v2f64, Load),
12405                      DAG.getIntPtrConstant(0, dl));
12406
12407   // Or the load with the bias.
12408   SDValue Or = DAG.getNode(
12409       ISD::OR, dl, MVT::v2i64,
12410       DAG.getBitcast(MVT::v2i64,
12411                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12412       DAG.getBitcast(MVT::v2i64,
12413                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12414   Or =
12415       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12416                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12417
12418   // Subtract the bias.
12419   // TODO: Are there any fast-math-flags to propagate here?
12420   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12421
12422   // Handle final rounding.
12423   EVT DestVT = Op.getValueType();
12424
12425   if (DestVT.bitsLT(MVT::f64))
12426     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12427                        DAG.getIntPtrConstant(0, dl));
12428   if (DestVT.bitsGT(MVT::f64))
12429     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12430
12431   // Handle final rounding.
12432   return Sub;
12433 }
12434
12435 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12436                                      const X86Subtarget &Subtarget) {
12437   // The algorithm is the following:
12438   // #ifdef __SSE4_1__
12439   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12440   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12441   //                                 (uint4) 0x53000000, 0xaa);
12442   // #else
12443   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12444   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12445   // #endif
12446   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12447   //     return (float4) lo + fhi;
12448
12449   SDLoc DL(Op);
12450   SDValue V = Op->getOperand(0);
12451   EVT VecIntVT = V.getValueType();
12452   bool Is128 = VecIntVT == MVT::v4i32;
12453   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12454   // If we convert to something else than the supported type, e.g., to v4f64,
12455   // abort early.
12456   if (VecFloatVT != Op->getValueType(0))
12457     return SDValue();
12458
12459   unsigned NumElts = VecIntVT.getVectorNumElements();
12460   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12461          "Unsupported custom type");
12462   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12463
12464   // In the #idef/#else code, we have in common:
12465   // - The vector of constants:
12466   // -- 0x4b000000
12467   // -- 0x53000000
12468   // - A shift:
12469   // -- v >> 16
12470
12471   // Create the splat vector for 0x4b000000.
12472   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12473   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12474                            CstLow, CstLow, CstLow, CstLow};
12475   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12476                                   makeArrayRef(&CstLowArray[0], NumElts));
12477   // Create the splat vector for 0x53000000.
12478   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12479   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12480                             CstHigh, CstHigh, CstHigh, CstHigh};
12481   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12482                                    makeArrayRef(&CstHighArray[0], NumElts));
12483
12484   // Create the right shift.
12485   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12486   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12487                              CstShift, CstShift, CstShift, CstShift};
12488   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12489                                     makeArrayRef(&CstShiftArray[0], NumElts));
12490   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12491
12492   SDValue Low, High;
12493   if (Subtarget.hasSSE41()) {
12494     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12495     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12496     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12497     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12498     // Low will be bitcasted right away, so do not bother bitcasting back to its
12499     // original type.
12500     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12501                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12502     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12503     //                                 (uint4) 0x53000000, 0xaa);
12504     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12505     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12506     // High will be bitcasted right away, so do not bother bitcasting back to
12507     // its original type.
12508     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12509                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12510   } else {
12511     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12512     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12513                                      CstMask, CstMask, CstMask);
12514     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12515     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12516     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12517
12518     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12519     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12520   }
12521
12522   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12523   SDValue CstFAdd = DAG.getConstantFP(
12524       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12525   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12526                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12527   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12528                                    makeArrayRef(&CstFAddArray[0], NumElts));
12529
12530   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12531   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12532   // TODO: Are there any fast-math-flags to propagate here?
12533   SDValue FHigh =
12534       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12535   //     return (float4) lo + fhi;
12536   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12537   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12538 }
12539
12540 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12541                                                SelectionDAG &DAG) const {
12542   SDValue N0 = Op.getOperand(0);
12543   MVT SVT = N0.getSimpleValueType();
12544   SDLoc dl(Op);
12545
12546   switch (SVT.SimpleTy) {
12547   default:
12548     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12549   case MVT::v4i8:
12550   case MVT::v4i16:
12551   case MVT::v8i8:
12552   case MVT::v8i16: {
12553     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12554     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12555                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12556   }
12557   case MVT::v4i32:
12558   case MVT::v8i32:
12559     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12560   case MVT::v16i8:
12561   case MVT::v16i16:
12562     if (Subtarget->hasAVX512())
12563       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12564                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12565   }
12566   llvm_unreachable(nullptr);
12567 }
12568
12569 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12570                                            SelectionDAG &DAG) const {
12571   SDValue N0 = Op.getOperand(0);
12572   SDLoc dl(Op);
12573   auto PtrVT = getPointerTy(DAG.getDataLayout());
12574
12575   if (Op.getValueType().isVector())
12576     return lowerUINT_TO_FP_vec(Op, DAG);
12577
12578   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12579   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12580   // the optimization here.
12581   if (DAG.SignBitIsZero(N0))
12582     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12583
12584   MVT SrcVT = N0.getSimpleValueType();
12585   MVT DstVT = Op.getSimpleValueType();
12586
12587   if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
12588       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
12589     // Conversions from unsigned i32 to f32/f64 are legal,
12590     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
12591     return Op;
12592   }
12593
12594   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12595     return LowerUINT_TO_FP_i64(Op, DAG);
12596   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12597     return LowerUINT_TO_FP_i32(Op, DAG);
12598   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12599     return SDValue();
12600
12601   // Make a 64-bit buffer, and use it to build an FILD.
12602   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12603   if (SrcVT == MVT::i32) {
12604     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12605     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12606     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12607                                   StackSlot, MachinePointerInfo(),
12608                                   false, false, 0);
12609     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12610                                   OffsetSlot, MachinePointerInfo(),
12611                                   false, false, 0);
12612     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12613     return Fild;
12614   }
12615
12616   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12617   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12618                                StackSlot, MachinePointerInfo(),
12619                                false, false, 0);
12620   // For i64 source, we need to add the appropriate power of 2 if the input
12621   // was negative.  This is the same as the optimization in
12622   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12623   // we must be careful to do the computation in x87 extended precision, not
12624   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12625   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12626   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12627       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12628       MachineMemOperand::MOLoad, 8, 8);
12629
12630   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12631   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12632   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12633                                          MVT::i64, MMO);
12634
12635   APInt FF(32, 0x5F800000ULL);
12636
12637   // Check whether the sign bit is set.
12638   SDValue SignSet = DAG.getSetCC(
12639       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12640       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12641
12642   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12643   SDValue FudgePtr = DAG.getConstantPool(
12644       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12645
12646   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12647   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12648   SDValue Four = DAG.getIntPtrConstant(4, dl);
12649   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12650                                Zero, Four);
12651   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12652
12653   // Load the value out, extending it from f32 to f80.
12654   // FIXME: Avoid the extend by constructing the right constant pool?
12655   SDValue Fudge = DAG.getExtLoad(
12656       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12657       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12658       false, false, false, 4);
12659   // Extend everything to 80 bits to force it to be done on x87.
12660   // TODO: Are there any fast-math-flags to propagate here?
12661   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12662   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12663                      DAG.getIntPtrConstant(0, dl));
12664 }
12665
12666 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12667 // is legal, or has an f16 source (which needs to be promoted to f32),
12668 // just return an <SDValue(), SDValue()> pair.
12669 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12670 // to i16, i32 or i64, and we lower it to a legal sequence.
12671 // If lowered to the final integer result we return a <result, SDValue()> pair.
12672 // Otherwise we lower it to a sequence ending with a FIST, return a
12673 // <FIST, StackSlot> pair, and the caller is responsible for loading
12674 // the final integer result from StackSlot.
12675 std::pair<SDValue,SDValue>
12676 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12677                                    bool IsSigned, bool IsReplace) const {
12678   SDLoc DL(Op);
12679
12680   EVT DstTy = Op.getValueType();
12681   EVT TheVT = Op.getOperand(0).getValueType();
12682   auto PtrVT = getPointerTy(DAG.getDataLayout());
12683
12684   if (TheVT == MVT::f16)
12685     // We need to promote the f16 to f32 before using the lowering
12686     // in this routine.
12687     return std::make_pair(SDValue(), SDValue());
12688
12689   assert((TheVT == MVT::f32 ||
12690           TheVT == MVT::f64 ||
12691           TheVT == MVT::f80) &&
12692          "Unexpected FP operand type in FP_TO_INTHelper");
12693
12694   // If using FIST to compute an unsigned i64, we'll need some fixup
12695   // to handle values above the maximum signed i64.  A FIST is always
12696   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12697   bool UnsignedFixup = !IsSigned &&
12698                        DstTy == MVT::i64 &&
12699                        (!Subtarget->is64Bit() ||
12700                         !isScalarFPTypeInSSEReg(TheVT));
12701
12702   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12703     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12704     // The low 32 bits of the fist result will have the correct uint32 result.
12705     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12706     DstTy = MVT::i64;
12707   }
12708
12709   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12710          DstTy.getSimpleVT() >= MVT::i16 &&
12711          "Unknown FP_TO_INT to lower!");
12712
12713   // These are really Legal.
12714   if (DstTy == MVT::i32 &&
12715       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12716     return std::make_pair(SDValue(), SDValue());
12717   if (Subtarget->is64Bit() &&
12718       DstTy == MVT::i64 &&
12719       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12720     return std::make_pair(SDValue(), SDValue());
12721
12722   // We lower FP->int64 into FISTP64 followed by a load from a temporary
12723   // stack slot.
12724   MachineFunction &MF = DAG.getMachineFunction();
12725   unsigned MemSize = DstTy.getSizeInBits()/8;
12726   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12727   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12728
12729   unsigned Opc;
12730   switch (DstTy.getSimpleVT().SimpleTy) {
12731   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12732   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12733   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12734   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12735   }
12736
12737   SDValue Chain = DAG.getEntryNode();
12738   SDValue Value = Op.getOperand(0);
12739   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12740
12741   if (UnsignedFixup) {
12742     //
12743     // Conversion to unsigned i64 is implemented with a select,
12744     // depending on whether the source value fits in the range
12745     // of a signed i64.  Let Thresh be the FP equivalent of
12746     // 0x8000000000000000ULL.
12747     //
12748     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12749     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
12750     //  Fist-to-mem64 FistSrc
12751     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12752     //  to XOR'ing the high 32 bits with Adjust.
12753     //
12754     // Being a power of 2, Thresh is exactly representable in all FP formats.
12755     // For X87 we'd like to use the smallest FP type for this constant, but
12756     // for DAG type consistency we have to match the FP operand type.
12757
12758     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12759     APFloat::opStatus Status = APFloat::opOK;
12760     bool LosesInfo = false;
12761     if (TheVT == MVT::f64)
12762       // The rounding mode is irrelevant as the conversion should be exact.
12763       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12764                               &LosesInfo);
12765     else if (TheVT == MVT::f80)
12766       Status = Thresh.convert(APFloat::x87DoubleExtended,
12767                               APFloat::rmNearestTiesToEven, &LosesInfo);
12768
12769     assert(Status == APFloat::opOK && !LosesInfo &&
12770            "FP conversion should have been exact");
12771
12772     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12773
12774     SDValue Cmp = DAG.getSetCC(DL,
12775                                getSetCCResultType(DAG.getDataLayout(),
12776                                                   *DAG.getContext(), TheVT),
12777                                Value, ThreshVal, ISD::SETLT);
12778     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12779                            DAG.getConstant(0, DL, MVT::i32),
12780                            DAG.getConstant(0x80000000, DL, MVT::i32));
12781     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12782     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12783                                               *DAG.getContext(), TheVT),
12784                        Value, ThreshVal, ISD::SETLT);
12785     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12786   }
12787
12788   // FIXME This causes a redundant load/store if the SSE-class value is already
12789   // in memory, such as if it is on the callstack.
12790   if (isScalarFPTypeInSSEReg(TheVT)) {
12791     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12792     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12793                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12794                          false, 0);
12795     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12796     SDValue Ops[] = {
12797       Chain, StackSlot, DAG.getValueType(TheVT)
12798     };
12799
12800     MachineMemOperand *MMO =
12801         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12802                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12803     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12804     Chain = Value.getValue(1);
12805     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12806     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12807   }
12808
12809   MachineMemOperand *MMO =
12810       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12811                               MachineMemOperand::MOStore, MemSize, MemSize);
12812
12813   if (UnsignedFixup) {
12814
12815     // Insert the FIST, load its result as two i32's,
12816     // and XOR the high i32 with Adjust.
12817
12818     SDValue FistOps[] = { Chain, Value, StackSlot };
12819     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12820                                            FistOps, DstTy, MMO);
12821
12822     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12823                                 MachinePointerInfo(),
12824                                 false, false, false, 0);
12825     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12826                                    DAG.getConstant(4, DL, PtrVT));
12827
12828     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12829                                  MachinePointerInfo(),
12830                                  false, false, false, 0);
12831     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12832
12833     if (Subtarget->is64Bit()) {
12834       // Join High32 and Low32 into a 64-bit result.
12835       // (High32 << 32) | Low32
12836       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12837       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12838       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12839                            DAG.getConstant(32, DL, MVT::i8));
12840       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12841       return std::make_pair(Result, SDValue());
12842     }
12843
12844     SDValue ResultOps[] = { Low32, High32 };
12845
12846     SDValue pair = IsReplace
12847       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12848       : DAG.getMergeValues(ResultOps, DL);
12849     return std::make_pair(pair, SDValue());
12850   } else {
12851     // Build the FP_TO_INT*_IN_MEM
12852     SDValue Ops[] = { Chain, Value, StackSlot };
12853     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12854                                            Ops, DstTy, MMO);
12855     return std::make_pair(FIST, StackSlot);
12856   }
12857 }
12858
12859 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12860                               const X86Subtarget *Subtarget) {
12861   MVT VT = Op->getSimpleValueType(0);
12862   SDValue In = Op->getOperand(0);
12863   MVT InVT = In.getSimpleValueType();
12864   SDLoc dl(Op);
12865
12866   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12867     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12868
12869   // Optimize vectors in AVX mode:
12870   //
12871   //   v8i16 -> v8i32
12872   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12873   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12874   //   Concat upper and lower parts.
12875   //
12876   //   v4i32 -> v4i64
12877   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12878   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12879   //   Concat upper and lower parts.
12880   //
12881
12882   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12883       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12884       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12885     return SDValue();
12886
12887   if (Subtarget->hasInt256())
12888     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12889
12890   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12891   SDValue Undef = DAG.getUNDEF(InVT);
12892   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12893   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12894   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12895
12896   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12897                              VT.getVectorNumElements()/2);
12898
12899   OpLo = DAG.getBitcast(HVT, OpLo);
12900   OpHi = DAG.getBitcast(HVT, OpHi);
12901
12902   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12903 }
12904
12905 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12906                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12907   MVT VT = Op->getSimpleValueType(0);
12908   SDValue In = Op->getOperand(0);
12909   MVT InVT = In.getSimpleValueType();
12910   SDLoc DL(Op);
12911   unsigned int NumElts = VT.getVectorNumElements();
12912   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12913     return SDValue();
12914
12915   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12916     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12917
12918   assert(InVT.getVectorElementType() == MVT::i1);
12919   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12920   SDValue One =
12921    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12922   SDValue Zero =
12923    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12924
12925   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12926   if (VT.is512BitVector())
12927     return V;
12928   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12929 }
12930
12931 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12932                                SelectionDAG &DAG) {
12933   if (Subtarget->hasFp256())
12934     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12935       return Res;
12936
12937   return SDValue();
12938 }
12939
12940 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12941                                 SelectionDAG &DAG) {
12942   SDLoc DL(Op);
12943   MVT VT = Op.getSimpleValueType();
12944   SDValue In = Op.getOperand(0);
12945   MVT SVT = In.getSimpleValueType();
12946
12947   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12948     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12949
12950   if (Subtarget->hasFp256())
12951     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12952       return Res;
12953
12954   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12955          VT.getVectorNumElements() != SVT.getVectorNumElements());
12956   return SDValue();
12957 }
12958
12959 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12960   SDLoc DL(Op);
12961   MVT VT = Op.getSimpleValueType();
12962   SDValue In = Op.getOperand(0);
12963   MVT InVT = In.getSimpleValueType();
12964
12965   if (VT == MVT::i1) {
12966     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12967            "Invalid scalar TRUNCATE operation");
12968     if (InVT.getSizeInBits() >= 32)
12969       return SDValue();
12970     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12971     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12972   }
12973   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12974          "Invalid TRUNCATE operation");
12975
12976   // move vector to mask - truncate solution for SKX
12977   if (VT.getVectorElementType() == MVT::i1) {
12978     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12979         Subtarget->hasBWI())
12980       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12981     if ((InVT.is256BitVector() || InVT.is128BitVector())
12982         && InVT.getScalarSizeInBits() <= 16 &&
12983         Subtarget->hasBWI() && Subtarget->hasVLX())
12984       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12985     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12986         Subtarget->hasDQI())
12987       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12988     if ((InVT.is256BitVector() || InVT.is128BitVector())
12989         && InVT.getScalarSizeInBits() >= 32 &&
12990         Subtarget->hasDQI() && Subtarget->hasVLX())
12991       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12992   }
12993
12994   if (VT.getVectorElementType() == MVT::i1) {
12995     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12996     unsigned NumElts = InVT.getVectorNumElements();
12997     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12998     if (InVT.getSizeInBits() < 512) {
12999       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
13000       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13001       InVT = ExtVT;
13002     }
13003
13004     SDValue OneV =
13005      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
13006     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
13007     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
13008   }
13009
13010   // vpmovqb/w/d, vpmovdb/w, vpmovwb
13011   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
13012       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
13013     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13014
13015   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13016     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13017     if (Subtarget->hasInt256()) {
13018       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13019       In = DAG.getBitcast(MVT::v8i32, In);
13020       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13021                                 ShufMask);
13022       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13023                          DAG.getIntPtrConstant(0, DL));
13024     }
13025
13026     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13027                                DAG.getIntPtrConstant(0, DL));
13028     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13029                                DAG.getIntPtrConstant(2, DL));
13030     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13031     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13032     static const int ShufMask[] = {0, 2, 4, 6};
13033     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13034   }
13035
13036   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13037     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13038     if (Subtarget->hasInt256()) {
13039       In = DAG.getBitcast(MVT::v32i8, In);
13040
13041       SmallVector<SDValue,32> pshufbMask;
13042       for (unsigned i = 0; i < 2; ++i) {
13043         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13044         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13045         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13046         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13047         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13048         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13049         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13050         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13051         for (unsigned j = 0; j < 8; ++j)
13052           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13053       }
13054       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13055       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13056       In = DAG.getBitcast(MVT::v4i64, In);
13057
13058       static const int ShufMask[] = {0,  2,  -1,  -1};
13059       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13060                                 &ShufMask[0]);
13061       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13062                        DAG.getIntPtrConstant(0, DL));
13063       return DAG.getBitcast(VT, In);
13064     }
13065
13066     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13067                                DAG.getIntPtrConstant(0, DL));
13068
13069     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13070                                DAG.getIntPtrConstant(4, DL));
13071
13072     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13073     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13074
13075     // The PSHUFB mask:
13076     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13077                                    -1, -1, -1, -1, -1, -1, -1, -1};
13078
13079     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13080     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13081     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13082
13083     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13084     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13085
13086     // The MOVLHPS Mask:
13087     static const int ShufMask2[] = {0, 1, 4, 5};
13088     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13089     return DAG.getBitcast(MVT::v8i16, res);
13090   }
13091
13092   // Handle truncation of V256 to V128 using shuffles.
13093   if (!VT.is128BitVector() || !InVT.is256BitVector())
13094     return SDValue();
13095
13096   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13097
13098   unsigned NumElems = VT.getVectorNumElements();
13099   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13100
13101   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13102   // Prepare truncation shuffle mask
13103   for (unsigned i = 0; i != NumElems; ++i)
13104     MaskVec[i] = i * 2;
13105   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13106                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13107   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13108                      DAG.getIntPtrConstant(0, DL));
13109 }
13110
13111 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13112                                            SelectionDAG &DAG) const {
13113   assert(!Op.getSimpleValueType().isVector());
13114
13115   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13116     /*IsSigned=*/ true, /*IsReplace=*/ false);
13117   SDValue FIST = Vals.first, StackSlot = Vals.second;
13118   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13119   if (!FIST.getNode())
13120     return Op;
13121
13122   if (StackSlot.getNode())
13123     // Load the result.
13124     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13125                        FIST, StackSlot, MachinePointerInfo(),
13126                        false, false, false, 0);
13127
13128   // The node is the result.
13129   return FIST;
13130 }
13131
13132 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13133                                            SelectionDAG &DAG) const {
13134   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13135     /*IsSigned=*/ false, /*IsReplace=*/ false);
13136   SDValue FIST = Vals.first, StackSlot = Vals.second;
13137   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13138   if (!FIST.getNode())
13139     return Op;
13140
13141   if (StackSlot.getNode())
13142     // Load the result.
13143     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13144                        FIST, StackSlot, MachinePointerInfo(),
13145                        false, false, false, 0);
13146
13147   // The node is the result.
13148   return FIST;
13149 }
13150
13151 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13152   SDLoc DL(Op);
13153   MVT VT = Op.getSimpleValueType();
13154   SDValue In = Op.getOperand(0);
13155   MVT SVT = In.getSimpleValueType();
13156
13157   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13158
13159   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13160                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13161                                  In, DAG.getUNDEF(SVT)));
13162 }
13163
13164 /// The only differences between FABS and FNEG are the mask and the logic op.
13165 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13166 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13167   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13168          "Wrong opcode for lowering FABS or FNEG.");
13169
13170   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13171
13172   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13173   // into an FNABS. We'll lower the FABS after that if it is still in use.
13174   if (IsFABS)
13175     for (SDNode *User : Op->uses())
13176       if (User->getOpcode() == ISD::FNEG)
13177         return Op;
13178
13179   SDLoc dl(Op);
13180   MVT VT = Op.getSimpleValueType();
13181
13182   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13183   // decide if we should generate a 16-byte constant mask when we only need 4 or
13184   // 8 bytes for the scalar case.
13185
13186   MVT LogicVT;
13187   MVT EltVT;
13188   unsigned NumElts;
13189
13190   if (VT.isVector()) {
13191     LogicVT = VT;
13192     EltVT = VT.getVectorElementType();
13193     NumElts = VT.getVectorNumElements();
13194   } else {
13195     // There are no scalar bitwise logical SSE/AVX instructions, so we
13196     // generate a 16-byte vector constant and logic op even for the scalar case.
13197     // Using a 16-byte mask allows folding the load of the mask with
13198     // the logic op, so it can save (~4 bytes) on code size.
13199     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13200     EltVT = VT;
13201     NumElts = (VT == MVT::f64) ? 2 : 4;
13202   }
13203
13204   unsigned EltBits = EltVT.getSizeInBits();
13205   LLVMContext *Context = DAG.getContext();
13206   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13207   APInt MaskElt =
13208     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13209   Constant *C = ConstantInt::get(*Context, MaskElt);
13210   C = ConstantVector::getSplat(NumElts, C);
13211   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13212   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13213   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13214   SDValue Mask =
13215       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13216                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13217                   false, false, false, Alignment);
13218
13219   SDValue Op0 = Op.getOperand(0);
13220   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13221   unsigned LogicOp =
13222     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13223   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13224
13225   if (VT.isVector())
13226     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13227
13228   // For the scalar case extend to a 128-bit vector, perform the logic op,
13229   // and extract the scalar result back out.
13230   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13231   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13232   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13233                      DAG.getIntPtrConstant(0, dl));
13234 }
13235
13236 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13237   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13238   LLVMContext *Context = DAG.getContext();
13239   SDValue Op0 = Op.getOperand(0);
13240   SDValue Op1 = Op.getOperand(1);
13241   SDLoc dl(Op);
13242   MVT VT = Op.getSimpleValueType();
13243   MVT SrcVT = Op1.getSimpleValueType();
13244
13245   // If second operand is smaller, extend it first.
13246   if (SrcVT.bitsLT(VT)) {
13247     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13248     SrcVT = VT;
13249   }
13250   // And if it is bigger, shrink it first.
13251   if (SrcVT.bitsGT(VT)) {
13252     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13253     SrcVT = VT;
13254   }
13255
13256   // At this point the operands and the result should have the same
13257   // type, and that won't be f80 since that is not custom lowered.
13258
13259   const fltSemantics &Sem =
13260       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
13261   const unsigned SizeInBits = VT.getSizeInBits();
13262
13263   SmallVector<Constant *, 4> CV(
13264       VT == MVT::f64 ? 2 : 4,
13265       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13266
13267   // First, clear all bits but the sign bit from the second operand (sign).
13268   CV[0] = ConstantFP::get(*Context,
13269                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13270   Constant *C = ConstantVector::get(CV);
13271   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13272   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13273
13274   // Perform all logic operations as 16-byte vectors because there are no
13275   // scalar FP logic instructions in SSE. This allows load folding of the
13276   // constants into the logic instructions.
13277   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13278   SDValue Mask1 =
13279       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13280                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13281                   false, false, false, 16);
13282   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13283   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13284
13285   // Next, clear the sign bit from the first operand (magnitude).
13286   // If it's a constant, we can clear it here.
13287   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13288     APFloat APF = Op0CN->getValueAPF();
13289     // If the magnitude is a positive zero, the sign bit alone is enough.
13290     if (APF.isPosZero())
13291       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13292                          DAG.getIntPtrConstant(0, dl));
13293     APF.clearSign();
13294     CV[0] = ConstantFP::get(*Context, APF);
13295   } else {
13296     CV[0] = ConstantFP::get(
13297         *Context,
13298         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13299   }
13300   C = ConstantVector::get(CV);
13301   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13302   SDValue Val =
13303       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13304                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13305                   false, false, false, 16);
13306   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13307   if (!isa<ConstantFPSDNode>(Op0)) {
13308     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13309     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13310   }
13311   // OR the magnitude value with the sign bit.
13312   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13313   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13314                      DAG.getIntPtrConstant(0, dl));
13315 }
13316
13317 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13318   SDValue N0 = Op.getOperand(0);
13319   SDLoc dl(Op);
13320   MVT VT = Op.getSimpleValueType();
13321
13322   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13323   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13324                                   DAG.getConstant(1, dl, VT));
13325   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13326 }
13327
13328 // Check whether an OR'd tree is PTEST-able.
13329 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13330                                       SelectionDAG &DAG) {
13331   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13332
13333   if (!Subtarget->hasSSE41())
13334     return SDValue();
13335
13336   if (!Op->hasOneUse())
13337     return SDValue();
13338
13339   SDNode *N = Op.getNode();
13340   SDLoc DL(N);
13341
13342   SmallVector<SDValue, 8> Opnds;
13343   DenseMap<SDValue, unsigned> VecInMap;
13344   SmallVector<SDValue, 8> VecIns;
13345   EVT VT = MVT::Other;
13346
13347   // Recognize a special case where a vector is casted into wide integer to
13348   // test all 0s.
13349   Opnds.push_back(N->getOperand(0));
13350   Opnds.push_back(N->getOperand(1));
13351
13352   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13353     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13354     // BFS traverse all OR'd operands.
13355     if (I->getOpcode() == ISD::OR) {
13356       Opnds.push_back(I->getOperand(0));
13357       Opnds.push_back(I->getOperand(1));
13358       // Re-evaluate the number of nodes to be traversed.
13359       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13360       continue;
13361     }
13362
13363     // Quit if a non-EXTRACT_VECTOR_ELT
13364     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13365       return SDValue();
13366
13367     // Quit if without a constant index.
13368     SDValue Idx = I->getOperand(1);
13369     if (!isa<ConstantSDNode>(Idx))
13370       return SDValue();
13371
13372     SDValue ExtractedFromVec = I->getOperand(0);
13373     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13374     if (M == VecInMap.end()) {
13375       VT = ExtractedFromVec.getValueType();
13376       // Quit if not 128/256-bit vector.
13377       if (!VT.is128BitVector() && !VT.is256BitVector())
13378         return SDValue();
13379       // Quit if not the same type.
13380       if (VecInMap.begin() != VecInMap.end() &&
13381           VT != VecInMap.begin()->first.getValueType())
13382         return SDValue();
13383       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13384       VecIns.push_back(ExtractedFromVec);
13385     }
13386     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13387   }
13388
13389   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13390          "Not extracted from 128-/256-bit vector.");
13391
13392   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13393
13394   for (DenseMap<SDValue, unsigned>::const_iterator
13395         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13396     // Quit if not all elements are used.
13397     if (I->second != FullMask)
13398       return SDValue();
13399   }
13400
13401   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13402
13403   // Cast all vectors into TestVT for PTEST.
13404   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13405     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13406
13407   // If more than one full vectors are evaluated, OR them first before PTEST.
13408   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13409     // Each iteration will OR 2 nodes and append the result until there is only
13410     // 1 node left, i.e. the final OR'd value of all vectors.
13411     SDValue LHS = VecIns[Slot];
13412     SDValue RHS = VecIns[Slot + 1];
13413     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13414   }
13415
13416   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13417                      VecIns.back(), VecIns.back());
13418 }
13419
13420 /// \brief return true if \c Op has a use that doesn't just read flags.
13421 static bool hasNonFlagsUse(SDValue Op) {
13422   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13423        ++UI) {
13424     SDNode *User = *UI;
13425     unsigned UOpNo = UI.getOperandNo();
13426     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13427       // Look pass truncate.
13428       UOpNo = User->use_begin().getOperandNo();
13429       User = *User->use_begin();
13430     }
13431
13432     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13433         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13434       return true;
13435   }
13436   return false;
13437 }
13438
13439 /// Emit nodes that will be selected as "test Op0,Op0", or something
13440 /// equivalent.
13441 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13442                                     SelectionDAG &DAG) const {
13443   if (Op.getValueType() == MVT::i1) {
13444     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13445     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13446                        DAG.getConstant(0, dl, MVT::i8));
13447   }
13448   // CF and OF aren't always set the way we want. Determine which
13449   // of these we need.
13450   bool NeedCF = false;
13451   bool NeedOF = false;
13452   switch (X86CC) {
13453   default: break;
13454   case X86::COND_A: case X86::COND_AE:
13455   case X86::COND_B: case X86::COND_BE:
13456     NeedCF = true;
13457     break;
13458   case X86::COND_G: case X86::COND_GE:
13459   case X86::COND_L: case X86::COND_LE:
13460   case X86::COND_O: case X86::COND_NO: {
13461     // Check if we really need to set the
13462     // Overflow flag. If NoSignedWrap is present
13463     // that is not actually needed.
13464     switch (Op->getOpcode()) {
13465     case ISD::ADD:
13466     case ISD::SUB:
13467     case ISD::MUL:
13468     case ISD::SHL: {
13469       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13470       if (BinNode->Flags.hasNoSignedWrap())
13471         break;
13472     }
13473     default:
13474       NeedOF = true;
13475       break;
13476     }
13477     break;
13478   }
13479   }
13480   // See if we can use the EFLAGS value from the operand instead of
13481   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13482   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13483   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13484     // Emit a CMP with 0, which is the TEST pattern.
13485     //if (Op.getValueType() == MVT::i1)
13486     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13487     //                     DAG.getConstant(0, MVT::i1));
13488     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13489                        DAG.getConstant(0, dl, Op.getValueType()));
13490   }
13491   unsigned Opcode = 0;
13492   unsigned NumOperands = 0;
13493
13494   // Truncate operations may prevent the merge of the SETCC instruction
13495   // and the arithmetic instruction before it. Attempt to truncate the operands
13496   // of the arithmetic instruction and use a reduced bit-width instruction.
13497   bool NeedTruncation = false;
13498   SDValue ArithOp = Op;
13499   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13500     SDValue Arith = Op->getOperand(0);
13501     // Both the trunc and the arithmetic op need to have one user each.
13502     if (Arith->hasOneUse())
13503       switch (Arith.getOpcode()) {
13504         default: break;
13505         case ISD::ADD:
13506         case ISD::SUB:
13507         case ISD::AND:
13508         case ISD::OR:
13509         case ISD::XOR: {
13510           NeedTruncation = true;
13511           ArithOp = Arith;
13512         }
13513       }
13514   }
13515
13516   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13517   // which may be the result of a CAST.  We use the variable 'Op', which is the
13518   // non-casted variable when we check for possible users.
13519   switch (ArithOp.getOpcode()) {
13520   case ISD::ADD:
13521     // Due to an isel shortcoming, be conservative if this add is likely to be
13522     // selected as part of a load-modify-store instruction. When the root node
13523     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13524     // uses of other nodes in the match, such as the ADD in this case. This
13525     // leads to the ADD being left around and reselected, with the result being
13526     // two adds in the output.  Alas, even if none our users are stores, that
13527     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13528     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13529     // climbing the DAG back to the root, and it doesn't seem to be worth the
13530     // effort.
13531     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13532          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13533       if (UI->getOpcode() != ISD::CopyToReg &&
13534           UI->getOpcode() != ISD::SETCC &&
13535           UI->getOpcode() != ISD::STORE)
13536         goto default_case;
13537
13538     if (ConstantSDNode *C =
13539         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13540       // An add of one will be selected as an INC.
13541       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13542         Opcode = X86ISD::INC;
13543         NumOperands = 1;
13544         break;
13545       }
13546
13547       // An add of negative one (subtract of one) will be selected as a DEC.
13548       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13549         Opcode = X86ISD::DEC;
13550         NumOperands = 1;
13551         break;
13552       }
13553     }
13554
13555     // Otherwise use a regular EFLAGS-setting add.
13556     Opcode = X86ISD::ADD;
13557     NumOperands = 2;
13558     break;
13559   case ISD::SHL:
13560   case ISD::SRL:
13561     // If we have a constant logical shift that's only used in a comparison
13562     // against zero turn it into an equivalent AND. This allows turning it into
13563     // a TEST instruction later.
13564     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13565         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13566       EVT VT = Op.getValueType();
13567       unsigned BitWidth = VT.getSizeInBits();
13568       unsigned ShAmt = Op->getConstantOperandVal(1);
13569       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13570         break;
13571       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13572                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13573                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13574       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13575         break;
13576       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13577                                 DAG.getConstant(Mask, dl, VT));
13578       DAG.ReplaceAllUsesWith(Op, New);
13579       Op = New;
13580     }
13581     break;
13582
13583   case ISD::AND:
13584     // If the primary and result isn't used, don't bother using X86ISD::AND,
13585     // because a TEST instruction will be better.
13586     if (!hasNonFlagsUse(Op))
13587       break;
13588     // FALL THROUGH
13589   case ISD::SUB:
13590   case ISD::OR:
13591   case ISD::XOR:
13592     // Due to the ISEL shortcoming noted above, be conservative if this op is
13593     // likely to be selected as part of a load-modify-store instruction.
13594     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13595            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13596       if (UI->getOpcode() == ISD::STORE)
13597         goto default_case;
13598
13599     // Otherwise use a regular EFLAGS-setting instruction.
13600     switch (ArithOp.getOpcode()) {
13601     default: llvm_unreachable("unexpected operator!");
13602     case ISD::SUB: Opcode = X86ISD::SUB; break;
13603     case ISD::XOR: Opcode = X86ISD::XOR; break;
13604     case ISD::AND: Opcode = X86ISD::AND; break;
13605     case ISD::OR: {
13606       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13607         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13608         if (EFLAGS.getNode())
13609           return EFLAGS;
13610       }
13611       Opcode = X86ISD::OR;
13612       break;
13613     }
13614     }
13615
13616     NumOperands = 2;
13617     break;
13618   case X86ISD::ADD:
13619   case X86ISD::SUB:
13620   case X86ISD::INC:
13621   case X86ISD::DEC:
13622   case X86ISD::OR:
13623   case X86ISD::XOR:
13624   case X86ISD::AND:
13625     return SDValue(Op.getNode(), 1);
13626   default:
13627   default_case:
13628     break;
13629   }
13630
13631   // If we found that truncation is beneficial, perform the truncation and
13632   // update 'Op'.
13633   if (NeedTruncation) {
13634     EVT VT = Op.getValueType();
13635     SDValue WideVal = Op->getOperand(0);
13636     EVT WideVT = WideVal.getValueType();
13637     unsigned ConvertedOp = 0;
13638     // Use a target machine opcode to prevent further DAGCombine
13639     // optimizations that may separate the arithmetic operations
13640     // from the setcc node.
13641     switch (WideVal.getOpcode()) {
13642       default: break;
13643       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13644       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13645       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13646       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13647       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13648     }
13649
13650     if (ConvertedOp) {
13651       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13652       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13653         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13654         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13655         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13656       }
13657     }
13658   }
13659
13660   if (Opcode == 0)
13661     // Emit a CMP with 0, which is the TEST pattern.
13662     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13663                        DAG.getConstant(0, dl, Op.getValueType()));
13664
13665   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13666   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13667
13668   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13669   DAG.ReplaceAllUsesWith(Op, New);
13670   return SDValue(New.getNode(), 1);
13671 }
13672
13673 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13674 /// equivalent.
13675 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13676                                    SDLoc dl, SelectionDAG &DAG) const {
13677   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13678     if (C->getAPIntValue() == 0)
13679       return EmitTest(Op0, X86CC, dl, DAG);
13680
13681      if (Op0.getValueType() == MVT::i1)
13682        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13683   }
13684
13685   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13686        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13687     // Do the comparison at i32 if it's smaller, besides the Atom case.
13688     // This avoids subregister aliasing issues. Keep the smaller reference
13689     // if we're optimizing for size, however, as that'll allow better folding
13690     // of memory operations.
13691     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13692         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13693         !Subtarget->isAtom()) {
13694       unsigned ExtendOp =
13695           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13696       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13697       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13698     }
13699     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13700     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13701     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13702                               Op0, Op1);
13703     return SDValue(Sub.getNode(), 1);
13704   }
13705   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13706 }
13707
13708 /// Convert a comparison if required by the subtarget.
13709 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13710                                                  SelectionDAG &DAG) const {
13711   // If the subtarget does not support the FUCOMI instruction, floating-point
13712   // comparisons have to be converted.
13713   if (Subtarget->hasCMov() ||
13714       Cmp.getOpcode() != X86ISD::CMP ||
13715       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13716       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13717     return Cmp;
13718
13719   // The instruction selector will select an FUCOM instruction instead of
13720   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13721   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13722   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13723   SDLoc dl(Cmp);
13724   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13725   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13726   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13727                             DAG.getConstant(8, dl, MVT::i8));
13728   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13729   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13730 }
13731
13732 /// The minimum architected relative accuracy is 2^-12. We need one
13733 /// Newton-Raphson step to have a good float result (24 bits of precision).
13734 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13735                                             DAGCombinerInfo &DCI,
13736                                             unsigned &RefinementSteps,
13737                                             bool &UseOneConstNR) const {
13738   EVT VT = Op.getValueType();
13739   const char *RecipOp;
13740
13741   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13742   // TODO: Add support for AVX512 (v16f32).
13743   // It is likely not profitable to do this for f64 because a double-precision
13744   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13745   // instructions: convert to single, rsqrtss, convert back to double, refine
13746   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13747   // along with FMA, this could be a throughput win.
13748   if (VT == MVT::f32 && Subtarget->hasSSE1())
13749     RecipOp = "sqrtf";
13750   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13751            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13752     RecipOp = "vec-sqrtf";
13753   else
13754     return SDValue();
13755
13756   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13757   if (!Recips.isEnabled(RecipOp))
13758     return SDValue();
13759
13760   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13761   UseOneConstNR = false;
13762   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13763 }
13764
13765 /// The minimum architected relative accuracy is 2^-12. We need one
13766 /// Newton-Raphson step to have a good float result (24 bits of precision).
13767 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13768                                             DAGCombinerInfo &DCI,
13769                                             unsigned &RefinementSteps) const {
13770   EVT VT = Op.getValueType();
13771   const char *RecipOp;
13772
13773   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13774   // TODO: Add support for AVX512 (v16f32).
13775   // It is likely not profitable to do this for f64 because a double-precision
13776   // reciprocal estimate with refinement on x86 prior to FMA requires
13777   // 15 instructions: convert to single, rcpss, convert back to double, refine
13778   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13779   // along with FMA, this could be a throughput win.
13780   if (VT == MVT::f32 && Subtarget->hasSSE1())
13781     RecipOp = "divf";
13782   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13783            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13784     RecipOp = "vec-divf";
13785   else
13786     return SDValue();
13787
13788   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13789   if (!Recips.isEnabled(RecipOp))
13790     return SDValue();
13791
13792   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13793   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13794 }
13795
13796 /// If we have at least two divisions that use the same divisor, convert to
13797 /// multplication by a reciprocal. This may need to be adjusted for a given
13798 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13799 /// This is because we still need one division to calculate the reciprocal and
13800 /// then we need two multiplies by that reciprocal as replacements for the
13801 /// original divisions.
13802 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13803   return 2;
13804 }
13805
13806 static bool isAllOnes(SDValue V) {
13807   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13808   return C && C->isAllOnesValue();
13809 }
13810
13811 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13812 /// if it's possible.
13813 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13814                                      SDLoc dl, SelectionDAG &DAG) const {
13815   SDValue Op0 = And.getOperand(0);
13816   SDValue Op1 = And.getOperand(1);
13817   if (Op0.getOpcode() == ISD::TRUNCATE)
13818     Op0 = Op0.getOperand(0);
13819   if (Op1.getOpcode() == ISD::TRUNCATE)
13820     Op1 = Op1.getOperand(0);
13821
13822   SDValue LHS, RHS;
13823   if (Op1.getOpcode() == ISD::SHL)
13824     std::swap(Op0, Op1);
13825   if (Op0.getOpcode() == ISD::SHL) {
13826     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13827       if (And00C->getZExtValue() == 1) {
13828         // If we looked past a truncate, check that it's only truncating away
13829         // known zeros.
13830         unsigned BitWidth = Op0.getValueSizeInBits();
13831         unsigned AndBitWidth = And.getValueSizeInBits();
13832         if (BitWidth > AndBitWidth) {
13833           APInt Zeros, Ones;
13834           DAG.computeKnownBits(Op0, Zeros, Ones);
13835           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13836             return SDValue();
13837         }
13838         LHS = Op1;
13839         RHS = Op0.getOperand(1);
13840       }
13841   } else if (Op1.getOpcode() == ISD::Constant) {
13842     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13843     uint64_t AndRHSVal = AndRHS->getZExtValue();
13844     SDValue AndLHS = Op0;
13845
13846     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13847       LHS = AndLHS.getOperand(0);
13848       RHS = AndLHS.getOperand(1);
13849     }
13850
13851     // Use BT if the immediate can't be encoded in a TEST instruction.
13852     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13853       LHS = AndLHS;
13854       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13855     }
13856   }
13857
13858   if (LHS.getNode()) {
13859     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13860     // instruction.  Since the shift amount is in-range-or-undefined, we know
13861     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13862     // the encoding for the i16 version is larger than the i32 version.
13863     // Also promote i16 to i32 for performance / code size reason.
13864     if (LHS.getValueType() == MVT::i8 ||
13865         LHS.getValueType() == MVT::i16)
13866       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13867
13868     // If the operand types disagree, extend the shift amount to match.  Since
13869     // BT ignores high bits (like shifts) we can use anyextend.
13870     if (LHS.getValueType() != RHS.getValueType())
13871       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13872
13873     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13874     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13875     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13876                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13877   }
13878
13879   return SDValue();
13880 }
13881
13882 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13883 /// mask CMPs.
13884 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13885                               SDValue &Op1) {
13886   unsigned SSECC;
13887   bool Swap = false;
13888
13889   // SSE Condition code mapping:
13890   //  0 - EQ
13891   //  1 - LT
13892   //  2 - LE
13893   //  3 - UNORD
13894   //  4 - NEQ
13895   //  5 - NLT
13896   //  6 - NLE
13897   //  7 - ORD
13898   switch (SetCCOpcode) {
13899   default: llvm_unreachable("Unexpected SETCC condition");
13900   case ISD::SETOEQ:
13901   case ISD::SETEQ:  SSECC = 0; break;
13902   case ISD::SETOGT:
13903   case ISD::SETGT:  Swap = true; // Fallthrough
13904   case ISD::SETLT:
13905   case ISD::SETOLT: SSECC = 1; break;
13906   case ISD::SETOGE:
13907   case ISD::SETGE:  Swap = true; // Fallthrough
13908   case ISD::SETLE:
13909   case ISD::SETOLE: SSECC = 2; break;
13910   case ISD::SETUO:  SSECC = 3; break;
13911   case ISD::SETUNE:
13912   case ISD::SETNE:  SSECC = 4; break;
13913   case ISD::SETULE: Swap = true; // Fallthrough
13914   case ISD::SETUGE: SSECC = 5; break;
13915   case ISD::SETULT: Swap = true; // Fallthrough
13916   case ISD::SETUGT: SSECC = 6; break;
13917   case ISD::SETO:   SSECC = 7; break;
13918   case ISD::SETUEQ:
13919   case ISD::SETONE: SSECC = 8; break;
13920   }
13921   if (Swap)
13922     std::swap(Op0, Op1);
13923
13924   return SSECC;
13925 }
13926
13927 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13928 // ones, and then concatenate the result back.
13929 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13930   MVT VT = Op.getSimpleValueType();
13931
13932   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13933          "Unsupported value type for operation");
13934
13935   unsigned NumElems = VT.getVectorNumElements();
13936   SDLoc dl(Op);
13937   SDValue CC = Op.getOperand(2);
13938
13939   // Extract the LHS vectors
13940   SDValue LHS = Op.getOperand(0);
13941   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13942   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13943
13944   // Extract the RHS vectors
13945   SDValue RHS = Op.getOperand(1);
13946   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13947   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13948
13949   // Issue the operation on the smaller types and concatenate the result back
13950   MVT EltVT = VT.getVectorElementType();
13951   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13952   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13953                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13954                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13955 }
13956
13957 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13958   SDValue Op0 = Op.getOperand(0);
13959   SDValue Op1 = Op.getOperand(1);
13960   SDValue CC = Op.getOperand(2);
13961   MVT VT = Op.getSimpleValueType();
13962   SDLoc dl(Op);
13963
13964   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13965          "Unexpected type for boolean compare operation");
13966   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13967   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13968                                DAG.getConstant(-1, dl, VT));
13969   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13970                                DAG.getConstant(-1, dl, VT));
13971   switch (SetCCOpcode) {
13972   default: llvm_unreachable("Unexpected SETCC condition");
13973   case ISD::SETEQ:
13974     // (x == y) -> ~(x ^ y)
13975     return DAG.getNode(ISD::XOR, dl, VT,
13976                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13977                        DAG.getConstant(-1, dl, VT));
13978   case ISD::SETNE:
13979     // (x != y) -> (x ^ y)
13980     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13981   case ISD::SETUGT:
13982   case ISD::SETGT:
13983     // (x > y) -> (x & ~y)
13984     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13985   case ISD::SETULT:
13986   case ISD::SETLT:
13987     // (x < y) -> (~x & y)
13988     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13989   case ISD::SETULE:
13990   case ISD::SETLE:
13991     // (x <= y) -> (~x | y)
13992     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13993   case ISD::SETUGE:
13994   case ISD::SETGE:
13995     // (x >=y) -> (x | ~y)
13996     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13997   }
13998 }
13999
14000 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14001                                      const X86Subtarget *Subtarget) {
14002   SDValue Op0 = Op.getOperand(0);
14003   SDValue Op1 = Op.getOperand(1);
14004   SDValue CC = Op.getOperand(2);
14005   MVT VT = Op.getSimpleValueType();
14006   SDLoc dl(Op);
14007
14008   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
14009          Op.getValueType().getScalarType() == MVT::i1 &&
14010          "Cannot set masked compare for this operation");
14011
14012   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14013   unsigned  Opc = 0;
14014   bool Unsigned = false;
14015   bool Swap = false;
14016   unsigned SSECC;
14017   switch (SetCCOpcode) {
14018   default: llvm_unreachable("Unexpected SETCC condition");
14019   case ISD::SETNE:  SSECC = 4; break;
14020   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14021   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14022   case ISD::SETLT:  Swap = true; //fall-through
14023   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14024   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14025   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14026   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14027   case ISD::SETULE: Unsigned = true; //fall-through
14028   case ISD::SETLE:  SSECC = 2; break;
14029   }
14030
14031   if (Swap)
14032     std::swap(Op0, Op1);
14033   if (Opc)
14034     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14035   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14036   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14037                      DAG.getConstant(SSECC, dl, MVT::i8));
14038 }
14039
14040 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14041 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14042 /// return an empty value.
14043 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14044 {
14045   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14046   if (!BV)
14047     return SDValue();
14048
14049   MVT VT = Op1.getSimpleValueType();
14050   MVT EVT = VT.getVectorElementType();
14051   unsigned n = VT.getVectorNumElements();
14052   SmallVector<SDValue, 8> ULTOp1;
14053
14054   for (unsigned i = 0; i < n; ++i) {
14055     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14056     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
14057       return SDValue();
14058
14059     // Avoid underflow.
14060     APInt Val = Elt->getAPIntValue();
14061     if (Val == 0)
14062       return SDValue();
14063
14064     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14065   }
14066
14067   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14068 }
14069
14070 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14071                            SelectionDAG &DAG) {
14072   SDValue Op0 = Op.getOperand(0);
14073   SDValue Op1 = Op.getOperand(1);
14074   SDValue CC = Op.getOperand(2);
14075   MVT VT = Op.getSimpleValueType();
14076   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14077   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14078   SDLoc dl(Op);
14079
14080   if (isFP) {
14081 #ifndef NDEBUG
14082     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14083     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14084 #endif
14085
14086     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14087     unsigned Opc = X86ISD::CMPP;
14088     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14089       assert(VT.getVectorNumElements() <= 16);
14090       Opc = X86ISD::CMPM;
14091     }
14092     // In the two special cases we can't handle, emit two comparisons.
14093     if (SSECC == 8) {
14094       unsigned CC0, CC1;
14095       unsigned CombineOpc;
14096       if (SetCCOpcode == ISD::SETUEQ) {
14097         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14098       } else {
14099         assert(SetCCOpcode == ISD::SETONE);
14100         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14101       }
14102
14103       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14104                                  DAG.getConstant(CC0, dl, MVT::i8));
14105       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14106                                  DAG.getConstant(CC1, dl, MVT::i8));
14107       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14108     }
14109     // Handle all other FP comparisons here.
14110     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14111                        DAG.getConstant(SSECC, dl, MVT::i8));
14112   }
14113
14114   // Break 256-bit integer vector compare into smaller ones.
14115   if (VT.is256BitVector() && !Subtarget->hasInt256())
14116     return Lower256IntVSETCC(Op, DAG);
14117
14118   EVT OpVT = Op1.getValueType();
14119   if (OpVT.getVectorElementType() == MVT::i1)
14120     return LowerBoolVSETCC_AVX512(Op, DAG);
14121
14122   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14123   if (Subtarget->hasAVX512()) {
14124     if (Op1.getValueType().is512BitVector() ||
14125         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14126         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14127       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14128
14129     // In AVX-512 architecture setcc returns mask with i1 elements,
14130     // But there is no compare instruction for i8 and i16 elements in KNL.
14131     // We are not talking about 512-bit operands in this case, these
14132     // types are illegal.
14133     if (MaskResult &&
14134         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14135          OpVT.getVectorElementType().getSizeInBits() >= 8))
14136       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14137                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14138   }
14139
14140   // We are handling one of the integer comparisons here.  Since SSE only has
14141   // GT and EQ comparisons for integer, swapping operands and multiple
14142   // operations may be required for some comparisons.
14143   unsigned Opc;
14144   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14145   bool Subus = false;
14146
14147   switch (SetCCOpcode) {
14148   default: llvm_unreachable("Unexpected SETCC condition");
14149   case ISD::SETNE:  Invert = true;
14150   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14151   case ISD::SETLT:  Swap = true;
14152   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14153   case ISD::SETGE:  Swap = true;
14154   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14155                     Invert = true; break;
14156   case ISD::SETULT: Swap = true;
14157   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14158                     FlipSigns = true; break;
14159   case ISD::SETUGE: Swap = true;
14160   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14161                     FlipSigns = true; Invert = true; break;
14162   }
14163
14164   // Special case: Use min/max operations for SETULE/SETUGE
14165   MVT VET = VT.getVectorElementType();
14166   bool hasMinMax =
14167        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14168     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14169
14170   if (hasMinMax) {
14171     switch (SetCCOpcode) {
14172     default: break;
14173     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14174     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14175     }
14176
14177     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14178   }
14179
14180   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14181   if (!MinMax && hasSubus) {
14182     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14183     // Op0 u<= Op1:
14184     //   t = psubus Op0, Op1
14185     //   pcmpeq t, <0..0>
14186     switch (SetCCOpcode) {
14187     default: break;
14188     case ISD::SETULT: {
14189       // If the comparison is against a constant we can turn this into a
14190       // setule.  With psubus, setule does not require a swap.  This is
14191       // beneficial because the constant in the register is no longer
14192       // destructed as the destination so it can be hoisted out of a loop.
14193       // Only do this pre-AVX since vpcmp* is no longer destructive.
14194       if (Subtarget->hasAVX())
14195         break;
14196       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14197       if (ULEOp1.getNode()) {
14198         Op1 = ULEOp1;
14199         Subus = true; Invert = false; Swap = false;
14200       }
14201       break;
14202     }
14203     // Psubus is better than flip-sign because it requires no inversion.
14204     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14205     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14206     }
14207
14208     if (Subus) {
14209       Opc = X86ISD::SUBUS;
14210       FlipSigns = false;
14211     }
14212   }
14213
14214   if (Swap)
14215     std::swap(Op0, Op1);
14216
14217   // Check that the operation in question is available (most are plain SSE2,
14218   // but PCMPGTQ and PCMPEQQ have different requirements).
14219   if (VT == MVT::v2i64) {
14220     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14221       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14222
14223       // First cast everything to the right type.
14224       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14225       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14226
14227       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14228       // bits of the inputs before performing those operations. The lower
14229       // compare is always unsigned.
14230       SDValue SB;
14231       if (FlipSigns) {
14232         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14233       } else {
14234         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14235         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14236         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14237                          Sign, Zero, Sign, Zero);
14238       }
14239       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14240       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14241
14242       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14243       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14244       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14245
14246       // Create masks for only the low parts/high parts of the 64 bit integers.
14247       static const int MaskHi[] = { 1, 1, 3, 3 };
14248       static const int MaskLo[] = { 0, 0, 2, 2 };
14249       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14250       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14251       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14252
14253       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14254       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14255
14256       if (Invert)
14257         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14258
14259       return DAG.getBitcast(VT, Result);
14260     }
14261
14262     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14263       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14264       // pcmpeqd + pshufd + pand.
14265       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14266
14267       // First cast everything to the right type.
14268       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14269       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14270
14271       // Do the compare.
14272       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14273
14274       // Make sure the lower and upper halves are both all-ones.
14275       static const int Mask[] = { 1, 0, 3, 2 };
14276       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14277       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14278
14279       if (Invert)
14280         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14281
14282       return DAG.getBitcast(VT, Result);
14283     }
14284   }
14285
14286   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14287   // bits of the inputs before performing those operations.
14288   if (FlipSigns) {
14289     EVT EltVT = VT.getVectorElementType();
14290     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14291                                  VT);
14292     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14293     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14294   }
14295
14296   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14297
14298   // If the logical-not of the result is required, perform that now.
14299   if (Invert)
14300     Result = DAG.getNOT(dl, Result, VT);
14301
14302   if (MinMax)
14303     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14304
14305   if (Subus)
14306     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14307                          getZeroVector(VT, Subtarget, DAG, dl));
14308
14309   return Result;
14310 }
14311
14312 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14313
14314   MVT VT = Op.getSimpleValueType();
14315
14316   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14317
14318   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14319          && "SetCC type must be 8-bit or 1-bit integer");
14320   SDValue Op0 = Op.getOperand(0);
14321   SDValue Op1 = Op.getOperand(1);
14322   SDLoc dl(Op);
14323   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14324
14325   // Optimize to BT if possible.
14326   // Lower (X & (1 << N)) == 0 to BT(X, N).
14327   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14328   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14329   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14330       Op1.getOpcode() == ISD::Constant &&
14331       cast<ConstantSDNode>(Op1)->isNullValue() &&
14332       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14333     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14334     if (NewSetCC.getNode()) {
14335       if (VT == MVT::i1)
14336         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14337       return NewSetCC;
14338     }
14339   }
14340
14341   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14342   // these.
14343   if (Op1.getOpcode() == ISD::Constant &&
14344       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14345        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14346       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14347
14348     // If the input is a setcc, then reuse the input setcc or use a new one with
14349     // the inverted condition.
14350     if (Op0.getOpcode() == X86ISD::SETCC) {
14351       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14352       bool Invert = (CC == ISD::SETNE) ^
14353         cast<ConstantSDNode>(Op1)->isNullValue();
14354       if (!Invert)
14355         return Op0;
14356
14357       CCode = X86::GetOppositeBranchCondition(CCode);
14358       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14359                                   DAG.getConstant(CCode, dl, MVT::i8),
14360                                   Op0.getOperand(1));
14361       if (VT == MVT::i1)
14362         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14363       return SetCC;
14364     }
14365   }
14366   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14367       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14368       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14369
14370     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14371     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14372   }
14373
14374   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14375   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14376   if (X86CC == X86::COND_INVALID)
14377     return SDValue();
14378
14379   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14380   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14381   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14382                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14383   if (VT == MVT::i1)
14384     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14385   return SetCC;
14386 }
14387
14388 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14389 static bool isX86LogicalCmp(SDValue Op) {
14390   unsigned Opc = Op.getNode()->getOpcode();
14391   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14392       Opc == X86ISD::SAHF)
14393     return true;
14394   if (Op.getResNo() == 1 &&
14395       (Opc == X86ISD::ADD ||
14396        Opc == X86ISD::SUB ||
14397        Opc == X86ISD::ADC ||
14398        Opc == X86ISD::SBB ||
14399        Opc == X86ISD::SMUL ||
14400        Opc == X86ISD::UMUL ||
14401        Opc == X86ISD::INC ||
14402        Opc == X86ISD::DEC ||
14403        Opc == X86ISD::OR ||
14404        Opc == X86ISD::XOR ||
14405        Opc == X86ISD::AND))
14406     return true;
14407
14408   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14409     return true;
14410
14411   return false;
14412 }
14413
14414 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14415   if (V.getOpcode() != ISD::TRUNCATE)
14416     return false;
14417
14418   SDValue VOp0 = V.getOperand(0);
14419   unsigned InBits = VOp0.getValueSizeInBits();
14420   unsigned Bits = V.getValueSizeInBits();
14421   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14422 }
14423
14424 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14425   bool addTest = true;
14426   SDValue Cond  = Op.getOperand(0);
14427   SDValue Op1 = Op.getOperand(1);
14428   SDValue Op2 = Op.getOperand(2);
14429   SDLoc DL(Op);
14430   EVT VT = Op1.getValueType();
14431   SDValue CC;
14432
14433   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14434   // are available or VBLENDV if AVX is available.
14435   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14436   if (Cond.getOpcode() == ISD::SETCC &&
14437       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14438        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14439       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14440     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14441     int SSECC = translateX86FSETCC(
14442         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14443
14444     if (SSECC != 8) {
14445       if (Subtarget->hasAVX512()) {
14446         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14447                                   DAG.getConstant(SSECC, DL, MVT::i8));
14448         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14449       }
14450
14451       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14452                                 DAG.getConstant(SSECC, DL, MVT::i8));
14453
14454       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14455       // of 3 logic instructions for size savings and potentially speed.
14456       // Unfortunately, there is no scalar form of VBLENDV.
14457
14458       // If either operand is a constant, don't try this. We can expect to
14459       // optimize away at least one of the logic instructions later in that
14460       // case, so that sequence would be faster than a variable blend.
14461
14462       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14463       // uses XMM0 as the selection register. That may need just as many
14464       // instructions as the AND/ANDN/OR sequence due to register moves, so
14465       // don't bother.
14466
14467       if (Subtarget->hasAVX() &&
14468           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14469
14470         // Convert to vectors, do a VSELECT, and convert back to scalar.
14471         // All of the conversions should be optimized away.
14472
14473         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14474         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14475         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14476         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14477
14478         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14479         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14480
14481         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14482
14483         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14484                            VSel, DAG.getIntPtrConstant(0, DL));
14485       }
14486       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14487       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14488       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14489     }
14490   }
14491
14492   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14493     SDValue Op1Scalar;
14494     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14495       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14496     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14497       Op1Scalar = Op1.getOperand(0);
14498     SDValue Op2Scalar;
14499     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14500       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14501     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14502       Op2Scalar = Op2.getOperand(0);
14503     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14504       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14505                                       Op1Scalar.getValueType(),
14506                                       Cond, Op1Scalar, Op2Scalar);
14507       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14508         return DAG.getBitcast(VT, newSelect);
14509       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14510       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14511                          DAG.getIntPtrConstant(0, DL));
14512     }
14513   }
14514
14515   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14516     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14517     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14518                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14519     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14520                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14521     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14522                                     Cond, Op1, Op2);
14523     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14524   }
14525
14526   if (Cond.getOpcode() == ISD::SETCC) {
14527     SDValue NewCond = LowerSETCC(Cond, DAG);
14528     if (NewCond.getNode())
14529       Cond = NewCond;
14530   }
14531
14532   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14533   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14534   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14535   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14536   if (Cond.getOpcode() == X86ISD::SETCC &&
14537       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14538       isZero(Cond.getOperand(1).getOperand(1))) {
14539     SDValue Cmp = Cond.getOperand(1);
14540
14541     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14542
14543     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14544         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14545       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14546
14547       SDValue CmpOp0 = Cmp.getOperand(0);
14548       // Apply further optimizations for special cases
14549       // (select (x != 0), -1, 0) -> neg & sbb
14550       // (select (x == 0), 0, -1) -> neg & sbb
14551       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14552         if (YC->isNullValue() &&
14553             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14554           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14555           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14556                                     DAG.getConstant(0, DL,
14557                                                     CmpOp0.getValueType()),
14558                                     CmpOp0);
14559           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14560                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14561                                     SDValue(Neg.getNode(), 1));
14562           return Res;
14563         }
14564
14565       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14566                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14567       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14568
14569       SDValue Res =   // Res = 0 or -1.
14570         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14571                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14572
14573       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14574         Res = DAG.getNOT(DL, Res, Res.getValueType());
14575
14576       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14577       if (!N2C || !N2C->isNullValue())
14578         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14579       return Res;
14580     }
14581   }
14582
14583   // Look past (and (setcc_carry (cmp ...)), 1).
14584   if (Cond.getOpcode() == ISD::AND &&
14585       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14586     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14587     if (C && C->getAPIntValue() == 1)
14588       Cond = Cond.getOperand(0);
14589   }
14590
14591   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14592   // setting operand in place of the X86ISD::SETCC.
14593   unsigned CondOpcode = Cond.getOpcode();
14594   if (CondOpcode == X86ISD::SETCC ||
14595       CondOpcode == X86ISD::SETCC_CARRY) {
14596     CC = Cond.getOperand(0);
14597
14598     SDValue Cmp = Cond.getOperand(1);
14599     unsigned Opc = Cmp.getOpcode();
14600     MVT VT = Op.getSimpleValueType();
14601
14602     bool IllegalFPCMov = false;
14603     if (VT.isFloatingPoint() && !VT.isVector() &&
14604         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14605       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14606
14607     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14608         Opc == X86ISD::BT) { // FIXME
14609       Cond = Cmp;
14610       addTest = false;
14611     }
14612   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14613              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14614              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14615               Cond.getOperand(0).getValueType() != MVT::i8)) {
14616     SDValue LHS = Cond.getOperand(0);
14617     SDValue RHS = Cond.getOperand(1);
14618     unsigned X86Opcode;
14619     unsigned X86Cond;
14620     SDVTList VTs;
14621     switch (CondOpcode) {
14622     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14623     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14624     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14625     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14626     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14627     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14628     default: llvm_unreachable("unexpected overflowing operator");
14629     }
14630     if (CondOpcode == ISD::UMULO)
14631       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14632                           MVT::i32);
14633     else
14634       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14635
14636     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14637
14638     if (CondOpcode == ISD::UMULO)
14639       Cond = X86Op.getValue(2);
14640     else
14641       Cond = X86Op.getValue(1);
14642
14643     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14644     addTest = false;
14645   }
14646
14647   if (addTest) {
14648     // Look past the truncate if the high bits are known zero.
14649     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14650       Cond = Cond.getOperand(0);
14651
14652     // We know the result of AND is compared against zero. Try to match
14653     // it to BT.
14654     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14655       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14656       if (NewSetCC.getNode()) {
14657         CC = NewSetCC.getOperand(0);
14658         Cond = NewSetCC.getOperand(1);
14659         addTest = false;
14660       }
14661     }
14662   }
14663
14664   if (addTest) {
14665     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14666     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14667   }
14668
14669   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14670   // a <  b ?  0 : -1 -> RES = setcc_carry
14671   // a >= b ? -1 :  0 -> RES = setcc_carry
14672   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14673   if (Cond.getOpcode() == X86ISD::SUB) {
14674     Cond = ConvertCmpIfNecessary(Cond, DAG);
14675     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14676
14677     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14678         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14679       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14680                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14681                                 Cond);
14682       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14683         return DAG.getNOT(DL, Res, Res.getValueType());
14684       return Res;
14685     }
14686   }
14687
14688   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14689   // widen the cmov and push the truncate through. This avoids introducing a new
14690   // branch during isel and doesn't add any extensions.
14691   if (Op.getValueType() == MVT::i8 &&
14692       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14693     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14694     if (T1.getValueType() == T2.getValueType() &&
14695         // Blacklist CopyFromReg to avoid partial register stalls.
14696         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14697       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14698       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14699       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14700     }
14701   }
14702
14703   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14704   // condition is true.
14705   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14706   SDValue Ops[] = { Op2, Op1, CC, Cond };
14707   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14708 }
14709
14710 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14711                                        const X86Subtarget *Subtarget,
14712                                        SelectionDAG &DAG) {
14713   MVT VT = Op->getSimpleValueType(0);
14714   SDValue In = Op->getOperand(0);
14715   MVT InVT = In.getSimpleValueType();
14716   MVT VTElt = VT.getVectorElementType();
14717   MVT InVTElt = InVT.getVectorElementType();
14718   SDLoc dl(Op);
14719
14720   // SKX processor
14721   if ((InVTElt == MVT::i1) &&
14722       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14723         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14724
14725        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14726         VTElt.getSizeInBits() <= 16)) ||
14727
14728        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14729         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14730
14731        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14732         VTElt.getSizeInBits() >= 32))))
14733     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14734
14735   unsigned int NumElts = VT.getVectorNumElements();
14736
14737   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14738     return SDValue();
14739
14740   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14741     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14742       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14743     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14744   }
14745
14746   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14747   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14748   SDValue NegOne =
14749    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14750                    ExtVT);
14751   SDValue Zero =
14752    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14753
14754   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14755   if (VT.is512BitVector())
14756     return V;
14757   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14758 }
14759
14760 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14761                                              const X86Subtarget *Subtarget,
14762                                              SelectionDAG &DAG) {
14763   SDValue In = Op->getOperand(0);
14764   MVT VT = Op->getSimpleValueType(0);
14765   MVT InVT = In.getSimpleValueType();
14766   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14767
14768   MVT InSVT = InVT.getScalarType();
14769   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14770
14771   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14772     return SDValue();
14773   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14774     return SDValue();
14775
14776   SDLoc dl(Op);
14777
14778   // SSE41 targets can use the pmovsx* instructions directly.
14779   if (Subtarget->hasSSE41())
14780     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14781
14782   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14783   SDValue Curr = In;
14784   MVT CurrVT = InVT;
14785
14786   // As SRAI is only available on i16/i32 types, we expand only up to i32
14787   // and handle i64 separately.
14788   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14789     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14790     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14791     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14792     Curr = DAG.getBitcast(CurrVT, Curr);
14793   }
14794
14795   SDValue SignExt = Curr;
14796   if (CurrVT != InVT) {
14797     unsigned SignExtShift =
14798         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14799     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14800                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14801   }
14802
14803   if (CurrVT == VT)
14804     return SignExt;
14805
14806   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14807     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14808                                DAG.getConstant(31, dl, MVT::i8));
14809     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14810     return DAG.getBitcast(VT, Ext);
14811   }
14812
14813   return SDValue();
14814 }
14815
14816 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14817                                 SelectionDAG &DAG) {
14818   MVT VT = Op->getSimpleValueType(0);
14819   SDValue In = Op->getOperand(0);
14820   MVT InVT = In.getSimpleValueType();
14821   SDLoc dl(Op);
14822
14823   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14824     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14825
14826   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14827       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14828       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14829     return SDValue();
14830
14831   if (Subtarget->hasInt256())
14832     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14833
14834   // Optimize vectors in AVX mode
14835   // Sign extend  v8i16 to v8i32 and
14836   //              v4i32 to v4i64
14837   //
14838   // Divide input vector into two parts
14839   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14840   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14841   // concat the vectors to original VT
14842
14843   unsigned NumElems = InVT.getVectorNumElements();
14844   SDValue Undef = DAG.getUNDEF(InVT);
14845
14846   SmallVector<int,8> ShufMask1(NumElems, -1);
14847   for (unsigned i = 0; i != NumElems/2; ++i)
14848     ShufMask1[i] = i;
14849
14850   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14851
14852   SmallVector<int,8> ShufMask2(NumElems, -1);
14853   for (unsigned i = 0; i != NumElems/2; ++i)
14854     ShufMask2[i] = i + NumElems/2;
14855
14856   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14857
14858   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14859                                 VT.getVectorNumElements()/2);
14860
14861   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14862   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14863
14864   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14865 }
14866
14867 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14868 // may emit an illegal shuffle but the expansion is still better than scalar
14869 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14870 // we'll emit a shuffle and a arithmetic shift.
14871 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14872 // TODO: It is possible to support ZExt by zeroing the undef values during
14873 // the shuffle phase or after the shuffle.
14874 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14875                                  SelectionDAG &DAG) {
14876   MVT RegVT = Op.getSimpleValueType();
14877   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14878   assert(RegVT.isInteger() &&
14879          "We only custom lower integer vector sext loads.");
14880
14881   // Nothing useful we can do without SSE2 shuffles.
14882   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14883
14884   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14885   SDLoc dl(Ld);
14886   EVT MemVT = Ld->getMemoryVT();
14887   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14888   unsigned RegSz = RegVT.getSizeInBits();
14889
14890   ISD::LoadExtType Ext = Ld->getExtensionType();
14891
14892   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14893          && "Only anyext and sext are currently implemented.");
14894   assert(MemVT != RegVT && "Cannot extend to the same type");
14895   assert(MemVT.isVector() && "Must load a vector from memory");
14896
14897   unsigned NumElems = RegVT.getVectorNumElements();
14898   unsigned MemSz = MemVT.getSizeInBits();
14899   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14900
14901   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14902     // The only way in which we have a legal 256-bit vector result but not the
14903     // integer 256-bit operations needed to directly lower a sextload is if we
14904     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14905     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14906     // correctly legalized. We do this late to allow the canonical form of
14907     // sextload to persist throughout the rest of the DAG combiner -- it wants
14908     // to fold together any extensions it can, and so will fuse a sign_extend
14909     // of an sextload into a sextload targeting a wider value.
14910     SDValue Load;
14911     if (MemSz == 128) {
14912       // Just switch this to a normal load.
14913       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14914                                        "it must be a legal 128-bit vector "
14915                                        "type!");
14916       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14917                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14918                   Ld->isInvariant(), Ld->getAlignment());
14919     } else {
14920       assert(MemSz < 128 &&
14921              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14922       // Do an sext load to a 128-bit vector type. We want to use the same
14923       // number of elements, but elements half as wide. This will end up being
14924       // recursively lowered by this routine, but will succeed as we definitely
14925       // have all the necessary features if we're using AVX1.
14926       EVT HalfEltVT =
14927           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14928       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14929       Load =
14930           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14931                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14932                          Ld->isNonTemporal(), Ld->isInvariant(),
14933                          Ld->getAlignment());
14934     }
14935
14936     // Replace chain users with the new chain.
14937     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14938     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14939
14940     // Finally, do a normal sign-extend to the desired register.
14941     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14942   }
14943
14944   // All sizes must be a power of two.
14945   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14946          "Non-power-of-two elements are not custom lowered!");
14947
14948   // Attempt to load the original value using scalar loads.
14949   // Find the largest scalar type that divides the total loaded size.
14950   MVT SclrLoadTy = MVT::i8;
14951   for (MVT Tp : MVT::integer_valuetypes()) {
14952     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14953       SclrLoadTy = Tp;
14954     }
14955   }
14956
14957   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14958   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14959       (64 <= MemSz))
14960     SclrLoadTy = MVT::f64;
14961
14962   // Calculate the number of scalar loads that we need to perform
14963   // in order to load our vector from memory.
14964   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14965
14966   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14967          "Can only lower sext loads with a single scalar load!");
14968
14969   unsigned loadRegZize = RegSz;
14970   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14971     loadRegZize = 128;
14972
14973   // Represent our vector as a sequence of elements which are the
14974   // largest scalar that we can load.
14975   EVT LoadUnitVecVT = EVT::getVectorVT(
14976       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14977
14978   // Represent the data using the same element type that is stored in
14979   // memory. In practice, we ''widen'' MemVT.
14980   EVT WideVecVT =
14981       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14982                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14983
14984   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14985          "Invalid vector type");
14986
14987   // We can't shuffle using an illegal type.
14988   assert(TLI.isTypeLegal(WideVecVT) &&
14989          "We only lower types that form legal widened vector types");
14990
14991   SmallVector<SDValue, 8> Chains;
14992   SDValue Ptr = Ld->getBasePtr();
14993   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14994                                       TLI.getPointerTy(DAG.getDataLayout()));
14995   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14996
14997   for (unsigned i = 0; i < NumLoads; ++i) {
14998     // Perform a single load.
14999     SDValue ScalarLoad =
15000         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15001                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15002                     Ld->getAlignment());
15003     Chains.push_back(ScalarLoad.getValue(1));
15004     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15005     // another round of DAGCombining.
15006     if (i == 0)
15007       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15008     else
15009       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15010                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
15011
15012     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15013   }
15014
15015   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15016
15017   // Bitcast the loaded value to a vector of the original element type, in
15018   // the size of the target vector type.
15019   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15020   unsigned SizeRatio = RegSz / MemSz;
15021
15022   if (Ext == ISD::SEXTLOAD) {
15023     // If we have SSE4.1, we can directly emit a VSEXT node.
15024     if (Subtarget->hasSSE41()) {
15025       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15026       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15027       return Sext;
15028     }
15029
15030     // Otherwise we'll shuffle the small elements in the high bits of the
15031     // larger type and perform an arithmetic shift. If the shift is not legal
15032     // it's better to scalarize.
15033     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
15034            "We can't implement a sext load without an arithmetic right shift!");
15035
15036     // Redistribute the loaded elements into the different locations.
15037     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15038     for (unsigned i = 0; i != NumElems; ++i)
15039       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
15040
15041     SDValue Shuff = DAG.getVectorShuffle(
15042         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15043
15044     Shuff = DAG.getBitcast(RegVT, Shuff);
15045
15046     // Build the arithmetic shift.
15047     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
15048                    MemVT.getVectorElementType().getSizeInBits();
15049     Shuff =
15050         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
15051                     DAG.getConstant(Amt, dl, RegVT));
15052
15053     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15054     return Shuff;
15055   }
15056
15057   // Redistribute the loaded elements into the different locations.
15058   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15059   for (unsigned i = 0; i != NumElems; ++i)
15060     ShuffleVec[i * SizeRatio] = i;
15061
15062   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15063                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15064
15065   // Bitcast to the requested type.
15066   Shuff = DAG.getBitcast(RegVT, Shuff);
15067   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15068   return Shuff;
15069 }
15070
15071 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15072 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15073 // from the AND / OR.
15074 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15075   Opc = Op.getOpcode();
15076   if (Opc != ISD::OR && Opc != ISD::AND)
15077     return false;
15078   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15079           Op.getOperand(0).hasOneUse() &&
15080           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15081           Op.getOperand(1).hasOneUse());
15082 }
15083
15084 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15085 // 1 and that the SETCC node has a single use.
15086 static bool isXor1OfSetCC(SDValue Op) {
15087   if (Op.getOpcode() != ISD::XOR)
15088     return false;
15089   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15090   if (N1C && N1C->getAPIntValue() == 1) {
15091     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15092       Op.getOperand(0).hasOneUse();
15093   }
15094   return false;
15095 }
15096
15097 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15098   bool addTest = true;
15099   SDValue Chain = Op.getOperand(0);
15100   SDValue Cond  = Op.getOperand(1);
15101   SDValue Dest  = Op.getOperand(2);
15102   SDLoc dl(Op);
15103   SDValue CC;
15104   bool Inverted = false;
15105
15106   if (Cond.getOpcode() == ISD::SETCC) {
15107     // Check for setcc([su]{add,sub,mul}o == 0).
15108     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15109         isa<ConstantSDNode>(Cond.getOperand(1)) &&
15110         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
15111         Cond.getOperand(0).getResNo() == 1 &&
15112         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15113          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15114          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15115          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15116          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15117          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15118       Inverted = true;
15119       Cond = Cond.getOperand(0);
15120     } else {
15121       SDValue NewCond = LowerSETCC(Cond, DAG);
15122       if (NewCond.getNode())
15123         Cond = NewCond;
15124     }
15125   }
15126 #if 0
15127   // FIXME: LowerXALUO doesn't handle these!!
15128   else if (Cond.getOpcode() == X86ISD::ADD  ||
15129            Cond.getOpcode() == X86ISD::SUB  ||
15130            Cond.getOpcode() == X86ISD::SMUL ||
15131            Cond.getOpcode() == X86ISD::UMUL)
15132     Cond = LowerXALUO(Cond, DAG);
15133 #endif
15134
15135   // Look pass (and (setcc_carry (cmp ...)), 1).
15136   if (Cond.getOpcode() == ISD::AND &&
15137       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15138     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15139     if (C && C->getAPIntValue() == 1)
15140       Cond = Cond.getOperand(0);
15141   }
15142
15143   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15144   // setting operand in place of the X86ISD::SETCC.
15145   unsigned CondOpcode = Cond.getOpcode();
15146   if (CondOpcode == X86ISD::SETCC ||
15147       CondOpcode == X86ISD::SETCC_CARRY) {
15148     CC = Cond.getOperand(0);
15149
15150     SDValue Cmp = Cond.getOperand(1);
15151     unsigned Opc = Cmp.getOpcode();
15152     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15153     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15154       Cond = Cmp;
15155       addTest = false;
15156     } else {
15157       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15158       default: break;
15159       case X86::COND_O:
15160       case X86::COND_B:
15161         // These can only come from an arithmetic instruction with overflow,
15162         // e.g. SADDO, UADDO.
15163         Cond = Cond.getNode()->getOperand(1);
15164         addTest = false;
15165         break;
15166       }
15167     }
15168   }
15169   CondOpcode = Cond.getOpcode();
15170   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15171       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15172       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15173        Cond.getOperand(0).getValueType() != MVT::i8)) {
15174     SDValue LHS = Cond.getOperand(0);
15175     SDValue RHS = Cond.getOperand(1);
15176     unsigned X86Opcode;
15177     unsigned X86Cond;
15178     SDVTList VTs;
15179     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15180     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15181     // X86ISD::INC).
15182     switch (CondOpcode) {
15183     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15184     case ISD::SADDO:
15185       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15186         if (C->isOne()) {
15187           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15188           break;
15189         }
15190       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15191     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15192     case ISD::SSUBO:
15193       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15194         if (C->isOne()) {
15195           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15196           break;
15197         }
15198       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15199     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15200     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15201     default: llvm_unreachable("unexpected overflowing operator");
15202     }
15203     if (Inverted)
15204       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15205     if (CondOpcode == ISD::UMULO)
15206       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15207                           MVT::i32);
15208     else
15209       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15210
15211     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15212
15213     if (CondOpcode == ISD::UMULO)
15214       Cond = X86Op.getValue(2);
15215     else
15216       Cond = X86Op.getValue(1);
15217
15218     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15219     addTest = false;
15220   } else {
15221     unsigned CondOpc;
15222     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15223       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15224       if (CondOpc == ISD::OR) {
15225         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15226         // two branches instead of an explicit OR instruction with a
15227         // separate test.
15228         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15229             isX86LogicalCmp(Cmp)) {
15230           CC = Cond.getOperand(0).getOperand(0);
15231           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15232                               Chain, Dest, CC, Cmp);
15233           CC = Cond.getOperand(1).getOperand(0);
15234           Cond = Cmp;
15235           addTest = false;
15236         }
15237       } else { // ISD::AND
15238         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15239         // two branches instead of an explicit AND instruction with a
15240         // separate test. However, we only do this if this block doesn't
15241         // have a fall-through edge, because this requires an explicit
15242         // jmp when the condition is false.
15243         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15244             isX86LogicalCmp(Cmp) &&
15245             Op.getNode()->hasOneUse()) {
15246           X86::CondCode CCode =
15247             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15248           CCode = X86::GetOppositeBranchCondition(CCode);
15249           CC = DAG.getConstant(CCode, dl, MVT::i8);
15250           SDNode *User = *Op.getNode()->use_begin();
15251           // Look for an unconditional branch following this conditional branch.
15252           // We need this because we need to reverse the successors in order
15253           // to implement FCMP_OEQ.
15254           if (User->getOpcode() == ISD::BR) {
15255             SDValue FalseBB = User->getOperand(1);
15256             SDNode *NewBR =
15257               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15258             assert(NewBR == User);
15259             (void)NewBR;
15260             Dest = FalseBB;
15261
15262             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15263                                 Chain, Dest, CC, Cmp);
15264             X86::CondCode CCode =
15265               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15266             CCode = X86::GetOppositeBranchCondition(CCode);
15267             CC = DAG.getConstant(CCode, dl, MVT::i8);
15268             Cond = Cmp;
15269             addTest = false;
15270           }
15271         }
15272       }
15273     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15274       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15275       // It should be transformed during dag combiner except when the condition
15276       // is set by a arithmetics with overflow node.
15277       X86::CondCode CCode =
15278         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15279       CCode = X86::GetOppositeBranchCondition(CCode);
15280       CC = DAG.getConstant(CCode, dl, MVT::i8);
15281       Cond = Cond.getOperand(0).getOperand(1);
15282       addTest = false;
15283     } else if (Cond.getOpcode() == ISD::SETCC &&
15284                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15285       // For FCMP_OEQ, we can emit
15286       // two branches instead of an explicit AND instruction with a
15287       // separate test. However, we only do this if this block doesn't
15288       // have a fall-through edge, because this requires an explicit
15289       // jmp when the condition is false.
15290       if (Op.getNode()->hasOneUse()) {
15291         SDNode *User = *Op.getNode()->use_begin();
15292         // Look for an unconditional branch following this conditional branch.
15293         // We need this because we need to reverse the successors in order
15294         // to implement FCMP_OEQ.
15295         if (User->getOpcode() == ISD::BR) {
15296           SDValue FalseBB = User->getOperand(1);
15297           SDNode *NewBR =
15298             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15299           assert(NewBR == User);
15300           (void)NewBR;
15301           Dest = FalseBB;
15302
15303           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15304                                     Cond.getOperand(0), Cond.getOperand(1));
15305           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15306           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15307           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15308                               Chain, Dest, CC, Cmp);
15309           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15310           Cond = Cmp;
15311           addTest = false;
15312         }
15313       }
15314     } else if (Cond.getOpcode() == ISD::SETCC &&
15315                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15316       // For FCMP_UNE, we can emit
15317       // two branches instead of an explicit AND instruction with a
15318       // separate test. However, we only do this if this block doesn't
15319       // have a fall-through edge, because this requires an explicit
15320       // jmp when the condition is false.
15321       if (Op.getNode()->hasOneUse()) {
15322         SDNode *User = *Op.getNode()->use_begin();
15323         // Look for an unconditional branch following this conditional branch.
15324         // We need this because we need to reverse the successors in order
15325         // to implement FCMP_UNE.
15326         if (User->getOpcode() == ISD::BR) {
15327           SDValue FalseBB = User->getOperand(1);
15328           SDNode *NewBR =
15329             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15330           assert(NewBR == User);
15331           (void)NewBR;
15332
15333           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15334                                     Cond.getOperand(0), Cond.getOperand(1));
15335           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15336           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15337           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15338                               Chain, Dest, CC, Cmp);
15339           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15340           Cond = Cmp;
15341           addTest = false;
15342           Dest = FalseBB;
15343         }
15344       }
15345     }
15346   }
15347
15348   if (addTest) {
15349     // Look pass the truncate if the high bits are known zero.
15350     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15351         Cond = Cond.getOperand(0);
15352
15353     // We know the result of AND is compared against zero. Try to match
15354     // it to BT.
15355     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15356       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15357       if (NewSetCC.getNode()) {
15358         CC = NewSetCC.getOperand(0);
15359         Cond = NewSetCC.getOperand(1);
15360         addTest = false;
15361       }
15362     }
15363   }
15364
15365   if (addTest) {
15366     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15367     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15368     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15369   }
15370   Cond = ConvertCmpIfNecessary(Cond, DAG);
15371   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15372                      Chain, Dest, CC, Cond);
15373 }
15374
15375 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15376 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15377 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15378 // that the guard pages used by the OS virtual memory manager are allocated in
15379 // correct sequence.
15380 SDValue
15381 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15382                                            SelectionDAG &DAG) const {
15383   MachineFunction &MF = DAG.getMachineFunction();
15384   bool SplitStack = MF.shouldSplitStack();
15385   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15386                SplitStack;
15387   SDLoc dl(Op);
15388
15389   if (!Lower) {
15390     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15391     SDNode* Node = Op.getNode();
15392
15393     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15394     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15395         " not tell us which reg is the stack pointer!");
15396     EVT VT = Node->getValueType(0);
15397     SDValue Tmp1 = SDValue(Node, 0);
15398     SDValue Tmp2 = SDValue(Node, 1);
15399     SDValue Tmp3 = Node->getOperand(2);
15400     SDValue Chain = Tmp1.getOperand(0);
15401
15402     // Chain the dynamic stack allocation so that it doesn't modify the stack
15403     // pointer when other instructions are using the stack.
15404     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15405         SDLoc(Node));
15406
15407     SDValue Size = Tmp2.getOperand(1);
15408     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15409     Chain = SP.getValue(1);
15410     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15411     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15412     unsigned StackAlign = TFI.getStackAlignment();
15413     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15414     if (Align > StackAlign)
15415       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15416           DAG.getConstant(-(uint64_t)Align, dl, VT));
15417     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15418
15419     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15420         DAG.getIntPtrConstant(0, dl, true), SDValue(),
15421         SDLoc(Node));
15422
15423     SDValue Ops[2] = { Tmp1, Tmp2 };
15424     return DAG.getMergeValues(Ops, dl);
15425   }
15426
15427   // Get the inputs.
15428   SDValue Chain = Op.getOperand(0);
15429   SDValue Size  = Op.getOperand(1);
15430   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15431   EVT VT = Op.getNode()->getValueType(0);
15432
15433   bool Is64Bit = Subtarget->is64Bit();
15434   MVT SPTy = getPointerTy(DAG.getDataLayout());
15435
15436   if (SplitStack) {
15437     MachineRegisterInfo &MRI = MF.getRegInfo();
15438
15439     if (Is64Bit) {
15440       // The 64 bit implementation of segmented stacks needs to clobber both r10
15441       // r11. This makes it impossible to use it along with nested parameters.
15442       const Function *F = MF.getFunction();
15443
15444       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15445            I != E; ++I)
15446         if (I->hasNestAttr())
15447           report_fatal_error("Cannot use segmented stacks with functions that "
15448                              "have nested arguments.");
15449     }
15450
15451     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15452     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15453     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15454     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15455                                 DAG.getRegister(Vreg, SPTy));
15456     SDValue Ops1[2] = { Value, Chain };
15457     return DAG.getMergeValues(Ops1, dl);
15458   } else {
15459     SDValue Flag;
15460     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15461
15462     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15463     Flag = Chain.getValue(1);
15464     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15465
15466     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15467
15468     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15469     unsigned SPReg = RegInfo->getStackRegister();
15470     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15471     Chain = SP.getValue(1);
15472
15473     if (Align) {
15474       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15475                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15476       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15477     }
15478
15479     SDValue Ops1[2] = { SP, Chain };
15480     return DAG.getMergeValues(Ops1, dl);
15481   }
15482 }
15483
15484 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15485   MachineFunction &MF = DAG.getMachineFunction();
15486   auto PtrVT = getPointerTy(MF.getDataLayout());
15487   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15488
15489   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15490   SDLoc DL(Op);
15491
15492   if (!Subtarget->is64Bit() ||
15493       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15494     // vastart just stores the address of the VarArgsFrameIndex slot into the
15495     // memory location argument.
15496     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15497     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15498                         MachinePointerInfo(SV), false, false, 0);
15499   }
15500
15501   // __va_list_tag:
15502   //   gp_offset         (0 - 6 * 8)
15503   //   fp_offset         (48 - 48 + 8 * 16)
15504   //   overflow_arg_area (point to parameters coming in memory).
15505   //   reg_save_area
15506   SmallVector<SDValue, 8> MemOps;
15507   SDValue FIN = Op.getOperand(1);
15508   // Store gp_offset
15509   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15510                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15511                                                DL, MVT::i32),
15512                                FIN, MachinePointerInfo(SV), false, false, 0);
15513   MemOps.push_back(Store);
15514
15515   // Store fp_offset
15516   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15517   Store = DAG.getStore(Op.getOperand(0), DL,
15518                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15519                                        MVT::i32),
15520                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15521   MemOps.push_back(Store);
15522
15523   // Store ptr to overflow_arg_area
15524   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15525   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15526   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15527                        MachinePointerInfo(SV, 8),
15528                        false, false, 0);
15529   MemOps.push_back(Store);
15530
15531   // Store ptr to reg_save_area.
15532   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15533       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15534   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15535   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15536       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15537   MemOps.push_back(Store);
15538   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15539 }
15540
15541 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15542   assert(Subtarget->is64Bit() &&
15543          "LowerVAARG only handles 64-bit va_arg!");
15544   assert(Op.getNode()->getNumOperands() == 4);
15545
15546   MachineFunction &MF = DAG.getMachineFunction();
15547   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15548     // The Win64 ABI uses char* instead of a structure.
15549     return DAG.expandVAArg(Op.getNode());
15550
15551   SDValue Chain = Op.getOperand(0);
15552   SDValue SrcPtr = Op.getOperand(1);
15553   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15554   unsigned Align = Op.getConstantOperandVal(3);
15555   SDLoc dl(Op);
15556
15557   EVT ArgVT = Op.getNode()->getValueType(0);
15558   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15559   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15560   uint8_t ArgMode;
15561
15562   // Decide which area this value should be read from.
15563   // TODO: Implement the AMD64 ABI in its entirety. This simple
15564   // selection mechanism works only for the basic types.
15565   if (ArgVT == MVT::f80) {
15566     llvm_unreachable("va_arg for f80 not yet implemented");
15567   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15568     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15569   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15570     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15571   } else {
15572     llvm_unreachable("Unhandled argument type in LowerVAARG");
15573   }
15574
15575   if (ArgMode == 2) {
15576     // Sanity Check: Make sure using fp_offset makes sense.
15577     assert(!Subtarget->useSoftFloat() &&
15578            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15579            Subtarget->hasSSE1());
15580   }
15581
15582   // Insert VAARG_64 node into the DAG
15583   // VAARG_64 returns two values: Variable Argument Address, Chain
15584   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15585                        DAG.getConstant(ArgMode, dl, MVT::i8),
15586                        DAG.getConstant(Align, dl, MVT::i32)};
15587   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15588   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15589                                           VTs, InstOps, MVT::i64,
15590                                           MachinePointerInfo(SV),
15591                                           /*Align=*/0,
15592                                           /*Volatile=*/false,
15593                                           /*ReadMem=*/true,
15594                                           /*WriteMem=*/true);
15595   Chain = VAARG.getValue(1);
15596
15597   // Load the next argument and return it
15598   return DAG.getLoad(ArgVT, dl,
15599                      Chain,
15600                      VAARG,
15601                      MachinePointerInfo(),
15602                      false, false, false, 0);
15603 }
15604
15605 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15606                            SelectionDAG &DAG) {
15607   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15608   // where a va_list is still an i8*.
15609   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15610   if (Subtarget->isCallingConvWin64(
15611         DAG.getMachineFunction().getFunction()->getCallingConv()))
15612     // Probably a Win64 va_copy.
15613     return DAG.expandVACopy(Op.getNode());
15614
15615   SDValue Chain = Op.getOperand(0);
15616   SDValue DstPtr = Op.getOperand(1);
15617   SDValue SrcPtr = Op.getOperand(2);
15618   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15619   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15620   SDLoc DL(Op);
15621
15622   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15623                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15624                        false, false,
15625                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15626 }
15627
15628 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15629 // amount is a constant. Takes immediate version of shift as input.
15630 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15631                                           SDValue SrcOp, uint64_t ShiftAmt,
15632                                           SelectionDAG &DAG) {
15633   MVT ElementType = VT.getVectorElementType();
15634
15635   // Fold this packed shift into its first operand if ShiftAmt is 0.
15636   if (ShiftAmt == 0)
15637     return SrcOp;
15638
15639   // Check for ShiftAmt >= element width
15640   if (ShiftAmt >= ElementType.getSizeInBits()) {
15641     if (Opc == X86ISD::VSRAI)
15642       ShiftAmt = ElementType.getSizeInBits() - 1;
15643     else
15644       return DAG.getConstant(0, dl, VT);
15645   }
15646
15647   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15648          && "Unknown target vector shift-by-constant node");
15649
15650   // Fold this packed vector shift into a build vector if SrcOp is a
15651   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15652   if (VT == SrcOp.getSimpleValueType() &&
15653       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15654     SmallVector<SDValue, 8> Elts;
15655     unsigned NumElts = SrcOp->getNumOperands();
15656     ConstantSDNode *ND;
15657
15658     switch(Opc) {
15659     default: llvm_unreachable(nullptr);
15660     case X86ISD::VSHLI:
15661       for (unsigned i=0; i!=NumElts; ++i) {
15662         SDValue CurrentOp = SrcOp->getOperand(i);
15663         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15664           Elts.push_back(CurrentOp);
15665           continue;
15666         }
15667         ND = cast<ConstantSDNode>(CurrentOp);
15668         const APInt &C = ND->getAPIntValue();
15669         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15670       }
15671       break;
15672     case X86ISD::VSRLI:
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.lshr(ShiftAmt), dl, ElementType));
15682       }
15683       break;
15684     case X86ISD::VSRAI:
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.ashr(ShiftAmt), dl, ElementType));
15694       }
15695       break;
15696     }
15697
15698     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15699   }
15700
15701   return DAG.getNode(Opc, dl, VT, SrcOp,
15702                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15703 }
15704
15705 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15706 // may or may not be a constant. Takes immediate version of shift as input.
15707 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15708                                    SDValue SrcOp, SDValue ShAmt,
15709                                    SelectionDAG &DAG) {
15710   MVT SVT = ShAmt.getSimpleValueType();
15711   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15712
15713   // Catch shift-by-constant.
15714   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15715     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15716                                       CShAmt->getZExtValue(), DAG);
15717
15718   // Change opcode to non-immediate version
15719   switch (Opc) {
15720     default: llvm_unreachable("Unknown target vector shift node");
15721     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15722     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15723     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15724   }
15725
15726   const X86Subtarget &Subtarget =
15727       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15728   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15729       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15730     // Let the shuffle legalizer expand this shift amount node.
15731     SDValue Op0 = ShAmt.getOperand(0);
15732     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15733     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15734   } else {
15735     // Need to build a vector containing shift amount.
15736     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15737     SmallVector<SDValue, 4> ShOps;
15738     ShOps.push_back(ShAmt);
15739     if (SVT == MVT::i32) {
15740       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15741       ShOps.push_back(DAG.getUNDEF(SVT));
15742     }
15743     ShOps.push_back(DAG.getUNDEF(SVT));
15744
15745     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15746     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15747   }
15748
15749   // The return type has to be a 128-bit type with the same element
15750   // type as the input type.
15751   MVT EltVT = VT.getVectorElementType();
15752   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15753
15754   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15755   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15756 }
15757
15758 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15759 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15760 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15761 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15762                                     SDValue PreservedSrc,
15763                                     const X86Subtarget *Subtarget,
15764                                     SelectionDAG &DAG) {
15765     EVT VT = Op.getValueType();
15766     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15767                                   MVT::i1, VT.getVectorNumElements());
15768     SDValue VMask = SDValue();
15769     unsigned OpcodeSelect = ISD::VSELECT;
15770     SDLoc dl(Op);
15771
15772     assert(MaskVT.isSimple() && "invalid mask type");
15773
15774     if (isAllOnes(Mask))
15775       return Op;
15776
15777     if (MaskVT.bitsGT(Mask.getValueType())) {
15778       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15779                                          MaskVT.getSizeInBits());
15780       VMask = DAG.getBitcast(MaskVT,
15781                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15782     } else {
15783       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15784                                        Mask.getValueType().getSizeInBits());
15785       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15786       // are extracted by EXTRACT_SUBVECTOR.
15787       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15788                           DAG.getBitcast(BitcastVT, Mask),
15789                           DAG.getIntPtrConstant(0, dl));
15790     }
15791
15792     switch (Op.getOpcode()) {
15793       default: break;
15794       case X86ISD::PCMPEQM:
15795       case X86ISD::PCMPGTM:
15796       case X86ISD::CMPM:
15797       case X86ISD::CMPMU:
15798         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15799       case X86ISD::VFPCLASS:
15800         return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
15801       case X86ISD::VTRUNC:
15802       case X86ISD::VTRUNCS:
15803       case X86ISD::VTRUNCUS:
15804         // We can't use ISD::VSELECT here because it is not always "Legal"
15805         // for the destination type. For example vpmovqb require only AVX512
15806         // and vselect that can operate on byte element type require BWI
15807         OpcodeSelect = X86ISD::SELECT;
15808         break;
15809     }
15810     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15811       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15812     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15813 }
15814
15815 /// \brief Creates an SDNode for a predicated scalar operation.
15816 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15817 /// The mask is coming as MVT::i8 and it should be truncated
15818 /// to MVT::i1 while lowering masking intrinsics.
15819 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15820 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15821 /// for a scalar instruction.
15822 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15823                                     SDValue PreservedSrc,
15824                                     const X86Subtarget *Subtarget,
15825                                     SelectionDAG &DAG) {
15826   if (isAllOnes(Mask))
15827     return Op;
15828
15829   EVT VT = Op.getValueType();
15830   SDLoc dl(Op);
15831   // The mask should be of type MVT::i1
15832   SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15833
15834   if (Op.getOpcode() == X86ISD::FSETCC)
15835     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
15836
15837   if (PreservedSrc.getOpcode() == ISD::UNDEF)
15838     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15839   return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15840 }
15841
15842 static int getSEHRegistrationNodeSize(const Function *Fn) {
15843   if (!Fn->hasPersonalityFn())
15844     report_fatal_error(
15845         "querying registration node size for function without personality");
15846   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15847   // WinEHStatePass for the full struct definition.
15848   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15849   case EHPersonality::MSVC_X86SEH: return 24;
15850   case EHPersonality::MSVC_CXX: return 16;
15851   default: break;
15852   }
15853   report_fatal_error("can only recover FP for MSVC EH personality functions");
15854 }
15855
15856 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15857 /// function or when returning to a parent frame after catching an exception, we
15858 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15859 /// Here's the math:
15860 ///   RegNodeBase = EntryEBP - RegNodeSize
15861 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15862 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15863 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15864 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15865                                    SDValue EntryEBP) {
15866   MachineFunction &MF = DAG.getMachineFunction();
15867   SDLoc dl;
15868
15869   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15870   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15871
15872   // It's possible that the parent function no longer has a personality function
15873   // if the exceptional code was optimized away, in which case we just return
15874   // the incoming EBP.
15875   if (!Fn->hasPersonalityFn())
15876     return EntryEBP;
15877
15878   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15879
15880   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15881   // registration.
15882   MCSymbol *OffsetSym =
15883       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15884           GlobalValue::getRealLinkageName(Fn->getName()));
15885   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15886   SDValue RegNodeFrameOffset =
15887       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15888
15889   // RegNodeBase = EntryEBP - RegNodeSize
15890   // ParentFP = RegNodeBase - RegNodeFrameOffset
15891   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15892                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15893   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15894 }
15895
15896 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15897                                        SelectionDAG &DAG) {
15898   SDLoc dl(Op);
15899   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15900   EVT VT = Op.getValueType();
15901   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15902   if (IntrData) {
15903     switch(IntrData->Type) {
15904     case INTR_TYPE_1OP:
15905       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15906     case INTR_TYPE_2OP:
15907       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15908         Op.getOperand(2));
15909     case INTR_TYPE_2OP_IMM8:
15910       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15911                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
15912     case INTR_TYPE_3OP:
15913       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15914         Op.getOperand(2), Op.getOperand(3));
15915     case INTR_TYPE_4OP:
15916       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15917         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15918     case INTR_TYPE_1OP_MASK_RM: {
15919       SDValue Src = Op.getOperand(1);
15920       SDValue PassThru = Op.getOperand(2);
15921       SDValue Mask = Op.getOperand(3);
15922       SDValue RoundingMode;
15923       // We allways add rounding mode to the Node.
15924       // If the rounding mode is not specified, we add the
15925       // "current direction" mode.
15926       if (Op.getNumOperands() == 4)
15927         RoundingMode =
15928           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15929       else
15930         RoundingMode = Op.getOperand(4);
15931       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15932       if (IntrWithRoundingModeOpcode != 0)
15933         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15934             X86::STATIC_ROUNDING::CUR_DIRECTION)
15935           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15936                                       dl, Op.getValueType(), Src, RoundingMode),
15937                                       Mask, PassThru, Subtarget, DAG);
15938       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15939                                               RoundingMode),
15940                                   Mask, PassThru, Subtarget, DAG);
15941     }
15942     case INTR_TYPE_1OP_MASK: {
15943       SDValue Src = Op.getOperand(1);
15944       SDValue PassThru = Op.getOperand(2);
15945       SDValue Mask = Op.getOperand(3);
15946       // We add rounding mode to the Node when
15947       //   - RM Opcode is specified and
15948       //   - RM is not "current direction".
15949       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15950       if (IntrWithRoundingModeOpcode != 0) {
15951         SDValue Rnd = Op.getOperand(4);
15952         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15953         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15954           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15955                                       dl, Op.getValueType(),
15956                                       Src, Rnd),
15957                                       Mask, PassThru, Subtarget, DAG);
15958         }
15959       }
15960       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15961                                   Mask, PassThru, Subtarget, DAG);
15962     }
15963     case INTR_TYPE_SCALAR_MASK: {
15964       SDValue Src1 = Op.getOperand(1);
15965       SDValue Src2 = Op.getOperand(2);
15966       SDValue passThru = Op.getOperand(3);
15967       SDValue Mask = Op.getOperand(4);
15968       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
15969                                   Mask, passThru, Subtarget, DAG);
15970     }
15971     case INTR_TYPE_SCALAR_MASK_RM: {
15972       SDValue Src1 = Op.getOperand(1);
15973       SDValue Src2 = Op.getOperand(2);
15974       SDValue Src0 = Op.getOperand(3);
15975       SDValue Mask = Op.getOperand(4);
15976       // There are 2 kinds of intrinsics in this group:
15977       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15978       // (2) With rounding mode and sae - 7 operands.
15979       if (Op.getNumOperands() == 6) {
15980         SDValue Sae  = Op.getOperand(5);
15981         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15982         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15983                                                 Sae),
15984                                     Mask, Src0, Subtarget, DAG);
15985       }
15986       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15987       SDValue RoundingMode  = Op.getOperand(5);
15988       SDValue Sae  = Op.getOperand(6);
15989       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15990                                               RoundingMode, Sae),
15991                                   Mask, Src0, Subtarget, DAG);
15992     }
15993     case INTR_TYPE_2OP_MASK: {
15994       SDValue Src1 = Op.getOperand(1);
15995       SDValue Src2 = Op.getOperand(2);
15996       SDValue PassThru = Op.getOperand(3);
15997       SDValue Mask = Op.getOperand(4);
15998       // We specify 2 possible opcodes for intrinsics with rounding modes.
15999       // First, we check if the intrinsic may have non-default rounding mode,
16000       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16001       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16002       if (IntrWithRoundingModeOpcode != 0) {
16003         SDValue Rnd = Op.getOperand(5);
16004         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16005         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16006           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16007                                       dl, Op.getValueType(),
16008                                       Src1, Src2, Rnd),
16009                                       Mask, PassThru, Subtarget, DAG);
16010         }
16011       }
16012       // TODO: Intrinsics should have fast-math-flags to propagate.
16013       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16014                                   Mask, PassThru, Subtarget, DAG);
16015     }
16016     case INTR_TYPE_2OP_MASK_RM: {
16017       SDValue Src1 = Op.getOperand(1);
16018       SDValue Src2 = Op.getOperand(2);
16019       SDValue PassThru = Op.getOperand(3);
16020       SDValue Mask = Op.getOperand(4);
16021       // We specify 2 possible modes for intrinsics, with/without rounding
16022       // modes.
16023       // First, we check if the intrinsic have rounding mode (6 operands),
16024       // if not, we set rounding mode to "current".
16025       SDValue Rnd;
16026       if (Op.getNumOperands() == 6)
16027         Rnd = Op.getOperand(5);
16028       else
16029         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16030       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16031                                               Src1, Src2, Rnd),
16032                                   Mask, PassThru, Subtarget, DAG);
16033     }
16034     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16035       SDValue Src1 = Op.getOperand(1);
16036       SDValue Src2 = Op.getOperand(2);
16037       SDValue Src3 = Op.getOperand(3);
16038       SDValue PassThru = Op.getOperand(4);
16039       SDValue Mask = Op.getOperand(5);
16040       SDValue Sae  = Op.getOperand(6);
16041
16042       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16043                                               Src2, Src3, Sae),
16044                                   Mask, PassThru, Subtarget, DAG);
16045     }
16046     case INTR_TYPE_3OP_MASK_RM: {
16047       SDValue Src1 = Op.getOperand(1);
16048       SDValue Src2 = Op.getOperand(2);
16049       SDValue Imm = Op.getOperand(3);
16050       SDValue PassThru = Op.getOperand(4);
16051       SDValue Mask = Op.getOperand(5);
16052       // We specify 2 possible modes for intrinsics, with/without rounding
16053       // modes.
16054       // First, we check if the intrinsic have rounding mode (7 operands),
16055       // if not, we set rounding mode to "current".
16056       SDValue Rnd;
16057       if (Op.getNumOperands() == 7)
16058         Rnd = Op.getOperand(6);
16059       else
16060         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16061       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16062         Src1, Src2, Imm, Rnd),
16063         Mask, PassThru, Subtarget, DAG);
16064     }
16065     case INTR_TYPE_3OP_IMM8_MASK:
16066     case INTR_TYPE_3OP_MASK:
16067     case INSERT_SUBVEC: {
16068       SDValue Src1 = Op.getOperand(1);
16069       SDValue Src2 = Op.getOperand(2);
16070       SDValue Src3 = Op.getOperand(3);
16071       SDValue PassThru = Op.getOperand(4);
16072       SDValue Mask = Op.getOperand(5);
16073
16074       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16075         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16076       else if (IntrData->Type == INSERT_SUBVEC) {
16077         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16078         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16079         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16080         Imm *= Src2.getValueType().getVectorNumElements();
16081         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16082       }
16083
16084       // We specify 2 possible opcodes for intrinsics with rounding modes.
16085       // First, we check if the intrinsic may have non-default rounding mode,
16086       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16087       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16088       if (IntrWithRoundingModeOpcode != 0) {
16089         SDValue Rnd = Op.getOperand(6);
16090         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16091         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16092           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16093                                       dl, Op.getValueType(),
16094                                       Src1, Src2, Src3, Rnd),
16095                                       Mask, PassThru, Subtarget, DAG);
16096         }
16097       }
16098       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16099                                               Src1, Src2, Src3),
16100                                   Mask, PassThru, Subtarget, DAG);
16101     }
16102     case VPERM_3OP_MASKZ:
16103     case VPERM_3OP_MASK:
16104     case FMA_OP_MASK3:
16105     case FMA_OP_MASKZ:
16106     case FMA_OP_MASK: {
16107       SDValue Src1 = Op.getOperand(1);
16108       SDValue Src2 = Op.getOperand(2);
16109       SDValue Src3 = Op.getOperand(3);
16110       SDValue Mask = Op.getOperand(4);
16111       EVT VT = Op.getValueType();
16112       SDValue PassThru = SDValue();
16113
16114       // set PassThru element
16115       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
16116         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16117       else if (IntrData->Type == FMA_OP_MASK3)
16118         PassThru = Src3;
16119       else
16120         PassThru = Src1;
16121
16122       // We specify 2 possible opcodes for intrinsics with rounding modes.
16123       // First, we check if the intrinsic may have non-default rounding mode,
16124       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16125       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16126       if (IntrWithRoundingModeOpcode != 0) {
16127         SDValue Rnd = Op.getOperand(5);
16128         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16129             X86::STATIC_ROUNDING::CUR_DIRECTION)
16130           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16131                                                   dl, Op.getValueType(),
16132                                                   Src1, Src2, Src3, Rnd),
16133                                       Mask, PassThru, Subtarget, DAG);
16134       }
16135       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16136                                               dl, Op.getValueType(),
16137                                               Src1, Src2, Src3),
16138                                   Mask, PassThru, Subtarget, DAG);
16139     }
16140     case FPCLASS: {
16141       // FPclass intrinsics with mask
16142        SDValue Src1 = Op.getOperand(1);
16143        EVT VT = Src1.getValueType();
16144        EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16145                                       VT.getVectorNumElements());
16146        SDValue Imm = Op.getOperand(2);
16147        SDValue Mask = Op.getOperand(3);
16148        EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16149                                         Mask.getValueType().getSizeInBits());
16150        SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16151        SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16152                                                  DAG.getTargetConstant(0, dl, MaskVT),
16153                                                  Subtarget, DAG);
16154        SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16155                                  DAG.getUNDEF(BitcastVT), FPclassMask,
16156                                  DAG.getIntPtrConstant(0, dl));
16157        return DAG.getBitcast(Op.getValueType(), Res);
16158     }
16159     case CMP_MASK:
16160     case CMP_MASK_CC: {
16161       // Comparison intrinsics with masks.
16162       // Example of transformation:
16163       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16164       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16165       // (i8 (bitcast
16166       //   (v8i1 (insert_subvector undef,
16167       //           (v2i1 (and (PCMPEQM %a, %b),
16168       //                      (extract_subvector
16169       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16170       EVT VT = Op.getOperand(1).getValueType();
16171       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16172                                     VT.getVectorNumElements());
16173       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16174       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16175                                        Mask.getValueType().getSizeInBits());
16176       SDValue Cmp;
16177       if (IntrData->Type == CMP_MASK_CC) {
16178         SDValue CC = Op.getOperand(3);
16179         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16180         // We specify 2 possible opcodes for intrinsics with rounding modes.
16181         // First, we check if the intrinsic may have non-default rounding mode,
16182         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16183         if (IntrData->Opc1 != 0) {
16184           SDValue Rnd = Op.getOperand(5);
16185           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16186               X86::STATIC_ROUNDING::CUR_DIRECTION)
16187             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16188                               Op.getOperand(2), CC, Rnd);
16189         }
16190         //default rounding mode
16191         if(!Cmp.getNode())
16192             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16193                               Op.getOperand(2), CC);
16194
16195       } else {
16196         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16197         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16198                           Op.getOperand(2));
16199       }
16200       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16201                                              DAG.getTargetConstant(0, dl,
16202                                                                    MaskVT),
16203                                              Subtarget, DAG);
16204       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16205                                 DAG.getUNDEF(BitcastVT), CmpMask,
16206                                 DAG.getIntPtrConstant(0, dl));
16207       return DAG.getBitcast(Op.getValueType(), Res);
16208     }
16209     case CMP_MASK_SCALAR_CC: {
16210       SDValue Src1 = Op.getOperand(1);
16211       SDValue Src2 = Op.getOperand(2);
16212       SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16213       SDValue Mask = Op.getOperand(4);
16214
16215       SDValue Cmp;
16216       if (IntrData->Opc1 != 0) {
16217         SDValue Rnd = Op.getOperand(5);
16218         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16219             X86::STATIC_ROUNDING::CUR_DIRECTION)
16220           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16221       }
16222       //default rounding mode
16223       if(!Cmp.getNode())
16224         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16225
16226       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16227                                              DAG.getTargetConstant(0, dl,
16228                                                                    MVT::i1),
16229                                              Subtarget, DAG);
16230
16231       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16232                          DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16233                          DAG.getValueType(MVT::i1));
16234     }
16235     case COMI: { // Comparison intrinsics
16236       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16237       SDValue LHS = Op.getOperand(1);
16238       SDValue RHS = Op.getOperand(2);
16239       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16240       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16241       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16242       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16243                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16244       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16245     }
16246     case VSHIFT:
16247       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16248                                  Op.getOperand(1), Op.getOperand(2), DAG);
16249     case VSHIFT_MASK:
16250       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16251                                                       Op.getSimpleValueType(),
16252                                                       Op.getOperand(1),
16253                                                       Op.getOperand(2), DAG),
16254                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16255                                   DAG);
16256     case COMPRESS_EXPAND_IN_REG: {
16257       SDValue Mask = Op.getOperand(3);
16258       SDValue DataToCompress = Op.getOperand(1);
16259       SDValue PassThru = Op.getOperand(2);
16260       if (isAllOnes(Mask)) // return data as is
16261         return Op.getOperand(1);
16262
16263       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16264                                               DataToCompress),
16265                                   Mask, PassThru, Subtarget, DAG);
16266     }
16267     case BLEND: {
16268       SDValue Mask = Op.getOperand(3);
16269       EVT VT = Op.getValueType();
16270       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16271                                     VT.getVectorNumElements());
16272       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16273                                        Mask.getValueType().getSizeInBits());
16274       SDLoc dl(Op);
16275       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16276                                   DAG.getBitcast(BitcastVT, Mask),
16277                                   DAG.getIntPtrConstant(0, dl));
16278       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16279                          Op.getOperand(2));
16280     }
16281     default:
16282       break;
16283     }
16284   }
16285
16286   switch (IntNo) {
16287   default: return SDValue();    // Don't custom lower most intrinsics.
16288
16289   case Intrinsic::x86_avx2_permd:
16290   case Intrinsic::x86_avx2_permps:
16291     // Operands intentionally swapped. Mask is last operand to intrinsic,
16292     // but second operand for node/instruction.
16293     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16294                        Op.getOperand(2), Op.getOperand(1));
16295
16296   // ptest and testp intrinsics. The intrinsic these come from are designed to
16297   // return an integer value, not just an instruction so lower it to the ptest
16298   // or testp pattern and a setcc for the result.
16299   case Intrinsic::x86_sse41_ptestz:
16300   case Intrinsic::x86_sse41_ptestc:
16301   case Intrinsic::x86_sse41_ptestnzc:
16302   case Intrinsic::x86_avx_ptestz_256:
16303   case Intrinsic::x86_avx_ptestc_256:
16304   case Intrinsic::x86_avx_ptestnzc_256:
16305   case Intrinsic::x86_avx_vtestz_ps:
16306   case Intrinsic::x86_avx_vtestc_ps:
16307   case Intrinsic::x86_avx_vtestnzc_ps:
16308   case Intrinsic::x86_avx_vtestz_pd:
16309   case Intrinsic::x86_avx_vtestc_pd:
16310   case Intrinsic::x86_avx_vtestnzc_pd:
16311   case Intrinsic::x86_avx_vtestz_ps_256:
16312   case Intrinsic::x86_avx_vtestc_ps_256:
16313   case Intrinsic::x86_avx_vtestnzc_ps_256:
16314   case Intrinsic::x86_avx_vtestz_pd_256:
16315   case Intrinsic::x86_avx_vtestc_pd_256:
16316   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16317     bool IsTestPacked = false;
16318     unsigned X86CC;
16319     switch (IntNo) {
16320     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16321     case Intrinsic::x86_avx_vtestz_ps:
16322     case Intrinsic::x86_avx_vtestz_pd:
16323     case Intrinsic::x86_avx_vtestz_ps_256:
16324     case Intrinsic::x86_avx_vtestz_pd_256:
16325       IsTestPacked = true; // Fallthrough
16326     case Intrinsic::x86_sse41_ptestz:
16327     case Intrinsic::x86_avx_ptestz_256:
16328       // ZF = 1
16329       X86CC = X86::COND_E;
16330       break;
16331     case Intrinsic::x86_avx_vtestc_ps:
16332     case Intrinsic::x86_avx_vtestc_pd:
16333     case Intrinsic::x86_avx_vtestc_ps_256:
16334     case Intrinsic::x86_avx_vtestc_pd_256:
16335       IsTestPacked = true; // Fallthrough
16336     case Intrinsic::x86_sse41_ptestc:
16337     case Intrinsic::x86_avx_ptestc_256:
16338       // CF = 1
16339       X86CC = X86::COND_B;
16340       break;
16341     case Intrinsic::x86_avx_vtestnzc_ps:
16342     case Intrinsic::x86_avx_vtestnzc_pd:
16343     case Intrinsic::x86_avx_vtestnzc_ps_256:
16344     case Intrinsic::x86_avx_vtestnzc_pd_256:
16345       IsTestPacked = true; // Fallthrough
16346     case Intrinsic::x86_sse41_ptestnzc:
16347     case Intrinsic::x86_avx_ptestnzc_256:
16348       // ZF and CF = 0
16349       X86CC = X86::COND_A;
16350       break;
16351     }
16352
16353     SDValue LHS = Op.getOperand(1);
16354     SDValue RHS = Op.getOperand(2);
16355     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16356     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16357     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16358     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16359     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16360   }
16361   case Intrinsic::x86_avx512_kortestz_w:
16362   case Intrinsic::x86_avx512_kortestc_w: {
16363     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16364     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16365     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16366     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16367     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16368     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16369     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16370   }
16371
16372   case Intrinsic::x86_sse42_pcmpistria128:
16373   case Intrinsic::x86_sse42_pcmpestria128:
16374   case Intrinsic::x86_sse42_pcmpistric128:
16375   case Intrinsic::x86_sse42_pcmpestric128:
16376   case Intrinsic::x86_sse42_pcmpistrio128:
16377   case Intrinsic::x86_sse42_pcmpestrio128:
16378   case Intrinsic::x86_sse42_pcmpistris128:
16379   case Intrinsic::x86_sse42_pcmpestris128:
16380   case Intrinsic::x86_sse42_pcmpistriz128:
16381   case Intrinsic::x86_sse42_pcmpestriz128: {
16382     unsigned Opcode;
16383     unsigned X86CC;
16384     switch (IntNo) {
16385     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16386     case Intrinsic::x86_sse42_pcmpistria128:
16387       Opcode = X86ISD::PCMPISTRI;
16388       X86CC = X86::COND_A;
16389       break;
16390     case Intrinsic::x86_sse42_pcmpestria128:
16391       Opcode = X86ISD::PCMPESTRI;
16392       X86CC = X86::COND_A;
16393       break;
16394     case Intrinsic::x86_sse42_pcmpistric128:
16395       Opcode = X86ISD::PCMPISTRI;
16396       X86CC = X86::COND_B;
16397       break;
16398     case Intrinsic::x86_sse42_pcmpestric128:
16399       Opcode = X86ISD::PCMPESTRI;
16400       X86CC = X86::COND_B;
16401       break;
16402     case Intrinsic::x86_sse42_pcmpistrio128:
16403       Opcode = X86ISD::PCMPISTRI;
16404       X86CC = X86::COND_O;
16405       break;
16406     case Intrinsic::x86_sse42_pcmpestrio128:
16407       Opcode = X86ISD::PCMPESTRI;
16408       X86CC = X86::COND_O;
16409       break;
16410     case Intrinsic::x86_sse42_pcmpistris128:
16411       Opcode = X86ISD::PCMPISTRI;
16412       X86CC = X86::COND_S;
16413       break;
16414     case Intrinsic::x86_sse42_pcmpestris128:
16415       Opcode = X86ISD::PCMPESTRI;
16416       X86CC = X86::COND_S;
16417       break;
16418     case Intrinsic::x86_sse42_pcmpistriz128:
16419       Opcode = X86ISD::PCMPISTRI;
16420       X86CC = X86::COND_E;
16421       break;
16422     case Intrinsic::x86_sse42_pcmpestriz128:
16423       Opcode = X86ISD::PCMPESTRI;
16424       X86CC = X86::COND_E;
16425       break;
16426     }
16427     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16428     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16429     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16430     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16431                                 DAG.getConstant(X86CC, dl, MVT::i8),
16432                                 SDValue(PCMP.getNode(), 1));
16433     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16434   }
16435
16436   case Intrinsic::x86_sse42_pcmpistri128:
16437   case Intrinsic::x86_sse42_pcmpestri128: {
16438     unsigned Opcode;
16439     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16440       Opcode = X86ISD::PCMPISTRI;
16441     else
16442       Opcode = X86ISD::PCMPESTRI;
16443
16444     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16445     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16446     return DAG.getNode(Opcode, dl, VTs, NewOps);
16447   }
16448
16449   case Intrinsic::x86_seh_lsda: {
16450     // Compute the symbol for the LSDA. We know it'll get emitted later.
16451     MachineFunction &MF = DAG.getMachineFunction();
16452     SDValue Op1 = Op.getOperand(1);
16453     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16454     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16455         GlobalValue::getRealLinkageName(Fn->getName()));
16456
16457     // Generate a simple absolute symbol reference. This intrinsic is only
16458     // supported on 32-bit Windows, which isn't PIC.
16459     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16460     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16461   }
16462
16463   case Intrinsic::x86_seh_recoverfp: {
16464     SDValue FnOp = Op.getOperand(1);
16465     SDValue IncomingFPOp = Op.getOperand(2);
16466     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16467     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16468     if (!Fn)
16469       report_fatal_error(
16470           "llvm.x86.seh.recoverfp must take a function as the first argument");
16471     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16472   }
16473
16474   case Intrinsic::localaddress: {
16475     // Returns one of the stack, base, or frame pointer registers, depending on
16476     // which is used to reference local variables.
16477     MachineFunction &MF = DAG.getMachineFunction();
16478     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16479     unsigned Reg;
16480     if (RegInfo->hasBasePointer(MF))
16481       Reg = RegInfo->getBaseRegister();
16482     else // This function handles the SP or FP case.
16483       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16484     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16485   }
16486   }
16487 }
16488
16489 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16490                               SDValue Src, SDValue Mask, SDValue Base,
16491                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16492                               const X86Subtarget * Subtarget) {
16493   SDLoc dl(Op);
16494   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16495   if (!C)
16496     llvm_unreachable("Invalid scale type");
16497   unsigned ScaleVal = C->getZExtValue();
16498   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16499     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16500
16501   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16502   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16503                              Index.getSimpleValueType().getVectorNumElements());
16504   SDValue MaskInReg;
16505   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16506   if (MaskC)
16507     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16508   else {
16509     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16510                                      Mask.getValueType().getSizeInBits());
16511
16512     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16513     // are extracted by EXTRACT_SUBVECTOR.
16514     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16515                             DAG.getBitcast(BitcastVT, Mask),
16516                             DAG.getIntPtrConstant(0, dl));
16517   }
16518   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16519   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16520   SDValue Segment = DAG.getRegister(0, MVT::i32);
16521   if (Src.getOpcode() == ISD::UNDEF)
16522     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16523   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16524   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16525   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16526   return DAG.getMergeValues(RetOps, dl);
16527 }
16528
16529 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16530                                SDValue Src, SDValue Mask, SDValue Base,
16531                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16532   SDLoc dl(Op);
16533   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16534   if (!C)
16535     llvm_unreachable("Invalid scale type");
16536   unsigned ScaleVal = C->getZExtValue();
16537   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16538     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16539
16540   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16541   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16542   SDValue Segment = DAG.getRegister(0, MVT::i32);
16543   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16544                              Index.getSimpleValueType().getVectorNumElements());
16545   SDValue MaskInReg;
16546   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16547   if (MaskC)
16548     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16549   else {
16550     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16551                                      Mask.getValueType().getSizeInBits());
16552
16553     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16554     // are extracted by EXTRACT_SUBVECTOR.
16555     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16556                             DAG.getBitcast(BitcastVT, Mask),
16557                             DAG.getIntPtrConstant(0, dl));
16558   }
16559   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16560   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16561   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16562   return SDValue(Res, 1);
16563 }
16564
16565 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16566                                SDValue Mask, SDValue Base, SDValue Index,
16567                                SDValue ScaleOp, SDValue Chain) {
16568   SDLoc dl(Op);
16569   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16570   assert(C && "Invalid scale type");
16571   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16572   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16573   SDValue Segment = DAG.getRegister(0, MVT::i32);
16574   EVT MaskVT =
16575     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16576   SDValue MaskInReg;
16577   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16578   if (MaskC)
16579     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16580   else
16581     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16582   //SDVTList VTs = DAG.getVTList(MVT::Other);
16583   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16584   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16585   return SDValue(Res, 0);
16586 }
16587
16588 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16589 // read performance monitor counters (x86_rdpmc).
16590 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16591                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16592                               SmallVectorImpl<SDValue> &Results) {
16593   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16594   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16595   SDValue LO, HI;
16596
16597   // The ECX register is used to select the index of the performance counter
16598   // to read.
16599   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16600                                    N->getOperand(2));
16601   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16602
16603   // Reads the content of a 64-bit performance counter and returns it in the
16604   // registers EDX:EAX.
16605   if (Subtarget->is64Bit()) {
16606     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16607     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16608                             LO.getValue(2));
16609   } else {
16610     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16611     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16612                             LO.getValue(2));
16613   }
16614   Chain = HI.getValue(1);
16615
16616   if (Subtarget->is64Bit()) {
16617     // The EAX register is loaded with the low-order 32 bits. The EDX register
16618     // is loaded with the supported high-order bits of the counter.
16619     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16620                               DAG.getConstant(32, DL, MVT::i8));
16621     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16622     Results.push_back(Chain);
16623     return;
16624   }
16625
16626   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16627   SDValue Ops[] = { LO, HI };
16628   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16629   Results.push_back(Pair);
16630   Results.push_back(Chain);
16631 }
16632
16633 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16634 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16635 // also used to custom lower READCYCLECOUNTER nodes.
16636 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16637                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16638                               SmallVectorImpl<SDValue> &Results) {
16639   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16640   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16641   SDValue LO, HI;
16642
16643   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16644   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16645   // and the EAX register is loaded with the low-order 32 bits.
16646   if (Subtarget->is64Bit()) {
16647     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16648     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16649                             LO.getValue(2));
16650   } else {
16651     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16652     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16653                             LO.getValue(2));
16654   }
16655   SDValue Chain = HI.getValue(1);
16656
16657   if (Opcode == X86ISD::RDTSCP_DAG) {
16658     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16659
16660     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16661     // the ECX register. Add 'ecx' explicitly to the chain.
16662     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16663                                      HI.getValue(2));
16664     // Explicitly store the content of ECX at the location passed in input
16665     // to the 'rdtscp' intrinsic.
16666     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16667                          MachinePointerInfo(), false, false, 0);
16668   }
16669
16670   if (Subtarget->is64Bit()) {
16671     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16672     // the EAX register is loaded with the low-order 32 bits.
16673     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16674                               DAG.getConstant(32, DL, MVT::i8));
16675     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16676     Results.push_back(Chain);
16677     return;
16678   }
16679
16680   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16681   SDValue Ops[] = { LO, HI };
16682   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16683   Results.push_back(Pair);
16684   Results.push_back(Chain);
16685 }
16686
16687 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16688                                      SelectionDAG &DAG) {
16689   SmallVector<SDValue, 2> Results;
16690   SDLoc DL(Op);
16691   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16692                           Results);
16693   return DAG.getMergeValues(Results, DL);
16694 }
16695
16696 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16697                                     SelectionDAG &DAG) {
16698   MachineFunction &MF = DAG.getMachineFunction();
16699   const Function *Fn = MF.getFunction();
16700   SDLoc dl(Op);
16701   SDValue Chain = Op.getOperand(0);
16702
16703   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16704          "using llvm.x86.seh.restoreframe requires a frame pointer");
16705
16706   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16707   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16708
16709   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16710   unsigned FrameReg =
16711       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16712   unsigned SPReg = RegInfo->getStackRegister();
16713   unsigned SlotSize = RegInfo->getSlotSize();
16714
16715   // Get incoming EBP.
16716   SDValue IncomingEBP =
16717       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16718
16719   // SP is saved in the first field of every registration node, so load
16720   // [EBP-RegNodeSize] into SP.
16721   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16722   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16723                                DAG.getConstant(-RegNodeSize, dl, VT));
16724   SDValue NewSP =
16725       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16726                   false, VT.getScalarSizeInBits() / 8);
16727   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16728
16729   if (!RegInfo->needsStackRealignment(MF)) {
16730     // Adjust EBP to point back to the original frame position.
16731     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16732     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16733   } else {
16734     assert(RegInfo->hasBasePointer(MF) &&
16735            "functions with Win32 EH must use frame or base pointer register");
16736
16737     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16738     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16739     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16740
16741     // Reload the spilled EBP value, now that the stack and base pointers are
16742     // set up.
16743     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16744     X86FI->setHasSEHFramePtrSave(true);
16745     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16746     X86FI->setSEHFramePtrSaveIndex(FI);
16747     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16748                                 MachinePointerInfo(), false, false, false,
16749                                 VT.getScalarSizeInBits() / 8);
16750     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16751   }
16752
16753   return Chain;
16754 }
16755
16756 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16757 /// return truncate Store/MaskedStore Node
16758 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16759                                                SelectionDAG &DAG,
16760                                                MVT ElementType) {
16761   SDLoc dl(Op);
16762   SDValue Mask = Op.getOperand(4);
16763   SDValue DataToTruncate = Op.getOperand(3);
16764   SDValue Addr = Op.getOperand(2);
16765   SDValue Chain = Op.getOperand(0);
16766
16767   EVT VT  = DataToTruncate.getValueType();
16768   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16769                              ElementType, VT.getVectorNumElements());
16770
16771   if (isAllOnes(Mask)) // return just a truncate store
16772     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16773                              MachinePointerInfo(), SVT, false, false,
16774                              SVT.getScalarSizeInBits()/8);
16775
16776   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16777                                 MVT::i1, VT.getVectorNumElements());
16778   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16779                                    Mask.getValueType().getSizeInBits());
16780   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16781   // are extracted by EXTRACT_SUBVECTOR.
16782   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16783                               DAG.getBitcast(BitcastVT, Mask),
16784                               DAG.getIntPtrConstant(0, dl));
16785
16786   MachineMemOperand *MMO = DAG.getMachineFunction().
16787     getMachineMemOperand(MachinePointerInfo(),
16788                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16789                          SVT.getScalarSizeInBits()/8);
16790
16791   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16792                             VMask, SVT, MMO, true);
16793 }
16794
16795 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16796                                       SelectionDAG &DAG) {
16797   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16798
16799   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16800   if (!IntrData) {
16801     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16802       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16803     return SDValue();
16804   }
16805
16806   SDLoc dl(Op);
16807   switch(IntrData->Type) {
16808   default:
16809     llvm_unreachable("Unknown Intrinsic Type");
16810     break;
16811   case RDSEED:
16812   case RDRAND: {
16813     // Emit the node with the right value type.
16814     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16815     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16816
16817     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16818     // Otherwise return the value from Rand, which is always 0, casted to i32.
16819     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16820                       DAG.getConstant(1, dl, Op->getValueType(1)),
16821                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16822                       SDValue(Result.getNode(), 1) };
16823     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16824                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16825                                   Ops);
16826
16827     // Return { result, isValid, chain }.
16828     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16829                        SDValue(Result.getNode(), 2));
16830   }
16831   case GATHER: {
16832   //gather(v1, mask, index, base, scale);
16833     SDValue Chain = Op.getOperand(0);
16834     SDValue Src   = Op.getOperand(2);
16835     SDValue Base  = Op.getOperand(3);
16836     SDValue Index = Op.getOperand(4);
16837     SDValue Mask  = Op.getOperand(5);
16838     SDValue Scale = Op.getOperand(6);
16839     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16840                          Chain, Subtarget);
16841   }
16842   case SCATTER: {
16843   //scatter(base, mask, index, v1, scale);
16844     SDValue Chain = Op.getOperand(0);
16845     SDValue Base  = Op.getOperand(2);
16846     SDValue Mask  = Op.getOperand(3);
16847     SDValue Index = Op.getOperand(4);
16848     SDValue Src   = Op.getOperand(5);
16849     SDValue Scale = Op.getOperand(6);
16850     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16851                           Scale, Chain);
16852   }
16853   case PREFETCH: {
16854     SDValue Hint = Op.getOperand(6);
16855     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16856     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16857     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16858     SDValue Chain = Op.getOperand(0);
16859     SDValue Mask  = Op.getOperand(2);
16860     SDValue Index = Op.getOperand(3);
16861     SDValue Base  = Op.getOperand(4);
16862     SDValue Scale = Op.getOperand(5);
16863     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16864   }
16865   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16866   case RDTSC: {
16867     SmallVector<SDValue, 2> Results;
16868     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16869                             Results);
16870     return DAG.getMergeValues(Results, dl);
16871   }
16872   // Read Performance Monitoring Counters.
16873   case RDPMC: {
16874     SmallVector<SDValue, 2> Results;
16875     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16876     return DAG.getMergeValues(Results, dl);
16877   }
16878   // XTEST intrinsics.
16879   case XTEST: {
16880     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16881     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16882     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16883                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16884                                 InTrans);
16885     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16886     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16887                        Ret, SDValue(InTrans.getNode(), 1));
16888   }
16889   // ADC/ADCX/SBB
16890   case ADX: {
16891     SmallVector<SDValue, 2> Results;
16892     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16893     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16894     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16895                                 DAG.getConstant(-1, dl, MVT::i8));
16896     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16897                               Op.getOperand(4), GenCF.getValue(1));
16898     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16899                                  Op.getOperand(5), MachinePointerInfo(),
16900                                  false, false, 0);
16901     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16902                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16903                                 Res.getValue(1));
16904     Results.push_back(SetCC);
16905     Results.push_back(Store);
16906     return DAG.getMergeValues(Results, dl);
16907   }
16908   case COMPRESS_TO_MEM: {
16909     SDLoc dl(Op);
16910     SDValue Mask = Op.getOperand(4);
16911     SDValue DataToCompress = Op.getOperand(3);
16912     SDValue Addr = Op.getOperand(2);
16913     SDValue Chain = Op.getOperand(0);
16914
16915     EVT VT = DataToCompress.getValueType();
16916     if (isAllOnes(Mask)) // return just a store
16917       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16918                           MachinePointerInfo(), false, false,
16919                           VT.getScalarSizeInBits()/8);
16920
16921     SDValue Compressed =
16922       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16923                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16924     return DAG.getStore(Chain, dl, Compressed, Addr,
16925                         MachinePointerInfo(), false, false,
16926                         VT.getScalarSizeInBits()/8);
16927   }
16928   case TRUNCATE_TO_MEM_VI8:
16929     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16930   case TRUNCATE_TO_MEM_VI16:
16931     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16932   case TRUNCATE_TO_MEM_VI32:
16933     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16934   case EXPAND_FROM_MEM: {
16935     SDLoc dl(Op);
16936     SDValue Mask = Op.getOperand(4);
16937     SDValue PassThru = Op.getOperand(3);
16938     SDValue Addr = Op.getOperand(2);
16939     SDValue Chain = Op.getOperand(0);
16940     EVT VT = Op.getValueType();
16941
16942     if (isAllOnes(Mask)) // return just a load
16943       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16944                          false, VT.getScalarSizeInBits()/8);
16945
16946     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16947                                        false, false, false,
16948                                        VT.getScalarSizeInBits()/8);
16949
16950     SDValue Results[] = {
16951       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16952                            Mask, PassThru, Subtarget, DAG), Chain};
16953     return DAG.getMergeValues(Results, dl);
16954   }
16955   }
16956 }
16957
16958 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16959                                            SelectionDAG &DAG) const {
16960   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16961   MFI->setReturnAddressIsTaken(true);
16962
16963   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16964     return SDValue();
16965
16966   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16967   SDLoc dl(Op);
16968   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16969
16970   if (Depth > 0) {
16971     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16972     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16973     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16974     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16975                        DAG.getNode(ISD::ADD, dl, PtrVT,
16976                                    FrameAddr, Offset),
16977                        MachinePointerInfo(), false, false, false, 0);
16978   }
16979
16980   // Just load the return address.
16981   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16982   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16983                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16984 }
16985
16986 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16987   MachineFunction &MF = DAG.getMachineFunction();
16988   MachineFrameInfo *MFI = MF.getFrameInfo();
16989   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16990   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16991   EVT VT = Op.getValueType();
16992
16993   MFI->setFrameAddressIsTaken(true);
16994
16995   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16996     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16997     // is not possible to crawl up the stack without looking at the unwind codes
16998     // simultaneously.
16999     int FrameAddrIndex = FuncInfo->getFAIndex();
17000     if (!FrameAddrIndex) {
17001       // Set up a frame object for the return address.
17002       unsigned SlotSize = RegInfo->getSlotSize();
17003       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17004           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17005       FuncInfo->setFAIndex(FrameAddrIndex);
17006     }
17007     return DAG.getFrameIndex(FrameAddrIndex, VT);
17008   }
17009
17010   unsigned FrameReg =
17011       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17012   SDLoc dl(Op);  // FIXME probably not meaningful
17013   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17014   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17015           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17016          "Invalid Frame Register!");
17017   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17018   while (Depth--)
17019     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17020                             MachinePointerInfo(),
17021                             false, false, false, 0);
17022   return FrameAddr;
17023 }
17024
17025 // FIXME? Maybe this could be a TableGen attribute on some registers and
17026 // this table could be generated automatically from RegInfo.
17027 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17028                                               SelectionDAG &DAG) const {
17029   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17030   const MachineFunction &MF = DAG.getMachineFunction();
17031
17032   unsigned Reg = StringSwitch<unsigned>(RegName)
17033                        .Case("esp", X86::ESP)
17034                        .Case("rsp", X86::RSP)
17035                        .Case("ebp", X86::EBP)
17036                        .Case("rbp", X86::RBP)
17037                        .Default(0);
17038
17039   if (Reg == X86::EBP || Reg == X86::RBP) {
17040     if (!TFI.hasFP(MF))
17041       report_fatal_error("register " + StringRef(RegName) +
17042                          " is allocatable: function has no frame pointer");
17043 #ifndef NDEBUG
17044     else {
17045       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17046       unsigned FrameReg =
17047           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17048       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17049              "Invalid Frame Register!");
17050     }
17051 #endif
17052   }
17053
17054   if (Reg)
17055     return Reg;
17056
17057   report_fatal_error("Invalid register name global variable");
17058 }
17059
17060 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17061                                                      SelectionDAG &DAG) const {
17062   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17063   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17064 }
17065
17066 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17067   SDValue Chain     = Op.getOperand(0);
17068   SDValue Offset    = Op.getOperand(1);
17069   SDValue Handler   = Op.getOperand(2);
17070   SDLoc dl      (Op);
17071
17072   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17073   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17074   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17075   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17076           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17077          "Invalid Frame Register!");
17078   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17079   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17080
17081   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17082                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17083                                                        dl));
17084   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17085   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17086                        false, false, 0);
17087   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17088
17089   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17090                      DAG.getRegister(StoreAddrReg, PtrVT));
17091 }
17092
17093 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17094                                                SelectionDAG &DAG) const {
17095   SDLoc DL(Op);
17096   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17097                      DAG.getVTList(MVT::i32, MVT::Other),
17098                      Op.getOperand(0), Op.getOperand(1));
17099 }
17100
17101 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17102                                                 SelectionDAG &DAG) const {
17103   SDLoc DL(Op);
17104   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17105                      Op.getOperand(0), Op.getOperand(1));
17106 }
17107
17108 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17109   return Op.getOperand(0);
17110 }
17111
17112 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17113                                                 SelectionDAG &DAG) const {
17114   SDValue Root = Op.getOperand(0);
17115   SDValue Trmp = Op.getOperand(1); // trampoline
17116   SDValue FPtr = Op.getOperand(2); // nested function
17117   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17118   SDLoc dl (Op);
17119
17120   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17121   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17122
17123   if (Subtarget->is64Bit()) {
17124     SDValue OutChains[6];
17125
17126     // Large code-model.
17127     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17128     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17129
17130     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17131     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17132
17133     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17134
17135     // Load the pointer to the nested function into R11.
17136     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17137     SDValue Addr = Trmp;
17138     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17139                                 Addr, MachinePointerInfo(TrmpAddr),
17140                                 false, false, 0);
17141
17142     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17143                        DAG.getConstant(2, dl, MVT::i64));
17144     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17145                                 MachinePointerInfo(TrmpAddr, 2),
17146                                 false, false, 2);
17147
17148     // Load the 'nest' parameter value into R10.
17149     // R10 is specified in X86CallingConv.td
17150     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17151     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17152                        DAG.getConstant(10, dl, MVT::i64));
17153     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17154                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17155                                 false, false, 0);
17156
17157     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17158                        DAG.getConstant(12, dl, MVT::i64));
17159     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17160                                 MachinePointerInfo(TrmpAddr, 12),
17161                                 false, false, 2);
17162
17163     // Jump to the nested function.
17164     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17165     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17166                        DAG.getConstant(20, dl, MVT::i64));
17167     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17168                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17169                                 false, false, 0);
17170
17171     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17172     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17173                        DAG.getConstant(22, dl, MVT::i64));
17174     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17175                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17176                                 false, false, 0);
17177
17178     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17179   } else {
17180     const Function *Func =
17181       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17182     CallingConv::ID CC = Func->getCallingConv();
17183     unsigned NestReg;
17184
17185     switch (CC) {
17186     default:
17187       llvm_unreachable("Unsupported calling convention");
17188     case CallingConv::C:
17189     case CallingConv::X86_StdCall: {
17190       // Pass 'nest' parameter in ECX.
17191       // Must be kept in sync with X86CallingConv.td
17192       NestReg = X86::ECX;
17193
17194       // Check that ECX wasn't needed by an 'inreg' parameter.
17195       FunctionType *FTy = Func->getFunctionType();
17196       const AttributeSet &Attrs = Func->getAttributes();
17197
17198       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17199         unsigned InRegCount = 0;
17200         unsigned Idx = 1;
17201
17202         for (FunctionType::param_iterator I = FTy->param_begin(),
17203              E = FTy->param_end(); I != E; ++I, ++Idx)
17204           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17205             auto &DL = DAG.getDataLayout();
17206             // FIXME: should only count parameters that are lowered to integers.
17207             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17208           }
17209
17210         if (InRegCount > 2) {
17211           report_fatal_error("Nest register in use - reduce number of inreg"
17212                              " parameters!");
17213         }
17214       }
17215       break;
17216     }
17217     case CallingConv::X86_FastCall:
17218     case CallingConv::X86_ThisCall:
17219     case CallingConv::Fast:
17220       // Pass 'nest' parameter in EAX.
17221       // Must be kept in sync with X86CallingConv.td
17222       NestReg = X86::EAX;
17223       break;
17224     }
17225
17226     SDValue OutChains[4];
17227     SDValue Addr, Disp;
17228
17229     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17230                        DAG.getConstant(10, dl, MVT::i32));
17231     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17232
17233     // This is storing the opcode for MOV32ri.
17234     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17235     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17236     OutChains[0] = DAG.getStore(Root, dl,
17237                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17238                                 Trmp, MachinePointerInfo(TrmpAddr),
17239                                 false, false, 0);
17240
17241     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17242                        DAG.getConstant(1, dl, MVT::i32));
17243     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17244                                 MachinePointerInfo(TrmpAddr, 1),
17245                                 false, false, 1);
17246
17247     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17248     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17249                        DAG.getConstant(5, dl, MVT::i32));
17250     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17251                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17252                                 false, false, 1);
17253
17254     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17255                        DAG.getConstant(6, dl, MVT::i32));
17256     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17257                                 MachinePointerInfo(TrmpAddr, 6),
17258                                 false, false, 1);
17259
17260     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17261   }
17262 }
17263
17264 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17265                                             SelectionDAG &DAG) const {
17266   /*
17267    The rounding mode is in bits 11:10 of FPSR, and has the following
17268    settings:
17269      00 Round to nearest
17270      01 Round to -inf
17271      10 Round to +inf
17272      11 Round to 0
17273
17274   FLT_ROUNDS, on the other hand, expects the following:
17275     -1 Undefined
17276      0 Round to 0
17277      1 Round to nearest
17278      2 Round to +inf
17279      3 Round to -inf
17280
17281   To perform the conversion, we do:
17282     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17283   */
17284
17285   MachineFunction &MF = DAG.getMachineFunction();
17286   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17287   unsigned StackAlignment = TFI.getStackAlignment();
17288   MVT VT = Op.getSimpleValueType();
17289   SDLoc DL(Op);
17290
17291   // Save FP Control Word to stack slot
17292   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17293   SDValue StackSlot =
17294       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17295
17296   MachineMemOperand *MMO =
17297       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17298                               MachineMemOperand::MOStore, 2, 2);
17299
17300   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17301   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17302                                           DAG.getVTList(MVT::Other),
17303                                           Ops, MVT::i16, MMO);
17304
17305   // Load FP Control Word from stack slot
17306   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17307                             MachinePointerInfo(), false, false, false, 0);
17308
17309   // Transform as necessary
17310   SDValue CWD1 =
17311     DAG.getNode(ISD::SRL, DL, MVT::i16,
17312                 DAG.getNode(ISD::AND, DL, MVT::i16,
17313                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17314                 DAG.getConstant(11, DL, MVT::i8));
17315   SDValue CWD2 =
17316     DAG.getNode(ISD::SRL, DL, MVT::i16,
17317                 DAG.getNode(ISD::AND, DL, MVT::i16,
17318                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17319                 DAG.getConstant(9, DL, MVT::i8));
17320
17321   SDValue RetVal =
17322     DAG.getNode(ISD::AND, DL, MVT::i16,
17323                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17324                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17325                             DAG.getConstant(1, DL, MVT::i16)),
17326                 DAG.getConstant(3, DL, MVT::i16));
17327
17328   return DAG.getNode((VT.getSizeInBits() < 16 ?
17329                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17330 }
17331
17332 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
17333   MVT VT = Op.getSimpleValueType();
17334   EVT OpVT = VT;
17335   unsigned NumBits = VT.getSizeInBits();
17336   SDLoc dl(Op);
17337
17338   Op = Op.getOperand(0);
17339   if (VT == MVT::i8) {
17340     // Zero extend to i32 since there is not an i8 bsr.
17341     OpVT = MVT::i32;
17342     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17343   }
17344
17345   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17346   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17347   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17348
17349   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17350   SDValue Ops[] = {
17351     Op,
17352     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17353     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17354     Op.getValue(1)
17355   };
17356   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17357
17358   // Finally xor with NumBits-1.
17359   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17360                    DAG.getConstant(NumBits - 1, dl, OpVT));
17361
17362   if (VT == MVT::i8)
17363     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17364   return Op;
17365 }
17366
17367 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17368   MVT VT = Op.getSimpleValueType();
17369   EVT OpVT = VT;
17370   unsigned NumBits = VT.getSizeInBits();
17371   SDLoc dl(Op);
17372
17373   Op = Op.getOperand(0);
17374   if (VT == MVT::i8) {
17375     // Zero extend to i32 since there is not an i8 bsr.
17376     OpVT = MVT::i32;
17377     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17378   }
17379
17380   // Issue a bsr (scan bits in reverse).
17381   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17382   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17383
17384   // And xor with NumBits-1.
17385   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17386                    DAG.getConstant(NumBits - 1, dl, OpVT));
17387
17388   if (VT == MVT::i8)
17389     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17390   return Op;
17391 }
17392
17393 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17394   MVT VT = Op.getSimpleValueType();
17395   unsigned NumBits = VT.getScalarSizeInBits();
17396   SDLoc dl(Op);
17397
17398   if (VT.isVector()) {
17399     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17400
17401     SDValue N0 = Op.getOperand(0);
17402     SDValue Zero = DAG.getConstant(0, dl, VT);
17403
17404     // lsb(x) = (x & -x)
17405     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
17406                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
17407
17408     // cttz_undef(x) = (width - 1) - ctlz(lsb)
17409     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
17410         TLI.isOperationLegal(ISD::CTLZ, VT)) {
17411       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
17412       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
17413                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
17414     }
17415
17416     // cttz(x) = ctpop(lsb - 1)
17417     SDValue One = DAG.getConstant(1, dl, VT);
17418     return DAG.getNode(ISD::CTPOP, dl, VT,
17419                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
17420   }
17421
17422   assert(Op.getOpcode() == ISD::CTTZ &&
17423          "Only scalar CTTZ requires custom lowering");
17424
17425   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17426   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17427   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
17428
17429   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17430   SDValue Ops[] = {
17431     Op,
17432     DAG.getConstant(NumBits, dl, VT),
17433     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17434     Op.getValue(1)
17435   };
17436   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17437 }
17438
17439 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17440 // ones, and then concatenate the result back.
17441 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17442   MVT VT = Op.getSimpleValueType();
17443
17444   assert(VT.is256BitVector() && VT.isInteger() &&
17445          "Unsupported value type for operation");
17446
17447   unsigned NumElems = VT.getVectorNumElements();
17448   SDLoc dl(Op);
17449
17450   // Extract the LHS vectors
17451   SDValue LHS = Op.getOperand(0);
17452   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17453   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17454
17455   // Extract the RHS vectors
17456   SDValue RHS = Op.getOperand(1);
17457   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17458   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17459
17460   MVT EltVT = VT.getVectorElementType();
17461   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17462
17463   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17464                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17465                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17466 }
17467
17468 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17469   if (Op.getValueType() == MVT::i1)
17470     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17471                        Op.getOperand(0), Op.getOperand(1));
17472   assert(Op.getSimpleValueType().is256BitVector() &&
17473          Op.getSimpleValueType().isInteger() &&
17474          "Only handle AVX 256-bit vector integer operation");
17475   return Lower256IntArith(Op, DAG);
17476 }
17477
17478 static SDValue LowerSUB(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 LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17489   assert(Op.getSimpleValueType().is256BitVector() &&
17490          Op.getSimpleValueType().isInteger() &&
17491          "Only handle AVX 256-bit vector integer operation");
17492   return Lower256IntArith(Op, DAG);
17493 }
17494
17495 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17496                         SelectionDAG &DAG) {
17497   SDLoc dl(Op);
17498   MVT VT = Op.getSimpleValueType();
17499
17500   if (VT == MVT::i1)
17501     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17502
17503   // Decompose 256-bit ops into smaller 128-bit ops.
17504   if (VT.is256BitVector() && !Subtarget->hasInt256())
17505     return Lower256IntArith(Op, DAG);
17506
17507   SDValue A = Op.getOperand(0);
17508   SDValue B = Op.getOperand(1);
17509
17510   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17511   // pairs, multiply and truncate.
17512   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17513     if (Subtarget->hasInt256()) {
17514       if (VT == MVT::v32i8) {
17515         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17516         SDValue Lo = DAG.getIntPtrConstant(0, dl);
17517         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17518         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17519         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17520         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17521         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17522         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17523                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17524                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17525       }
17526
17527       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17528       return DAG.getNode(
17529           ISD::TRUNCATE, dl, VT,
17530           DAG.getNode(ISD::MUL, dl, ExVT,
17531                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17532                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17533     }
17534
17535     assert(VT == MVT::v16i8 &&
17536            "Pre-AVX2 support only supports v16i8 multiplication");
17537     MVT ExVT = MVT::v8i16;
17538
17539     // Extract the lo parts and sign extend to i16
17540     SDValue ALo, BLo;
17541     if (Subtarget->hasSSE41()) {
17542       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17543       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17544     } else {
17545       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17546                               -1, 4, -1, 5, -1, 6, -1, 7};
17547       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17548       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17549       ALo = DAG.getBitcast(ExVT, ALo);
17550       BLo = DAG.getBitcast(ExVT, BLo);
17551       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17552       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17553     }
17554
17555     // Extract the hi parts and sign extend to i16
17556     SDValue AHi, BHi;
17557     if (Subtarget->hasSSE41()) {
17558       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17559                               -1, -1, -1, -1, -1, -1, -1, -1};
17560       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17561       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17562       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17563       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17564     } else {
17565       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17566                               -1, 12, -1, 13, -1, 14, -1, 15};
17567       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17568       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17569       AHi = DAG.getBitcast(ExVT, AHi);
17570       BHi = DAG.getBitcast(ExVT, BHi);
17571       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17572       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17573     }
17574
17575     // Multiply, mask the lower 8bits of the lo/hi results and pack
17576     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17577     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17578     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17579     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17580     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17581   }
17582
17583   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17584   if (VT == MVT::v4i32) {
17585     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17586            "Should not custom lower when pmuldq is available!");
17587
17588     // Extract the odd parts.
17589     static const int UnpackMask[] = { 1, -1, 3, -1 };
17590     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17591     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17592
17593     // Multiply the even parts.
17594     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17595     // Now multiply odd parts.
17596     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17597
17598     Evens = DAG.getBitcast(VT, Evens);
17599     Odds = DAG.getBitcast(VT, Odds);
17600
17601     // Merge the two vectors back together with a shuffle. This expands into 2
17602     // shuffles.
17603     static const int ShufMask[] = { 0, 4, 2, 6 };
17604     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17605   }
17606
17607   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17608          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17609
17610   //  Ahi = psrlqi(a, 32);
17611   //  Bhi = psrlqi(b, 32);
17612   //
17613   //  AloBlo = pmuludq(a, b);
17614   //  AloBhi = pmuludq(a, Bhi);
17615   //  AhiBlo = pmuludq(Ahi, b);
17616
17617   //  AloBhi = psllqi(AloBhi, 32);
17618   //  AhiBlo = psllqi(AhiBlo, 32);
17619   //  return AloBlo + AloBhi + AhiBlo;
17620
17621   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17622   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17623
17624   SDValue AhiBlo = Ahi;
17625   SDValue AloBhi = Bhi;
17626   // Bit cast to 32-bit vectors for MULUDQ
17627   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17628                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17629   A = DAG.getBitcast(MulVT, A);
17630   B = DAG.getBitcast(MulVT, B);
17631   Ahi = DAG.getBitcast(MulVT, Ahi);
17632   Bhi = DAG.getBitcast(MulVT, Bhi);
17633
17634   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17635   // After shifting right const values the result may be all-zero.
17636   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17637     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17638     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17639   }
17640   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17641     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17642     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17643   }
17644
17645   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17646   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17647 }
17648
17649 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17650   assert(Subtarget->isTargetWin64() && "Unexpected target");
17651   EVT VT = Op.getValueType();
17652   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17653          "Unexpected return type for lowering");
17654
17655   RTLIB::Libcall LC;
17656   bool isSigned;
17657   switch (Op->getOpcode()) {
17658   default: llvm_unreachable("Unexpected request for libcall!");
17659   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17660   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17661   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17662   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17663   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17664   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17665   }
17666
17667   SDLoc dl(Op);
17668   SDValue InChain = DAG.getEntryNode();
17669
17670   TargetLowering::ArgListTy Args;
17671   TargetLowering::ArgListEntry Entry;
17672   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17673     EVT ArgVT = Op->getOperand(i).getValueType();
17674     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17675            "Unexpected argument type for lowering");
17676     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17677     Entry.Node = StackPtr;
17678     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17679                            false, false, 16);
17680     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17681     Entry.Ty = PointerType::get(ArgTy,0);
17682     Entry.isSExt = false;
17683     Entry.isZExt = false;
17684     Args.push_back(Entry);
17685   }
17686
17687   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17688                                          getPointerTy(DAG.getDataLayout()));
17689
17690   TargetLowering::CallLoweringInfo CLI(DAG);
17691   CLI.setDebugLoc(dl).setChain(InChain)
17692     .setCallee(getLibcallCallingConv(LC),
17693                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17694                Callee, std::move(Args), 0)
17695     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17696
17697   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17698   return DAG.getBitcast(VT, CallInfo.first);
17699 }
17700
17701 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17702                              SelectionDAG &DAG) {
17703   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17704   EVT VT = Op0.getValueType();
17705   SDLoc dl(Op);
17706
17707   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17708          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17709
17710   // PMULxD operations multiply each even value (starting at 0) of LHS with
17711   // the related value of RHS and produce a widen result.
17712   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17713   // => <2 x i64> <ae|cg>
17714   //
17715   // In other word, to have all the results, we need to perform two PMULxD:
17716   // 1. one with the even values.
17717   // 2. one with the odd values.
17718   // To achieve #2, with need to place the odd values at an even position.
17719   //
17720   // Place the odd value at an even position (basically, shift all values 1
17721   // step to the left):
17722   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17723   // <a|b|c|d> => <b|undef|d|undef>
17724   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17725   // <e|f|g|h> => <f|undef|h|undef>
17726   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17727
17728   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17729   // ints.
17730   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17731   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17732   unsigned Opcode =
17733       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17734   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17735   // => <2 x i64> <ae|cg>
17736   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17737   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17738   // => <2 x i64> <bf|dh>
17739   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17740
17741   // Shuffle it back into the right order.
17742   SDValue Highs, Lows;
17743   if (VT == MVT::v8i32) {
17744     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17745     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17746     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17747     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17748   } else {
17749     const int HighMask[] = {1, 5, 3, 7};
17750     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17751     const int LowMask[] = {0, 4, 2, 6};
17752     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17753   }
17754
17755   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17756   // unsigned multiply.
17757   if (IsSigned && !Subtarget->hasSSE41()) {
17758     SDValue ShAmt = DAG.getConstant(
17759         31, dl,
17760         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17761     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17762                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17763     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17764                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17765
17766     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17767     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17768   }
17769
17770   // The first result of MUL_LOHI is actually the low value, followed by the
17771   // high value.
17772   SDValue Ops[] = {Lows, Highs};
17773   return DAG.getMergeValues(Ops, dl);
17774 }
17775
17776 // Return true if the required (according to Opcode) shift-imm form is natively
17777 // supported by the Subtarget
17778 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17779                                         unsigned Opcode) {
17780   if (VT.getScalarSizeInBits() < 16)
17781     return false;
17782
17783   if (VT.is512BitVector() &&
17784       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17785     return true;
17786
17787   bool LShift = VT.is128BitVector() ||
17788     (VT.is256BitVector() && Subtarget->hasInt256());
17789
17790   bool AShift = LShift && (Subtarget->hasVLX() ||
17791     (VT != MVT::v2i64 && VT != MVT::v4i64));
17792   return (Opcode == ISD::SRA) ? AShift : LShift;
17793 }
17794
17795 // The shift amount is a variable, but it is the same for all vector lanes.
17796 // These instructions are defined together with shift-immediate.
17797 static
17798 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17799                                       unsigned Opcode) {
17800   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17801 }
17802
17803 // Return true if the required (according to Opcode) variable-shift form is
17804 // natively supported by the Subtarget
17805 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17806                                     unsigned Opcode) {
17807
17808   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17809     return false;
17810
17811   // vXi16 supported only on AVX-512, BWI
17812   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17813     return false;
17814
17815   if (VT.is512BitVector() || Subtarget->hasVLX())
17816     return true;
17817
17818   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17819   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17820   return (Opcode == ISD::SRA) ? AShift : LShift;
17821 }
17822
17823 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17824                                          const X86Subtarget *Subtarget) {
17825   MVT VT = Op.getSimpleValueType();
17826   SDLoc dl(Op);
17827   SDValue R = Op.getOperand(0);
17828   SDValue Amt = Op.getOperand(1);
17829
17830   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17831     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17832
17833   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17834     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17835     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17836     SDValue Ex = DAG.getBitcast(ExVT, R);
17837
17838     if (ShiftAmt >= 32) {
17839       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17840       SDValue Upper =
17841           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17842       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17843                                                  ShiftAmt - 32, DAG);
17844       if (VT == MVT::v2i64)
17845         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17846       if (VT == MVT::v4i64)
17847         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17848                                   {9, 1, 11, 3, 13, 5, 15, 7});
17849     } else {
17850       // SRA upper i32, SHL whole i64 and select lower i32.
17851       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17852                                                  ShiftAmt, DAG);
17853       SDValue Lower =
17854           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17855       Lower = DAG.getBitcast(ExVT, Lower);
17856       if (VT == MVT::v2i64)
17857         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17858       if (VT == MVT::v4i64)
17859         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17860                                   {8, 1, 10, 3, 12, 5, 14, 7});
17861     }
17862     return DAG.getBitcast(VT, Ex);
17863   };
17864
17865   // Optimize shl/srl/sra with constant shift amount.
17866   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17867     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17868       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17869
17870       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17871         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17872
17873       // i64 SRA needs to be performed as partial shifts.
17874       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17875           Op.getOpcode() == ISD::SRA)
17876         return ArithmeticShiftRight64(ShiftAmt);
17877
17878       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17879         unsigned NumElts = VT.getVectorNumElements();
17880         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17881
17882         if (Op.getOpcode() == ISD::SHL) {
17883           // Simple i8 add case
17884           if (ShiftAmt == 1)
17885             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17886
17887           // Make a large shift.
17888           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17889                                                    R, ShiftAmt, DAG);
17890           SHL = DAG.getBitcast(VT, SHL);
17891           // Zero out the rightmost bits.
17892           SmallVector<SDValue, 32> V(
17893               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17894           return DAG.getNode(ISD::AND, dl, VT, SHL,
17895                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17896         }
17897         if (Op.getOpcode() == ISD::SRL) {
17898           // Make a large shift.
17899           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17900                                                    R, ShiftAmt, DAG);
17901           SRL = DAG.getBitcast(VT, SRL);
17902           // Zero out the leftmost bits.
17903           SmallVector<SDValue, 32> V(
17904               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17905           return DAG.getNode(ISD::AND, dl, VT, SRL,
17906                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17907         }
17908         if (Op.getOpcode() == ISD::SRA) {
17909           if (ShiftAmt == 7) {
17910             // ashr(R, 7)  === cmp_slt(R, 0)
17911             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17912             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17913           }
17914
17915           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17916           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17917           SmallVector<SDValue, 32> V(NumElts,
17918                                      DAG.getConstant(128 >> ShiftAmt, dl,
17919                                                      MVT::i8));
17920           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17921           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17922           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17923           return Res;
17924         }
17925         llvm_unreachable("Unknown shift opcode.");
17926       }
17927     }
17928   }
17929
17930   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17931   if (!Subtarget->is64Bit() &&
17932       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17933
17934     // Peek through any splat that was introduced for i64 shift vectorization.
17935     int SplatIndex = -1;
17936     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17937       if (SVN->isSplat()) {
17938         SplatIndex = SVN->getSplatIndex();
17939         Amt = Amt.getOperand(0);
17940         assert(SplatIndex < (int)VT.getVectorNumElements() &&
17941                "Splat shuffle referencing second operand");
17942       }
17943
17944     if (Amt.getOpcode() != ISD::BITCAST ||
17945         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17946       return SDValue();
17947
17948     Amt = Amt.getOperand(0);
17949     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17950                      VT.getVectorNumElements();
17951     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17952     uint64_t ShiftAmt = 0;
17953     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17954     for (unsigned i = 0; i != Ratio; ++i) {
17955       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17956       if (!C)
17957         return SDValue();
17958       // 6 == Log2(64)
17959       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17960     }
17961
17962     // Check remaining shift amounts (if not a splat).
17963     if (SplatIndex < 0) {
17964       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17965         uint64_t ShAmt = 0;
17966         for (unsigned j = 0; j != Ratio; ++j) {
17967           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17968           if (!C)
17969             return SDValue();
17970           // 6 == Log2(64)
17971           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17972         }
17973         if (ShAmt != ShiftAmt)
17974           return SDValue();
17975       }
17976     }
17977
17978     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17979       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17980
17981     if (Op.getOpcode() == ISD::SRA)
17982       return ArithmeticShiftRight64(ShiftAmt);
17983   }
17984
17985   return SDValue();
17986 }
17987
17988 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17989                                         const X86Subtarget* Subtarget) {
17990   MVT VT = Op.getSimpleValueType();
17991   SDLoc dl(Op);
17992   SDValue R = Op.getOperand(0);
17993   SDValue Amt = Op.getOperand(1);
17994
17995   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17996     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17997
17998   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17999     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18000
18001   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18002     SDValue BaseShAmt;
18003     EVT EltVT = VT.getVectorElementType();
18004
18005     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18006       // Check if this build_vector node is doing a splat.
18007       // If so, then set BaseShAmt equal to the splat value.
18008       BaseShAmt = BV->getSplatValue();
18009       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18010         BaseShAmt = SDValue();
18011     } else {
18012       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18013         Amt = Amt.getOperand(0);
18014
18015       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18016       if (SVN && SVN->isSplat()) {
18017         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18018         SDValue InVec = Amt.getOperand(0);
18019         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18020           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
18021                  "Unexpected shuffle index found!");
18022           BaseShAmt = InVec.getOperand(SplatIdx);
18023         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18024            if (ConstantSDNode *C =
18025                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18026              if (C->getZExtValue() == SplatIdx)
18027                BaseShAmt = InVec.getOperand(1);
18028            }
18029         }
18030
18031         if (!BaseShAmt)
18032           // Avoid introducing an extract element from a shuffle.
18033           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18034                                   DAG.getIntPtrConstant(SplatIdx, dl));
18035       }
18036     }
18037
18038     if (BaseShAmt.getNode()) {
18039       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18040       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18041         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18042       else if (EltVT.bitsLT(MVT::i32))
18043         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18044
18045       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18046     }
18047   }
18048
18049   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18050   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
18051       Amt.getOpcode() == ISD::BITCAST &&
18052       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18053     Amt = Amt.getOperand(0);
18054     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18055                      VT.getVectorNumElements();
18056     std::vector<SDValue> Vals(Ratio);
18057     for (unsigned i = 0; i != Ratio; ++i)
18058       Vals[i] = Amt.getOperand(i);
18059     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18060       for (unsigned j = 0; j != Ratio; ++j)
18061         if (Vals[j] != Amt.getOperand(i + j))
18062           return SDValue();
18063     }
18064
18065     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18066       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18067   }
18068   return SDValue();
18069 }
18070
18071 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18072                           SelectionDAG &DAG) {
18073   MVT VT = Op.getSimpleValueType();
18074   SDLoc dl(Op);
18075   SDValue R = Op.getOperand(0);
18076   SDValue Amt = Op.getOperand(1);
18077
18078   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18079   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18080
18081   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18082     return V;
18083
18084   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18085       return V;
18086
18087   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18088     return Op;
18089
18090   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18091   // shifts per-lane and then shuffle the partial results back together.
18092   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18093     // Splat the shift amounts so the scalar shifts above will catch it.
18094     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18095     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18096     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18097     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18098     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18099   }
18100
18101   // i64 vector arithmetic shift can be emulated with the transform:
18102   // M = lshr(SIGN_BIT, Amt)
18103   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18104   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18105       Op.getOpcode() == ISD::SRA) {
18106     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18107     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18108     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18109     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18110     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18111     return R;
18112   }
18113
18114   // If possible, lower this packed shift into a vector multiply instead of
18115   // expanding it into a sequence of scalar shifts.
18116   // Do this only if the vector shift count is a constant build_vector.
18117   if (Op.getOpcode() == ISD::SHL &&
18118       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18119        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18120       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18121     SmallVector<SDValue, 8> Elts;
18122     EVT SVT = VT.getScalarType();
18123     unsigned SVTBits = SVT.getSizeInBits();
18124     const APInt &One = APInt(SVTBits, 1);
18125     unsigned NumElems = VT.getVectorNumElements();
18126
18127     for (unsigned i=0; i !=NumElems; ++i) {
18128       SDValue Op = Amt->getOperand(i);
18129       if (Op->getOpcode() == ISD::UNDEF) {
18130         Elts.push_back(Op);
18131         continue;
18132       }
18133
18134       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18135       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
18136       uint64_t ShAmt = C.getZExtValue();
18137       if (ShAmt >= SVTBits) {
18138         Elts.push_back(DAG.getUNDEF(SVT));
18139         continue;
18140       }
18141       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18142     }
18143     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18144     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18145   }
18146
18147   // Lower SHL with variable shift amount.
18148   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18149     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18150
18151     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18152                      DAG.getConstant(0x3f800000U, dl, VT));
18153     Op = DAG.getBitcast(MVT::v4f32, Op);
18154     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18155     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18156   }
18157
18158   // If possible, lower this shift as a sequence of two shifts by
18159   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18160   // Example:
18161   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18162   //
18163   // Could be rewritten as:
18164   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18165   //
18166   // The advantage is that the two shifts from the example would be
18167   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18168   // the vector shift into four scalar shifts plus four pairs of vector
18169   // insert/extract.
18170   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18171       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18172     unsigned TargetOpcode = X86ISD::MOVSS;
18173     bool CanBeSimplified;
18174     // The splat value for the first packed shift (the 'X' from the example).
18175     SDValue Amt1 = Amt->getOperand(0);
18176     // The splat value for the second packed shift (the 'Y' from the example).
18177     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18178                                         Amt->getOperand(2);
18179
18180     // See if it is possible to replace this node with a sequence of
18181     // two shifts followed by a MOVSS/MOVSD
18182     if (VT == MVT::v4i32) {
18183       // Check if it is legal to use a MOVSS.
18184       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18185                         Amt2 == Amt->getOperand(3);
18186       if (!CanBeSimplified) {
18187         // Otherwise, check if we can still simplify this node using a MOVSD.
18188         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18189                           Amt->getOperand(2) == Amt->getOperand(3);
18190         TargetOpcode = X86ISD::MOVSD;
18191         Amt2 = Amt->getOperand(2);
18192       }
18193     } else {
18194       // Do similar checks for the case where the machine value type
18195       // is MVT::v8i16.
18196       CanBeSimplified = Amt1 == Amt->getOperand(1);
18197       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18198         CanBeSimplified = Amt2 == Amt->getOperand(i);
18199
18200       if (!CanBeSimplified) {
18201         TargetOpcode = X86ISD::MOVSD;
18202         CanBeSimplified = true;
18203         Amt2 = Amt->getOperand(4);
18204         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18205           CanBeSimplified = Amt1 == Amt->getOperand(i);
18206         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18207           CanBeSimplified = Amt2 == Amt->getOperand(j);
18208       }
18209     }
18210
18211     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18212         isa<ConstantSDNode>(Amt2)) {
18213       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18214       EVT CastVT = MVT::v4i32;
18215       SDValue Splat1 =
18216         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18217       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18218       SDValue Splat2 =
18219         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18220       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18221       if (TargetOpcode == X86ISD::MOVSD)
18222         CastVT = MVT::v2i64;
18223       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18224       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18225       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18226                                             BitCast1, DAG);
18227       return DAG.getBitcast(VT, Result);
18228     }
18229   }
18230
18231   // v4i32 Non Uniform Shifts.
18232   // If the shift amount is constant we can shift each lane using the SSE2
18233   // immediate shifts, else we need to zero-extend each lane to the lower i64
18234   // and shift using the SSE2 variable shifts.
18235   // The separate results can then be blended together.
18236   if (VT == MVT::v4i32) {
18237     unsigned Opc = Op.getOpcode();
18238     SDValue Amt0, Amt1, Amt2, Amt3;
18239     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18240       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18241       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18242       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18243       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18244     } else {
18245       // ISD::SHL is handled above but we include it here for completeness.
18246       switch (Opc) {
18247       default:
18248         llvm_unreachable("Unknown target vector shift node");
18249       case ISD::SHL:
18250         Opc = X86ISD::VSHL;
18251         break;
18252       case ISD::SRL:
18253         Opc = X86ISD::VSRL;
18254         break;
18255       case ISD::SRA:
18256         Opc = X86ISD::VSRA;
18257         break;
18258       }
18259       // The SSE2 shifts use the lower i64 as the same shift amount for
18260       // all lanes and the upper i64 is ignored. These shuffle masks
18261       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18262       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18263       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18264       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18265       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18266       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18267     }
18268
18269     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18270     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18271     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18272     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18273     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18274     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18275     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18276   }
18277
18278   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
18279     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18280     unsigned ShiftOpcode = Op->getOpcode();
18281
18282     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18283       // On SSE41 targets we make use of the fact that VSELECT lowers
18284       // to PBLENDVB which selects bytes based just on the sign bit.
18285       if (Subtarget->hasSSE41()) {
18286         V0 = DAG.getBitcast(VT, V0);
18287         V1 = DAG.getBitcast(VT, V1);
18288         Sel = DAG.getBitcast(VT, Sel);
18289         return DAG.getBitcast(SelVT,
18290                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18291       }
18292       // On pre-SSE41 targets we test for the sign bit by comparing to
18293       // zero - a negative value will set all bits of the lanes to true
18294       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18295       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18296       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18297       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18298     };
18299
18300     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18301     // We can safely do this using i16 shifts as we're only interested in
18302     // the 3 lower bits of each byte.
18303     Amt = DAG.getBitcast(ExtVT, Amt);
18304     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18305     Amt = DAG.getBitcast(VT, Amt);
18306
18307     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18308       // r = VSELECT(r, shift(r, 4), a);
18309       SDValue M =
18310           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18311       R = SignBitSelect(VT, Amt, M, R);
18312
18313       // a += a
18314       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18315
18316       // r = VSELECT(r, shift(r, 2), a);
18317       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18318       R = SignBitSelect(VT, Amt, M, R);
18319
18320       // a += a
18321       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18322
18323       // return VSELECT(r, shift(r, 1), a);
18324       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18325       R = SignBitSelect(VT, Amt, M, R);
18326       return R;
18327     }
18328
18329     if (Op->getOpcode() == ISD::SRA) {
18330       // For SRA we need to unpack each byte to the higher byte of a i16 vector
18331       // so we can correctly sign extend. We don't care what happens to the
18332       // lower byte.
18333       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18334       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18335       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18336       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18337       ALo = DAG.getBitcast(ExtVT, ALo);
18338       AHi = DAG.getBitcast(ExtVT, AHi);
18339       RLo = DAG.getBitcast(ExtVT, RLo);
18340       RHi = DAG.getBitcast(ExtVT, RHi);
18341
18342       // r = VSELECT(r, shift(r, 4), a);
18343       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18344                                 DAG.getConstant(4, dl, ExtVT));
18345       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18346                                 DAG.getConstant(4, dl, ExtVT));
18347       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18348       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18349
18350       // a += a
18351       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18352       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18353
18354       // r = VSELECT(r, shift(r, 2), a);
18355       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18356                         DAG.getConstant(2, dl, ExtVT));
18357       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18358                         DAG.getConstant(2, dl, ExtVT));
18359       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18360       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18361
18362       // a += a
18363       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18364       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18365
18366       // r = VSELECT(r, shift(r, 1), a);
18367       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18368                         DAG.getConstant(1, dl, ExtVT));
18369       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18370                         DAG.getConstant(1, dl, ExtVT));
18371       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18372       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18373
18374       // Logical shift the result back to the lower byte, leaving a zero upper
18375       // byte
18376       // meaning that we can safely pack with PACKUSWB.
18377       RLo =
18378           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18379       RHi =
18380           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18381       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18382     }
18383   }
18384
18385   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18386   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18387   // solution better.
18388   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18389     MVT ExtVT = MVT::v8i32;
18390     unsigned ExtOpc =
18391         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18392     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18393     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18394     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18395                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18396   }
18397
18398   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
18399     MVT ExtVT = MVT::v8i32;
18400     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18401     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18402     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18403     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18404     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18405     ALo = DAG.getBitcast(ExtVT, ALo);
18406     AHi = DAG.getBitcast(ExtVT, AHi);
18407     RLo = DAG.getBitcast(ExtVT, RLo);
18408     RHi = DAG.getBitcast(ExtVT, RHi);
18409     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18410     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18411     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18412     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18413     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18414   }
18415
18416   if (VT == MVT::v8i16) {
18417     unsigned ShiftOpcode = Op->getOpcode();
18418
18419     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18420       // On SSE41 targets we make use of the fact that VSELECT lowers
18421       // to PBLENDVB which selects bytes based just on the sign bit.
18422       if (Subtarget->hasSSE41()) {
18423         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18424         V0 = DAG.getBitcast(ExtVT, V0);
18425         V1 = DAG.getBitcast(ExtVT, V1);
18426         Sel = DAG.getBitcast(ExtVT, Sel);
18427         return DAG.getBitcast(
18428             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18429       }
18430       // On pre-SSE41 targets we splat the sign bit - a negative value will
18431       // set all bits of the lanes to true and VSELECT uses that in
18432       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18433       SDValue C =
18434           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18435       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18436     };
18437
18438     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18439     if (Subtarget->hasSSE41()) {
18440       // On SSE41 targets we need to replicate the shift mask in both
18441       // bytes for PBLENDVB.
18442       Amt = DAG.getNode(
18443           ISD::OR, dl, VT,
18444           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18445           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18446     } else {
18447       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18448     }
18449
18450     // r = VSELECT(r, shift(r, 8), a);
18451     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18452     R = SignBitSelect(Amt, M, R);
18453
18454     // a += a
18455     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18456
18457     // r = VSELECT(r, shift(r, 4), a);
18458     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18459     R = SignBitSelect(Amt, M, R);
18460
18461     // a += a
18462     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18463
18464     // r = VSELECT(r, shift(r, 2), a);
18465     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18466     R = SignBitSelect(Amt, M, R);
18467
18468     // a += a
18469     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18470
18471     // return VSELECT(r, shift(r, 1), a);
18472     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18473     R = SignBitSelect(Amt, M, R);
18474     return R;
18475   }
18476
18477   // Decompose 256-bit shifts into smaller 128-bit shifts.
18478   if (VT.is256BitVector()) {
18479     unsigned NumElems = VT.getVectorNumElements();
18480     MVT EltVT = VT.getVectorElementType();
18481     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18482
18483     // Extract the two vectors
18484     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18485     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18486
18487     // Recreate the shift amount vectors
18488     SDValue Amt1, Amt2;
18489     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18490       // Constant shift amount
18491       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18492       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18493       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18494
18495       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18496       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18497     } else {
18498       // Variable shift amount
18499       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18500       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18501     }
18502
18503     // Issue new vector shifts for the smaller types
18504     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18505     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18506
18507     // Concatenate the result back
18508     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18509   }
18510
18511   return SDValue();
18512 }
18513
18514 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18515   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18516   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18517   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18518   // has only one use.
18519   SDNode *N = Op.getNode();
18520   SDValue LHS = N->getOperand(0);
18521   SDValue RHS = N->getOperand(1);
18522   unsigned BaseOp = 0;
18523   unsigned Cond = 0;
18524   SDLoc DL(Op);
18525   switch (Op.getOpcode()) {
18526   default: llvm_unreachable("Unknown ovf instruction!");
18527   case ISD::SADDO:
18528     // A subtract of one will be selected as a INC. Note that INC doesn't
18529     // set CF, so we can't do this for UADDO.
18530     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18531       if (C->isOne()) {
18532         BaseOp = X86ISD::INC;
18533         Cond = X86::COND_O;
18534         break;
18535       }
18536     BaseOp = X86ISD::ADD;
18537     Cond = X86::COND_O;
18538     break;
18539   case ISD::UADDO:
18540     BaseOp = X86ISD::ADD;
18541     Cond = X86::COND_B;
18542     break;
18543   case ISD::SSUBO:
18544     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18545     // set CF, so we can't do this for USUBO.
18546     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18547       if (C->isOne()) {
18548         BaseOp = X86ISD::DEC;
18549         Cond = X86::COND_O;
18550         break;
18551       }
18552     BaseOp = X86ISD::SUB;
18553     Cond = X86::COND_O;
18554     break;
18555   case ISD::USUBO:
18556     BaseOp = X86ISD::SUB;
18557     Cond = X86::COND_B;
18558     break;
18559   case ISD::SMULO:
18560     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18561     Cond = X86::COND_O;
18562     break;
18563   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18564     if (N->getValueType(0) == MVT::i8) {
18565       BaseOp = X86ISD::UMUL8;
18566       Cond = X86::COND_O;
18567       break;
18568     }
18569     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18570                                  MVT::i32);
18571     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18572
18573     SDValue SetCC =
18574       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18575                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18576                   SDValue(Sum.getNode(), 2));
18577
18578     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18579   }
18580   }
18581
18582   // Also sets EFLAGS.
18583   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18584   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18585
18586   SDValue SetCC =
18587     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18588                 DAG.getConstant(Cond, DL, MVT::i32),
18589                 SDValue(Sum.getNode(), 1));
18590
18591   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18592 }
18593
18594 /// Returns true if the operand type is exactly twice the native width, and
18595 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18596 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18597 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18598 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18599   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18600
18601   if (OpWidth == 64)
18602     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18603   else if (OpWidth == 128)
18604     return Subtarget->hasCmpxchg16b();
18605   else
18606     return false;
18607 }
18608
18609 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18610   return needsCmpXchgNb(SI->getValueOperand()->getType());
18611 }
18612
18613 // Note: this turns large loads into lock cmpxchg8b/16b.
18614 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18615 TargetLowering::AtomicExpansionKind
18616 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18617   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18618   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
18619                                                : AtomicExpansionKind::None;
18620 }
18621
18622 TargetLowering::AtomicExpansionKind
18623 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18624   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18625   Type *MemType = AI->getType();
18626
18627   // If the operand is too big, we must see if cmpxchg8/16b is available
18628   // and default to library calls otherwise.
18629   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18630     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
18631                                    : AtomicExpansionKind::None;
18632   }
18633
18634   AtomicRMWInst::BinOp Op = AI->getOperation();
18635   switch (Op) {
18636   default:
18637     llvm_unreachable("Unknown atomic operation");
18638   case AtomicRMWInst::Xchg:
18639   case AtomicRMWInst::Add:
18640   case AtomicRMWInst::Sub:
18641     // It's better to use xadd, xsub or xchg for these in all cases.
18642     return AtomicExpansionKind::None;
18643   case AtomicRMWInst::Or:
18644   case AtomicRMWInst::And:
18645   case AtomicRMWInst::Xor:
18646     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18647     // prefix to a normal instruction for these operations.
18648     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
18649                             : AtomicExpansionKind::None;
18650   case AtomicRMWInst::Nand:
18651   case AtomicRMWInst::Max:
18652   case AtomicRMWInst::Min:
18653   case AtomicRMWInst::UMax:
18654   case AtomicRMWInst::UMin:
18655     // These always require a non-trivial set of data operations on x86. We must
18656     // use a cmpxchg loop.
18657     return AtomicExpansionKind::CmpXChg;
18658   }
18659 }
18660
18661 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18662   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18663   // no-sse2). There isn't any reason to disable it if the target processor
18664   // supports it.
18665   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18666 }
18667
18668 LoadInst *
18669 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18670   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18671   Type *MemType = AI->getType();
18672   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18673   // there is no benefit in turning such RMWs into loads, and it is actually
18674   // harmful as it introduces a mfence.
18675   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18676     return nullptr;
18677
18678   auto Builder = IRBuilder<>(AI);
18679   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18680   auto SynchScope = AI->getSynchScope();
18681   // We must restrict the ordering to avoid generating loads with Release or
18682   // ReleaseAcquire orderings.
18683   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18684   auto Ptr = AI->getPointerOperand();
18685
18686   // Before the load we need a fence. Here is an example lifted from
18687   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18688   // is required:
18689   // Thread 0:
18690   //   x.store(1, relaxed);
18691   //   r1 = y.fetch_add(0, release);
18692   // Thread 1:
18693   //   y.fetch_add(42, acquire);
18694   //   r2 = x.load(relaxed);
18695   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18696   // lowered to just a load without a fence. A mfence flushes the store buffer,
18697   // making the optimization clearly correct.
18698   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18699   // otherwise, we might be able to be more aggressive on relaxed idempotent
18700   // rmw. In practice, they do not look useful, so we don't try to be
18701   // especially clever.
18702   if (SynchScope == SingleThread)
18703     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18704     // the IR level, so we must wrap it in an intrinsic.
18705     return nullptr;
18706
18707   if (!hasMFENCE(*Subtarget))
18708     // FIXME: it might make sense to use a locked operation here but on a
18709     // different cache-line to prevent cache-line bouncing. In practice it
18710     // is probably a small win, and x86 processors without mfence are rare
18711     // enough that we do not bother.
18712     return nullptr;
18713
18714   Function *MFence =
18715       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18716   Builder.CreateCall(MFence, {});
18717
18718   // Finally we can emit the atomic load.
18719   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18720           AI->getType()->getPrimitiveSizeInBits());
18721   Loaded->setAtomic(Order, SynchScope);
18722   AI->replaceAllUsesWith(Loaded);
18723   AI->eraseFromParent();
18724   return Loaded;
18725 }
18726
18727 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18728                                  SelectionDAG &DAG) {
18729   SDLoc dl(Op);
18730   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18731     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18732   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18733     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18734
18735   // The only fence that needs an instruction is a sequentially-consistent
18736   // cross-thread fence.
18737   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18738     if (hasMFENCE(*Subtarget))
18739       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18740
18741     SDValue Chain = Op.getOperand(0);
18742     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18743     SDValue Ops[] = {
18744       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18745       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18746       DAG.getRegister(0, MVT::i32),            // Index
18747       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18748       DAG.getRegister(0, MVT::i32),            // Segment.
18749       Zero,
18750       Chain
18751     };
18752     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18753     return SDValue(Res, 0);
18754   }
18755
18756   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18757   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18758 }
18759
18760 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18761                              SelectionDAG &DAG) {
18762   MVT T = Op.getSimpleValueType();
18763   SDLoc DL(Op);
18764   unsigned Reg = 0;
18765   unsigned size = 0;
18766   switch(T.SimpleTy) {
18767   default: llvm_unreachable("Invalid value type!");
18768   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18769   case MVT::i16: Reg = X86::AX;  size = 2; break;
18770   case MVT::i32: Reg = X86::EAX; size = 4; break;
18771   case MVT::i64:
18772     assert(Subtarget->is64Bit() && "Node not type legal!");
18773     Reg = X86::RAX; size = 8;
18774     break;
18775   }
18776   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18777                                   Op.getOperand(2), SDValue());
18778   SDValue Ops[] = { cpIn.getValue(0),
18779                     Op.getOperand(1),
18780                     Op.getOperand(3),
18781                     DAG.getTargetConstant(size, DL, MVT::i8),
18782                     cpIn.getValue(1) };
18783   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18784   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18785   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18786                                            Ops, T, MMO);
18787
18788   SDValue cpOut =
18789     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18790   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18791                                       MVT::i32, cpOut.getValue(2));
18792   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18793                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18794                                 EFLAGS);
18795
18796   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18797   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18798   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18799   return SDValue();
18800 }
18801
18802 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18803                             SelectionDAG &DAG) {
18804   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18805   MVT DstVT = Op.getSimpleValueType();
18806
18807   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18808     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18809     if (DstVT != MVT::f64)
18810       // This conversion needs to be expanded.
18811       return SDValue();
18812
18813     SDValue InVec = Op->getOperand(0);
18814     SDLoc dl(Op);
18815     unsigned NumElts = SrcVT.getVectorNumElements();
18816     EVT SVT = SrcVT.getVectorElementType();
18817
18818     // Widen the vector in input in the case of MVT::v2i32.
18819     // Example: from MVT::v2i32 to MVT::v4i32.
18820     SmallVector<SDValue, 16> Elts;
18821     for (unsigned i = 0, e = NumElts; i != e; ++i)
18822       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18823                                  DAG.getIntPtrConstant(i, dl)));
18824
18825     // Explicitly mark the extra elements as Undef.
18826     Elts.append(NumElts, DAG.getUNDEF(SVT));
18827
18828     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18829     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18830     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18831     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18832                        DAG.getIntPtrConstant(0, dl));
18833   }
18834
18835   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18836          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18837   assert((DstVT == MVT::i64 ||
18838           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18839          "Unexpected custom BITCAST");
18840   // i64 <=> MMX conversions are Legal.
18841   if (SrcVT==MVT::i64 && DstVT.isVector())
18842     return Op;
18843   if (DstVT==MVT::i64 && SrcVT.isVector())
18844     return Op;
18845   // MMX <=> MMX conversions are Legal.
18846   if (SrcVT.isVector() && DstVT.isVector())
18847     return Op;
18848   // All other conversions need to be expanded.
18849   return SDValue();
18850 }
18851
18852 /// Compute the horizontal sum of bytes in V for the elements of VT.
18853 ///
18854 /// Requires V to be a byte vector and VT to be an integer vector type with
18855 /// wider elements than V's type. The width of the elements of VT determines
18856 /// how many bytes of V are summed horizontally to produce each element of the
18857 /// result.
18858 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18859                                       const X86Subtarget *Subtarget,
18860                                       SelectionDAG &DAG) {
18861   SDLoc DL(V);
18862   MVT ByteVecVT = V.getSimpleValueType();
18863   MVT EltVT = VT.getVectorElementType();
18864   int NumElts = VT.getVectorNumElements();
18865   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18866          "Expected value to have byte element type.");
18867   assert(EltVT != MVT::i8 &&
18868          "Horizontal byte sum only makes sense for wider elements!");
18869   unsigned VecSize = VT.getSizeInBits();
18870   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18871
18872   // PSADBW instruction horizontally add all bytes and leave the result in i64
18873   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18874   if (EltVT == MVT::i64) {
18875     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18876     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18877     return DAG.getBitcast(VT, V);
18878   }
18879
18880   if (EltVT == MVT::i32) {
18881     // We unpack the low half and high half into i32s interleaved with zeros so
18882     // that we can use PSADBW to horizontally sum them. The most useful part of
18883     // this is that it lines up the results of two PSADBW instructions to be
18884     // two v2i64 vectors which concatenated are the 4 population counts. We can
18885     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18886     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18887     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18888     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18889
18890     // Do the horizontal sums into two v2i64s.
18891     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18892     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18893                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18894     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18895                        DAG.getBitcast(ByteVecVT, High), Zeros);
18896
18897     // Merge them together.
18898     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18899     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18900                     DAG.getBitcast(ShortVecVT, Low),
18901                     DAG.getBitcast(ShortVecVT, High));
18902
18903     return DAG.getBitcast(VT, V);
18904   }
18905
18906   // The only element type left is i16.
18907   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18908
18909   // To obtain pop count for each i16 element starting from the pop count for
18910   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18911   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18912   // directly supported.
18913   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18914   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18915   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18916   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18917                   DAG.getBitcast(ByteVecVT, V));
18918   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18919 }
18920
18921 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18922                                         const X86Subtarget *Subtarget,
18923                                         SelectionDAG &DAG) {
18924   MVT VT = Op.getSimpleValueType();
18925   MVT EltVT = VT.getVectorElementType();
18926   unsigned VecSize = VT.getSizeInBits();
18927
18928   // Implement a lookup table in register by using an algorithm based on:
18929   // http://wm.ite.pl/articles/sse-popcount.html
18930   //
18931   // The general idea is that every lower byte nibble in the input vector is an
18932   // index into a in-register pre-computed pop count table. We then split up the
18933   // input vector in two new ones: (1) a vector with only the shifted-right
18934   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18935   // masked out higher ones) for each byte. PSHUB is used separately with both
18936   // to index the in-register table. Next, both are added and the result is a
18937   // i8 vector where each element contains the pop count for input byte.
18938   //
18939   // To obtain the pop count for elements != i8, we follow up with the same
18940   // approach and use additional tricks as described below.
18941   //
18942   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18943                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18944                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18945                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18946
18947   int NumByteElts = VecSize / 8;
18948   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18949   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18950   SmallVector<SDValue, 16> LUTVec;
18951   for (int i = 0; i < NumByteElts; ++i)
18952     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18953   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18954   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18955                                   DAG.getConstant(0x0F, DL, MVT::i8));
18956   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18957
18958   // High nibbles
18959   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18960   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18961   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18962
18963   // Low nibbles
18964   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18965
18966   // The input vector is used as the shuffle mask that index elements into the
18967   // LUT. After counting low and high nibbles, add the vector to obtain the
18968   // final pop count per i8 element.
18969   SDValue HighPopCnt =
18970       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18971   SDValue LowPopCnt =
18972       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18973   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18974
18975   if (EltVT == MVT::i8)
18976     return PopCnt;
18977
18978   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18979 }
18980
18981 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18982                                        const X86Subtarget *Subtarget,
18983                                        SelectionDAG &DAG) {
18984   MVT VT = Op.getSimpleValueType();
18985   assert(VT.is128BitVector() &&
18986          "Only 128-bit vector bitmath lowering supported.");
18987
18988   int VecSize = VT.getSizeInBits();
18989   MVT EltVT = VT.getVectorElementType();
18990   int Len = EltVT.getSizeInBits();
18991
18992   // This is the vectorized version of the "best" algorithm from
18993   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18994   // with a minor tweak to use a series of adds + shifts instead of vector
18995   // multiplications. Implemented for all integer vector types. We only use
18996   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18997   // much faster, even faster than using native popcnt instructions.
18998
18999   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19000     MVT VT = V.getSimpleValueType();
19001     SmallVector<SDValue, 32> Shifters(
19002         VT.getVectorNumElements(),
19003         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19004     return DAG.getNode(OpCode, DL, VT, V,
19005                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19006   };
19007   auto GetMask = [&](SDValue V, APInt Mask) {
19008     MVT VT = V.getSimpleValueType();
19009     SmallVector<SDValue, 32> Masks(
19010         VT.getVectorNumElements(),
19011         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19012     return DAG.getNode(ISD::AND, DL, VT, V,
19013                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19014   };
19015
19016   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19017   // x86, so set the SRL type to have elements at least i16 wide. This is
19018   // correct because all of our SRLs are followed immediately by a mask anyways
19019   // that handles any bits that sneak into the high bits of the byte elements.
19020   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19021
19022   SDValue V = Op;
19023
19024   // v = v - ((v >> 1) & 0x55555555...)
19025   SDValue Srl =
19026       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19027   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19028   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19029
19030   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19031   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19032   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19033   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19034   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19035
19036   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19037   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19038   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19039   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19040
19041   // At this point, V contains the byte-wise population count, and we are
19042   // merely doing a horizontal sum if necessary to get the wider element
19043   // counts.
19044   if (EltVT == MVT::i8)
19045     return V;
19046
19047   return LowerHorizontalByteSum(
19048       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19049       DAG);
19050 }
19051
19052 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19053                                 SelectionDAG &DAG) {
19054   MVT VT = Op.getSimpleValueType();
19055   // FIXME: Need to add AVX-512 support here!
19056   assert((VT.is256BitVector() || VT.is128BitVector()) &&
19057          "Unknown CTPOP type to handle");
19058   SDLoc DL(Op.getNode());
19059   SDValue Op0 = Op.getOperand(0);
19060
19061   if (!Subtarget->hasSSSE3()) {
19062     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19063     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19064     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19065   }
19066
19067   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19068     unsigned NumElems = VT.getVectorNumElements();
19069
19070     // Extract each 128-bit vector, compute pop count and concat the result.
19071     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19072     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19073
19074     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19075                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19076                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19077   }
19078
19079   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19080 }
19081
19082 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19083                           SelectionDAG &DAG) {
19084   assert(Op.getValueType().isVector() &&
19085          "We only do custom lowering for vector population count.");
19086   return LowerVectorCTPOP(Op, Subtarget, DAG);
19087 }
19088
19089 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19090   SDNode *Node = Op.getNode();
19091   SDLoc dl(Node);
19092   EVT T = Node->getValueType(0);
19093   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19094                               DAG.getConstant(0, dl, T), Node->getOperand(2));
19095   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19096                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19097                        Node->getOperand(0),
19098                        Node->getOperand(1), negOp,
19099                        cast<AtomicSDNode>(Node)->getMemOperand(),
19100                        cast<AtomicSDNode>(Node)->getOrdering(),
19101                        cast<AtomicSDNode>(Node)->getSynchScope());
19102 }
19103
19104 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19105   SDNode *Node = Op.getNode();
19106   SDLoc dl(Node);
19107   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19108
19109   // Convert seq_cst store -> xchg
19110   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19111   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19112   //        (The only way to get a 16-byte store is cmpxchg16b)
19113   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19114   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19115       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19116     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19117                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19118                                  Node->getOperand(0),
19119                                  Node->getOperand(1), Node->getOperand(2),
19120                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19121                                  cast<AtomicSDNode>(Node)->getOrdering(),
19122                                  cast<AtomicSDNode>(Node)->getSynchScope());
19123     return Swap.getValue(1);
19124   }
19125   // Other atomic stores have a simple pattern.
19126   return Op;
19127 }
19128
19129 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19130   EVT VT = Op.getNode()->getSimpleValueType(0);
19131
19132   // Let legalize expand this if it isn't a legal type yet.
19133   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19134     return SDValue();
19135
19136   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19137
19138   unsigned Opc;
19139   bool ExtraOp = false;
19140   switch (Op.getOpcode()) {
19141   default: llvm_unreachable("Invalid code");
19142   case ISD::ADDC: Opc = X86ISD::ADD; break;
19143   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19144   case ISD::SUBC: Opc = X86ISD::SUB; break;
19145   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19146   }
19147
19148   if (!ExtraOp)
19149     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19150                        Op.getOperand(1));
19151   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19152                      Op.getOperand(1), Op.getOperand(2));
19153 }
19154
19155 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19156                             SelectionDAG &DAG) {
19157   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19158
19159   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19160   // which returns the values as { float, float } (in XMM0) or
19161   // { double, double } (which is returned in XMM0, XMM1).
19162   SDLoc dl(Op);
19163   SDValue Arg = Op.getOperand(0);
19164   EVT ArgVT = Arg.getValueType();
19165   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19166
19167   TargetLowering::ArgListTy Args;
19168   TargetLowering::ArgListEntry Entry;
19169
19170   Entry.Node = Arg;
19171   Entry.Ty = ArgTy;
19172   Entry.isSExt = false;
19173   Entry.isZExt = false;
19174   Args.push_back(Entry);
19175
19176   bool isF64 = ArgVT == MVT::f64;
19177   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19178   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19179   // the results are returned via SRet in memory.
19180   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19181   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19182   SDValue Callee =
19183       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19184
19185   Type *RetTy = isF64
19186     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19187     : (Type*)VectorType::get(ArgTy, 4);
19188
19189   TargetLowering::CallLoweringInfo CLI(DAG);
19190   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19191     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19192
19193   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19194
19195   if (isF64)
19196     // Returned in xmm0 and xmm1.
19197     return CallResult.first;
19198
19199   // Returned in bits 0:31 and 32:64 xmm0.
19200   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19201                                CallResult.first, DAG.getIntPtrConstant(0, dl));
19202   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19203                                CallResult.first, DAG.getIntPtrConstant(1, dl));
19204   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19205   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19206 }
19207
19208 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19209                              SelectionDAG &DAG) {
19210   assert(Subtarget->hasAVX512() &&
19211          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19212
19213   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19214   EVT VT = N->getValue().getValueType();
19215   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19216   SDLoc dl(Op);
19217
19218   // X86 scatter kills mask register, so its type should be added to
19219   // the list of return values
19220   if (N->getNumValues() == 1) {
19221     SDValue Index = N->getIndex();
19222     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19223         !Index.getValueType().is512BitVector())
19224       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19225
19226     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19227     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19228                       N->getOperand(3), Index };
19229
19230     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19231     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19232     return SDValue(NewScatter.getNode(), 0);
19233   }
19234   return Op;
19235 }
19236
19237 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19238                             SelectionDAG &DAG) {
19239   assert(Subtarget->hasAVX512() &&
19240          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19241
19242   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19243   EVT VT = Op.getValueType();
19244   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19245   SDLoc dl(Op);
19246
19247   SDValue Index = N->getIndex();
19248   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19249       !Index.getValueType().is512BitVector()) {
19250     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19251     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19252                       N->getOperand(3), Index };
19253     DAG.UpdateNodeOperands(N, Ops);
19254   }
19255   return Op;
19256 }
19257
19258 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19259                                                     SelectionDAG &DAG) const {
19260   // TODO: Eventually, the lowering of these nodes should be informed by or
19261   // deferred to the GC strategy for the function in which they appear. For
19262   // now, however, they must be lowered to something. Since they are logically
19263   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19264   // require special handling for these nodes), lower them as literal NOOPs for
19265   // the time being.
19266   SmallVector<SDValue, 2> Ops;
19267
19268   Ops.push_back(Op.getOperand(0));
19269   if (Op->getGluedNode())
19270     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19271
19272   SDLoc OpDL(Op);
19273   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19274   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19275
19276   return NOOP;
19277 }
19278
19279 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19280                                                   SelectionDAG &DAG) const {
19281   // TODO: Eventually, the lowering of these nodes should be informed by or
19282   // deferred to the GC strategy for the function in which they appear. For
19283   // now, however, they must be lowered to something. Since they are logically
19284   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19285   // require special handling for these nodes), lower them as literal NOOPs for
19286   // the time being.
19287   SmallVector<SDValue, 2> Ops;
19288
19289   Ops.push_back(Op.getOperand(0));
19290   if (Op->getGluedNode())
19291     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19292
19293   SDLoc OpDL(Op);
19294   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19295   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19296
19297   return NOOP;
19298 }
19299
19300 /// LowerOperation - Provide custom lowering hooks for some operations.
19301 ///
19302 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19303   switch (Op.getOpcode()) {
19304   default: llvm_unreachable("Should not custom lower this!");
19305   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19306   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19307     return LowerCMP_SWAP(Op, Subtarget, DAG);
19308   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
19309   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19310   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19311   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19312   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19313   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
19314   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19315   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19316   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19317   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19318   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19319   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19320   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19321   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19322   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19323   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19324   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19325   case ISD::SHL_PARTS:
19326   case ISD::SRA_PARTS:
19327   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19328   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19329   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19330   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19331   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19332   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19333   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19334   case ISD::SIGN_EXTEND_VECTOR_INREG:
19335     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19336   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19337   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19338   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19339   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19340   case ISD::FABS:
19341   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19342   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19343   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19344   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19345   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19346   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19347   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19348   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19349   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19350   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19351   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19352   case ISD::INTRINSIC_VOID:
19353   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19354   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19355   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19356   case ISD::FRAME_TO_ARGS_OFFSET:
19357                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19358   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19359   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19360   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19361   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19362   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19363   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19364   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19365   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
19366   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
19367   case ISD::CTTZ:
19368   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
19369   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19370   case ISD::UMUL_LOHI:
19371   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19372   case ISD::SRA:
19373   case ISD::SRL:
19374   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19375   case ISD::SADDO:
19376   case ISD::UADDO:
19377   case ISD::SSUBO:
19378   case ISD::USUBO:
19379   case ISD::SMULO:
19380   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19381   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19382   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19383   case ISD::ADDC:
19384   case ISD::ADDE:
19385   case ISD::SUBC:
19386   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19387   case ISD::ADD:                return LowerADD(Op, DAG);
19388   case ISD::SUB:                return LowerSUB(Op, DAG);
19389   case ISD::SMAX:
19390   case ISD::SMIN:
19391   case ISD::UMAX:
19392   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
19393   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19394   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
19395   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
19396   case ISD::GC_TRANSITION_START:
19397                                 return LowerGC_TRANSITION_START(Op, DAG);
19398   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
19399   }
19400 }
19401
19402 /// ReplaceNodeResults - Replace a node with an illegal result type
19403 /// with a new node built out of custom code.
19404 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19405                                            SmallVectorImpl<SDValue>&Results,
19406                                            SelectionDAG &DAG) const {
19407   SDLoc dl(N);
19408   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19409   switch (N->getOpcode()) {
19410   default:
19411     llvm_unreachable("Do not know how to custom type legalize this operation!");
19412   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19413   case X86ISD::FMINC:
19414   case X86ISD::FMIN:
19415   case X86ISD::FMAXC:
19416   case X86ISD::FMAX: {
19417     EVT VT = N->getValueType(0);
19418     if (VT != MVT::v2f32)
19419       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
19420     SDValue UNDEF = DAG.getUNDEF(VT);
19421     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19422                               N->getOperand(0), UNDEF);
19423     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19424                               N->getOperand(1), UNDEF);
19425     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19426     return;
19427   }
19428   case ISD::SIGN_EXTEND_INREG:
19429   case ISD::ADDC:
19430   case ISD::ADDE:
19431   case ISD::SUBC:
19432   case ISD::SUBE:
19433     // We don't want to expand or promote these.
19434     return;
19435   case ISD::SDIV:
19436   case ISD::UDIV:
19437   case ISD::SREM:
19438   case ISD::UREM:
19439   case ISD::SDIVREM:
19440   case ISD::UDIVREM: {
19441     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19442     Results.push_back(V);
19443     return;
19444   }
19445   case ISD::FP_TO_SINT:
19446   case ISD::FP_TO_UINT: {
19447     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19448
19449     std::pair<SDValue,SDValue> Vals =
19450         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19451     SDValue FIST = Vals.first, StackSlot = Vals.second;
19452     if (FIST.getNode()) {
19453       EVT VT = N->getValueType(0);
19454       // Return a load from the stack slot.
19455       if (StackSlot.getNode())
19456         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19457                                       MachinePointerInfo(),
19458                                       false, false, false, 0));
19459       else
19460         Results.push_back(FIST);
19461     }
19462     return;
19463   }
19464   case ISD::UINT_TO_FP: {
19465     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19466     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19467         N->getValueType(0) != MVT::v2f32)
19468       return;
19469     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19470                                  N->getOperand(0));
19471     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19472                                      MVT::f64);
19473     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19474     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19475                              DAG.getBitcast(MVT::v2i64, VBias));
19476     Or = DAG.getBitcast(MVT::v2f64, Or);
19477     // TODO: Are there any fast-math-flags to propagate here?
19478     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19479     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19480     return;
19481   }
19482   case ISD::FP_ROUND: {
19483     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19484         return;
19485     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19486     Results.push_back(V);
19487     return;
19488   }
19489   case ISD::FP_EXTEND: {
19490     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19491     // No other ValueType for FP_EXTEND should reach this point.
19492     assert(N->getValueType(0) == MVT::v2f32 &&
19493            "Do not know how to legalize this Node");
19494     return;
19495   }
19496   case ISD::INTRINSIC_W_CHAIN: {
19497     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19498     switch (IntNo) {
19499     default : llvm_unreachable("Do not know how to custom type "
19500                                "legalize this intrinsic operation!");
19501     case Intrinsic::x86_rdtsc:
19502       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19503                                      Results);
19504     case Intrinsic::x86_rdtscp:
19505       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19506                                      Results);
19507     case Intrinsic::x86_rdpmc:
19508       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19509     }
19510   }
19511   case ISD::READCYCLECOUNTER: {
19512     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19513                                    Results);
19514   }
19515   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19516     EVT T = N->getValueType(0);
19517     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19518     bool Regs64bit = T == MVT::i128;
19519     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19520     SDValue cpInL, cpInH;
19521     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19522                         DAG.getConstant(0, dl, HalfT));
19523     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19524                         DAG.getConstant(1, dl, HalfT));
19525     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19526                              Regs64bit ? X86::RAX : X86::EAX,
19527                              cpInL, SDValue());
19528     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19529                              Regs64bit ? X86::RDX : X86::EDX,
19530                              cpInH, cpInL.getValue(1));
19531     SDValue swapInL, swapInH;
19532     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19533                           DAG.getConstant(0, dl, HalfT));
19534     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19535                           DAG.getConstant(1, dl, HalfT));
19536     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19537                                Regs64bit ? X86::RBX : X86::EBX,
19538                                swapInL, cpInH.getValue(1));
19539     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19540                                Regs64bit ? X86::RCX : X86::ECX,
19541                                swapInH, swapInL.getValue(1));
19542     SDValue Ops[] = { swapInH.getValue(0),
19543                       N->getOperand(1),
19544                       swapInH.getValue(1) };
19545     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19546     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19547     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19548                                   X86ISD::LCMPXCHG8_DAG;
19549     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19550     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19551                                         Regs64bit ? X86::RAX : X86::EAX,
19552                                         HalfT, Result.getValue(1));
19553     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19554                                         Regs64bit ? X86::RDX : X86::EDX,
19555                                         HalfT, cpOutL.getValue(2));
19556     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19557
19558     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19559                                         MVT::i32, cpOutH.getValue(2));
19560     SDValue Success =
19561         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19562                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19563     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19564
19565     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19566     Results.push_back(Success);
19567     Results.push_back(EFLAGS.getValue(1));
19568     return;
19569   }
19570   case ISD::ATOMIC_SWAP:
19571   case ISD::ATOMIC_LOAD_ADD:
19572   case ISD::ATOMIC_LOAD_SUB:
19573   case ISD::ATOMIC_LOAD_AND:
19574   case ISD::ATOMIC_LOAD_OR:
19575   case ISD::ATOMIC_LOAD_XOR:
19576   case ISD::ATOMIC_LOAD_NAND:
19577   case ISD::ATOMIC_LOAD_MIN:
19578   case ISD::ATOMIC_LOAD_MAX:
19579   case ISD::ATOMIC_LOAD_UMIN:
19580   case ISD::ATOMIC_LOAD_UMAX:
19581   case ISD::ATOMIC_LOAD: {
19582     // Delegate to generic TypeLegalization. Situations we can really handle
19583     // should have already been dealt with by AtomicExpandPass.cpp.
19584     break;
19585   }
19586   case ISD::BITCAST: {
19587     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19588     EVT DstVT = N->getValueType(0);
19589     EVT SrcVT = N->getOperand(0)->getValueType(0);
19590
19591     if (SrcVT != MVT::f64 ||
19592         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19593       return;
19594
19595     unsigned NumElts = DstVT.getVectorNumElements();
19596     EVT SVT = DstVT.getVectorElementType();
19597     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19598     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19599                                    MVT::v2f64, N->getOperand(0));
19600     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19601
19602     if (ExperimentalVectorWideningLegalization) {
19603       // If we are legalizing vectors by widening, we already have the desired
19604       // legal vector type, just return it.
19605       Results.push_back(ToVecInt);
19606       return;
19607     }
19608
19609     SmallVector<SDValue, 8> Elts;
19610     for (unsigned i = 0, e = NumElts; i != e; ++i)
19611       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19612                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19613
19614     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19615   }
19616   }
19617 }
19618
19619 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19620   switch ((X86ISD::NodeType)Opcode) {
19621   case X86ISD::FIRST_NUMBER:       break;
19622   case X86ISD::BSF:                return "X86ISD::BSF";
19623   case X86ISD::BSR:                return "X86ISD::BSR";
19624   case X86ISD::SHLD:               return "X86ISD::SHLD";
19625   case X86ISD::SHRD:               return "X86ISD::SHRD";
19626   case X86ISD::FAND:               return "X86ISD::FAND";
19627   case X86ISD::FANDN:              return "X86ISD::FANDN";
19628   case X86ISD::FOR:                return "X86ISD::FOR";
19629   case X86ISD::FXOR:               return "X86ISD::FXOR";
19630   case X86ISD::FILD:               return "X86ISD::FILD";
19631   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19632   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19633   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19634   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19635   case X86ISD::FLD:                return "X86ISD::FLD";
19636   case X86ISD::FST:                return "X86ISD::FST";
19637   case X86ISD::CALL:               return "X86ISD::CALL";
19638   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19639   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19640   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19641   case X86ISD::BT:                 return "X86ISD::BT";
19642   case X86ISD::CMP:                return "X86ISD::CMP";
19643   case X86ISD::COMI:               return "X86ISD::COMI";
19644   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19645   case X86ISD::CMPM:               return "X86ISD::CMPM";
19646   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19647   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19648   case X86ISD::SETCC:              return "X86ISD::SETCC";
19649   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19650   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19651   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19652   case X86ISD::CMOV:               return "X86ISD::CMOV";
19653   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19654   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19655   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19656   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19657   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19658   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19659   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19660   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19661   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19662   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19663   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19664   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19665   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19666   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19667   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19668   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19669   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19670   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19671   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19672   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19673   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19674   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19675   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19676   case X86ISD::HADD:               return "X86ISD::HADD";
19677   case X86ISD::HSUB:               return "X86ISD::HSUB";
19678   case X86ISD::FHADD:              return "X86ISD::FHADD";
19679   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19680   case X86ISD::ABS:                return "X86ISD::ABS";
19681   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
19682   case X86ISD::FMAX:               return "X86ISD::FMAX";
19683   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19684   case X86ISD::FMIN:               return "X86ISD::FMIN";
19685   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19686   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19687   case X86ISD::FMINC:              return "X86ISD::FMINC";
19688   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19689   case X86ISD::FRCP:               return "X86ISD::FRCP";
19690   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19691   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19692   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19693   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19694   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19695   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19696   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19697   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19698   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19699   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19700   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19701   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19702   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19703   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19704   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19705   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19706   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19707   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19708   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19709   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19710   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19711   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19712   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19713   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19714   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19715   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19716   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19717   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19718   case X86ISD::VSHL:               return "X86ISD::VSHL";
19719   case X86ISD::VSRL:               return "X86ISD::VSRL";
19720   case X86ISD::VSRA:               return "X86ISD::VSRA";
19721   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19722   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19723   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19724   case X86ISD::CMPP:               return "X86ISD::CMPP";
19725   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19726   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19727   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19728   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19729   case X86ISD::ADD:                return "X86ISD::ADD";
19730   case X86ISD::SUB:                return "X86ISD::SUB";
19731   case X86ISD::ADC:                return "X86ISD::ADC";
19732   case X86ISD::SBB:                return "X86ISD::SBB";
19733   case X86ISD::SMUL:               return "X86ISD::SMUL";
19734   case X86ISD::UMUL:               return "X86ISD::UMUL";
19735   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19736   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19737   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19738   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19739   case X86ISD::INC:                return "X86ISD::INC";
19740   case X86ISD::DEC:                return "X86ISD::DEC";
19741   case X86ISD::OR:                 return "X86ISD::OR";
19742   case X86ISD::XOR:                return "X86ISD::XOR";
19743   case X86ISD::AND:                return "X86ISD::AND";
19744   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19745   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19746   case X86ISD::PTEST:              return "X86ISD::PTEST";
19747   case X86ISD::TESTP:              return "X86ISD::TESTP";
19748   case X86ISD::TESTM:              return "X86ISD::TESTM";
19749   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19750   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19751   case X86ISD::KTEST:              return "X86ISD::KTEST";
19752   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19753   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19754   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19755   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19756   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19757   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19758   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19759   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19760   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19761   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19762   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19763   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19764   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19765   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19766   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19767   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19768   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19769   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19770   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19771   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19772   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19773   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19774   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19775   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19776   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19777   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19778   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19779   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19780   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19781   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19782   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19783   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19784   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19785   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19786   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19787   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19788   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
19789   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19790   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19791   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19792   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19793   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19794   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19795   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19796   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19797   case X86ISD::SAHF:               return "X86ISD::SAHF";
19798   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19799   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19800   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19801   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19802   case X86ISD::FMADD:              return "X86ISD::FMADD";
19803   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19804   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19805   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19806   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19807   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19808   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19809   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19810   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19811   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19812   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19813   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19814   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19815   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19816   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
19817   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19818   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19819   case X86ISD::XTEST:              return "X86ISD::XTEST";
19820   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19821   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19822   case X86ISD::SELECT:             return "X86ISD::SELECT";
19823   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19824   case X86ISD::RCP28:              return "X86ISD::RCP28";
19825   case X86ISD::EXP2:               return "X86ISD::EXP2";
19826   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19827   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19828   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19829   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19830   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19831   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19832   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19833   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19834   case X86ISD::ADDS:               return "X86ISD::ADDS";
19835   case X86ISD::SUBS:               return "X86ISD::SUBS";
19836   case X86ISD::AVG:                return "X86ISD::AVG";
19837   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19838   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19839   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19840   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19841   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19842   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
19843   }
19844   return nullptr;
19845 }
19846
19847 // isLegalAddressingMode - Return true if the addressing mode represented
19848 // by AM is legal for this target, for a load/store of the specified type.
19849 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19850                                               const AddrMode &AM, Type *Ty,
19851                                               unsigned AS) const {
19852   // X86 supports extremely general addressing modes.
19853   CodeModel::Model M = getTargetMachine().getCodeModel();
19854   Reloc::Model R = getTargetMachine().getRelocationModel();
19855
19856   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19857   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19858     return false;
19859
19860   if (AM.BaseGV) {
19861     unsigned GVFlags =
19862       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19863
19864     // If a reference to this global requires an extra load, we can't fold it.
19865     if (isGlobalStubReference(GVFlags))
19866       return false;
19867
19868     // If BaseGV requires a register for the PIC base, we cannot also have a
19869     // BaseReg specified.
19870     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19871       return false;
19872
19873     // If lower 4G is not available, then we must use rip-relative addressing.
19874     if ((M != CodeModel::Small || R != Reloc::Static) &&
19875         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19876       return false;
19877   }
19878
19879   switch (AM.Scale) {
19880   case 0:
19881   case 1:
19882   case 2:
19883   case 4:
19884   case 8:
19885     // These scales always work.
19886     break;
19887   case 3:
19888   case 5:
19889   case 9:
19890     // These scales are formed with basereg+scalereg.  Only accept if there is
19891     // no basereg yet.
19892     if (AM.HasBaseReg)
19893       return false;
19894     break;
19895   default:  // Other stuff never works.
19896     return false;
19897   }
19898
19899   return true;
19900 }
19901
19902 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19903   unsigned Bits = Ty->getScalarSizeInBits();
19904
19905   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19906   // particularly cheaper than those without.
19907   if (Bits == 8)
19908     return false;
19909
19910   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19911   // variable shifts just as cheap as scalar ones.
19912   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19913     return false;
19914
19915   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19916   // fully general vector.
19917   return true;
19918 }
19919
19920 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19921   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19922     return false;
19923   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19924   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19925   return NumBits1 > NumBits2;
19926 }
19927
19928 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19929   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19930     return false;
19931
19932   if (!isTypeLegal(EVT::getEVT(Ty1)))
19933     return false;
19934
19935   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19936
19937   // Assuming the caller doesn't have a zeroext or signext return parameter,
19938   // truncation all the way down to i1 is valid.
19939   return true;
19940 }
19941
19942 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19943   return isInt<32>(Imm);
19944 }
19945
19946 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19947   // Can also use sub to handle negated immediates.
19948   return isInt<32>(Imm);
19949 }
19950
19951 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19952   if (!VT1.isInteger() || !VT2.isInteger())
19953     return false;
19954   unsigned NumBits1 = VT1.getSizeInBits();
19955   unsigned NumBits2 = VT2.getSizeInBits();
19956   return NumBits1 > NumBits2;
19957 }
19958
19959 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19960   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19961   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19962 }
19963
19964 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19965   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19966   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19967 }
19968
19969 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19970   EVT VT1 = Val.getValueType();
19971   if (isZExtFree(VT1, VT2))
19972     return true;
19973
19974   if (Val.getOpcode() != ISD::LOAD)
19975     return false;
19976
19977   if (!VT1.isSimple() || !VT1.isInteger() ||
19978       !VT2.isSimple() || !VT2.isInteger())
19979     return false;
19980
19981   switch (VT1.getSimpleVT().SimpleTy) {
19982   default: break;
19983   case MVT::i8:
19984   case MVT::i16:
19985   case MVT::i32:
19986     // X86 has 8, 16, and 32-bit zero-extending loads.
19987     return true;
19988   }
19989
19990   return false;
19991 }
19992
19993 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19994
19995 bool
19996 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19997   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19998     return false;
19999
20000   VT = VT.getScalarType();
20001
20002   if (!VT.isSimple())
20003     return false;
20004
20005   switch (VT.getSimpleVT().SimpleTy) {
20006   case MVT::f32:
20007   case MVT::f64:
20008     return true;
20009   default:
20010     break;
20011   }
20012
20013   return false;
20014 }
20015
20016 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20017   // i16 instructions are longer (0x66 prefix) and potentially slower.
20018   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20019 }
20020
20021 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20022 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20023 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20024 /// are assumed to be legal.
20025 bool
20026 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20027                                       EVT VT) const {
20028   if (!VT.isSimple())
20029     return false;
20030
20031   // Not for i1 vectors
20032   if (VT.getScalarType() == MVT::i1)
20033     return false;
20034
20035   // Very little shuffling can be done for 64-bit vectors right now.
20036   if (VT.getSizeInBits() == 64)
20037     return false;
20038
20039   // We only care that the types being shuffled are legal. The lowering can
20040   // handle any possible shuffle mask that results.
20041   return isTypeLegal(VT.getSimpleVT());
20042 }
20043
20044 bool
20045 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20046                                           EVT VT) const {
20047   // Just delegate to the generic legality, clear masks aren't special.
20048   return isShuffleMaskLegal(Mask, VT);
20049 }
20050
20051 //===----------------------------------------------------------------------===//
20052 //                           X86 Scheduler Hooks
20053 //===----------------------------------------------------------------------===//
20054
20055 /// Utility function to emit xbegin specifying the start of an RTM region.
20056 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20057                                      const TargetInstrInfo *TII) {
20058   DebugLoc DL = MI->getDebugLoc();
20059
20060   const BasicBlock *BB = MBB->getBasicBlock();
20061   MachineFunction::iterator I = MBB;
20062   ++I;
20063
20064   // For the v = xbegin(), we generate
20065   //
20066   // thisMBB:
20067   //  xbegin sinkMBB
20068   //
20069   // mainMBB:
20070   //  eax = -1
20071   //
20072   // sinkMBB:
20073   //  v = eax
20074
20075   MachineBasicBlock *thisMBB = MBB;
20076   MachineFunction *MF = MBB->getParent();
20077   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20078   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20079   MF->insert(I, mainMBB);
20080   MF->insert(I, sinkMBB);
20081
20082   // Transfer the remainder of BB and its successor edges to sinkMBB.
20083   sinkMBB->splice(sinkMBB->begin(), MBB,
20084                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20085   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20086
20087   // thisMBB:
20088   //  xbegin sinkMBB
20089   //  # fallthrough to mainMBB
20090   //  # abortion to sinkMBB
20091   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20092   thisMBB->addSuccessor(mainMBB);
20093   thisMBB->addSuccessor(sinkMBB);
20094
20095   // mainMBB:
20096   //  EAX = -1
20097   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20098   mainMBB->addSuccessor(sinkMBB);
20099
20100   // sinkMBB:
20101   // EAX is live into the sinkMBB
20102   sinkMBB->addLiveIn(X86::EAX);
20103   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20104           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20105     .addReg(X86::EAX);
20106
20107   MI->eraseFromParent();
20108   return sinkMBB;
20109 }
20110
20111 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20112 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20113 // in the .td file.
20114 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20115                                        const TargetInstrInfo *TII) {
20116   unsigned Opc;
20117   switch (MI->getOpcode()) {
20118   default: llvm_unreachable("illegal opcode!");
20119   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
20120   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20121   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
20122   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20123   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
20124   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20125   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
20126   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20127   }
20128
20129   DebugLoc dl = MI->getDebugLoc();
20130   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20131
20132   unsigned NumArgs = MI->getNumOperands();
20133   for (unsigned i = 1; i < NumArgs; ++i) {
20134     MachineOperand &Op = MI->getOperand(i);
20135     if (!(Op.isReg() && Op.isImplicit()))
20136       MIB.addOperand(Op);
20137   }
20138   if (MI->hasOneMemOperand())
20139     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20140
20141   BuildMI(*BB, MI, dl,
20142     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20143     .addReg(X86::XMM0);
20144
20145   MI->eraseFromParent();
20146   return BB;
20147 }
20148
20149 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20150 // defs in an instruction pattern
20151 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20152                                        const TargetInstrInfo *TII) {
20153   unsigned Opc;
20154   switch (MI->getOpcode()) {
20155   default: llvm_unreachable("illegal opcode!");
20156   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
20157   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20158   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
20159   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20160   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
20161   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20162   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
20163   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20164   }
20165
20166   DebugLoc dl = MI->getDebugLoc();
20167   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20168
20169   unsigned NumArgs = MI->getNumOperands(); // remove the results
20170   for (unsigned i = 1; i < NumArgs; ++i) {
20171     MachineOperand &Op = MI->getOperand(i);
20172     if (!(Op.isReg() && Op.isImplicit()))
20173       MIB.addOperand(Op);
20174   }
20175   if (MI->hasOneMemOperand())
20176     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20177
20178   BuildMI(*BB, MI, dl,
20179     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20180     .addReg(X86::ECX);
20181
20182   MI->eraseFromParent();
20183   return BB;
20184 }
20185
20186 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20187                                       const X86Subtarget *Subtarget) {
20188   DebugLoc dl = MI->getDebugLoc();
20189   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20190   // Address into RAX/EAX, other two args into ECX, EDX.
20191   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20192   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20193   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20194   for (int i = 0; i < X86::AddrNumOperands; ++i)
20195     MIB.addOperand(MI->getOperand(i));
20196
20197   unsigned ValOps = X86::AddrNumOperands;
20198   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20199     .addReg(MI->getOperand(ValOps).getReg());
20200   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20201     .addReg(MI->getOperand(ValOps+1).getReg());
20202
20203   // The instruction doesn't actually take any operands though.
20204   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20205
20206   MI->eraseFromParent(); // The pseudo is gone now.
20207   return BB;
20208 }
20209
20210 MachineBasicBlock *
20211 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20212                                                  MachineBasicBlock *MBB) const {
20213   // Emit va_arg instruction on X86-64.
20214
20215   // Operands to this pseudo-instruction:
20216   // 0  ) Output        : destination address (reg)
20217   // 1-5) Input         : va_list address (addr, i64mem)
20218   // 6  ) ArgSize       : Size (in bytes) of vararg type
20219   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20220   // 8  ) Align         : Alignment of type
20221   // 9  ) EFLAGS (implicit-def)
20222
20223   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20224   static_assert(X86::AddrNumOperands == 5,
20225                 "VAARG_64 assumes 5 address operands");
20226
20227   unsigned DestReg = MI->getOperand(0).getReg();
20228   MachineOperand &Base = MI->getOperand(1);
20229   MachineOperand &Scale = MI->getOperand(2);
20230   MachineOperand &Index = MI->getOperand(3);
20231   MachineOperand &Disp = MI->getOperand(4);
20232   MachineOperand &Segment = MI->getOperand(5);
20233   unsigned ArgSize = MI->getOperand(6).getImm();
20234   unsigned ArgMode = MI->getOperand(7).getImm();
20235   unsigned Align = MI->getOperand(8).getImm();
20236
20237   // Memory Reference
20238   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20239   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20240   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20241
20242   // Machine Information
20243   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20244   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20245   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20246   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20247   DebugLoc DL = MI->getDebugLoc();
20248
20249   // struct va_list {
20250   //   i32   gp_offset
20251   //   i32   fp_offset
20252   //   i64   overflow_area (address)
20253   //   i64   reg_save_area (address)
20254   // }
20255   // sizeof(va_list) = 24
20256   // alignment(va_list) = 8
20257
20258   unsigned TotalNumIntRegs = 6;
20259   unsigned TotalNumXMMRegs = 8;
20260   bool UseGPOffset = (ArgMode == 1);
20261   bool UseFPOffset = (ArgMode == 2);
20262   unsigned MaxOffset = TotalNumIntRegs * 8 +
20263                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20264
20265   /* Align ArgSize to a multiple of 8 */
20266   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20267   bool NeedsAlign = (Align > 8);
20268
20269   MachineBasicBlock *thisMBB = MBB;
20270   MachineBasicBlock *overflowMBB;
20271   MachineBasicBlock *offsetMBB;
20272   MachineBasicBlock *endMBB;
20273
20274   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20275   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20276   unsigned OffsetReg = 0;
20277
20278   if (!UseGPOffset && !UseFPOffset) {
20279     // If we only pull from the overflow region, we don't create a branch.
20280     // We don't need to alter control flow.
20281     OffsetDestReg = 0; // unused
20282     OverflowDestReg = DestReg;
20283
20284     offsetMBB = nullptr;
20285     overflowMBB = thisMBB;
20286     endMBB = thisMBB;
20287   } else {
20288     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20289     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20290     // If not, pull from overflow_area. (branch to overflowMBB)
20291     //
20292     //       thisMBB
20293     //         |     .
20294     //         |        .
20295     //     offsetMBB   overflowMBB
20296     //         |        .
20297     //         |     .
20298     //        endMBB
20299
20300     // Registers for the PHI in endMBB
20301     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20302     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20303
20304     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20305     MachineFunction *MF = MBB->getParent();
20306     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20307     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20308     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20309
20310     MachineFunction::iterator MBBIter = MBB;
20311     ++MBBIter;
20312
20313     // Insert the new basic blocks
20314     MF->insert(MBBIter, offsetMBB);
20315     MF->insert(MBBIter, overflowMBB);
20316     MF->insert(MBBIter, endMBB);
20317
20318     // Transfer the remainder of MBB and its successor edges to endMBB.
20319     endMBB->splice(endMBB->begin(), thisMBB,
20320                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20321     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20322
20323     // Make offsetMBB and overflowMBB successors of thisMBB
20324     thisMBB->addSuccessor(offsetMBB);
20325     thisMBB->addSuccessor(overflowMBB);
20326
20327     // endMBB is a successor of both offsetMBB and overflowMBB
20328     offsetMBB->addSuccessor(endMBB);
20329     overflowMBB->addSuccessor(endMBB);
20330
20331     // Load the offset value into a register
20332     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20333     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20334       .addOperand(Base)
20335       .addOperand(Scale)
20336       .addOperand(Index)
20337       .addDisp(Disp, UseFPOffset ? 4 : 0)
20338       .addOperand(Segment)
20339       .setMemRefs(MMOBegin, MMOEnd);
20340
20341     // Check if there is enough room left to pull this argument.
20342     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20343       .addReg(OffsetReg)
20344       .addImm(MaxOffset + 8 - ArgSizeA8);
20345
20346     // Branch to "overflowMBB" if offset >= max
20347     // Fall through to "offsetMBB" otherwise
20348     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20349       .addMBB(overflowMBB);
20350   }
20351
20352   // In offsetMBB, emit code to use the reg_save_area.
20353   if (offsetMBB) {
20354     assert(OffsetReg != 0);
20355
20356     // Read the reg_save_area address.
20357     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20358     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20359       .addOperand(Base)
20360       .addOperand(Scale)
20361       .addOperand(Index)
20362       .addDisp(Disp, 16)
20363       .addOperand(Segment)
20364       .setMemRefs(MMOBegin, MMOEnd);
20365
20366     // Zero-extend the offset
20367     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20368       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20369         .addImm(0)
20370         .addReg(OffsetReg)
20371         .addImm(X86::sub_32bit);
20372
20373     // Add the offset to the reg_save_area to get the final address.
20374     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20375       .addReg(OffsetReg64)
20376       .addReg(RegSaveReg);
20377
20378     // Compute the offset for the next argument
20379     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20380     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20381       .addReg(OffsetReg)
20382       .addImm(UseFPOffset ? 16 : 8);
20383
20384     // Store it back into the va_list.
20385     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20386       .addOperand(Base)
20387       .addOperand(Scale)
20388       .addOperand(Index)
20389       .addDisp(Disp, UseFPOffset ? 4 : 0)
20390       .addOperand(Segment)
20391       .addReg(NextOffsetReg)
20392       .setMemRefs(MMOBegin, MMOEnd);
20393
20394     // Jump to endMBB
20395     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20396       .addMBB(endMBB);
20397   }
20398
20399   //
20400   // Emit code to use overflow area
20401   //
20402
20403   // Load the overflow_area address into a register.
20404   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20405   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20406     .addOperand(Base)
20407     .addOperand(Scale)
20408     .addOperand(Index)
20409     .addDisp(Disp, 8)
20410     .addOperand(Segment)
20411     .setMemRefs(MMOBegin, MMOEnd);
20412
20413   // If we need to align it, do so. Otherwise, just copy the address
20414   // to OverflowDestReg.
20415   if (NeedsAlign) {
20416     // Align the overflow address
20417     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20418     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20419
20420     // aligned_addr = (addr + (align-1)) & ~(align-1)
20421     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20422       .addReg(OverflowAddrReg)
20423       .addImm(Align-1);
20424
20425     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20426       .addReg(TmpReg)
20427       .addImm(~(uint64_t)(Align-1));
20428   } else {
20429     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20430       .addReg(OverflowAddrReg);
20431   }
20432
20433   // Compute the next overflow address after this argument.
20434   // (the overflow address should be kept 8-byte aligned)
20435   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20436   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20437     .addReg(OverflowDestReg)
20438     .addImm(ArgSizeA8);
20439
20440   // Store the new overflow address.
20441   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20442     .addOperand(Base)
20443     .addOperand(Scale)
20444     .addOperand(Index)
20445     .addDisp(Disp, 8)
20446     .addOperand(Segment)
20447     .addReg(NextAddrReg)
20448     .setMemRefs(MMOBegin, MMOEnd);
20449
20450   // If we branched, emit the PHI to the front of endMBB.
20451   if (offsetMBB) {
20452     BuildMI(*endMBB, endMBB->begin(), DL,
20453             TII->get(X86::PHI), DestReg)
20454       .addReg(OffsetDestReg).addMBB(offsetMBB)
20455       .addReg(OverflowDestReg).addMBB(overflowMBB);
20456   }
20457
20458   // Erase the pseudo instruction
20459   MI->eraseFromParent();
20460
20461   return endMBB;
20462 }
20463
20464 MachineBasicBlock *
20465 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20466                                                  MachineInstr *MI,
20467                                                  MachineBasicBlock *MBB) const {
20468   // Emit code to save XMM registers to the stack. The ABI says that the
20469   // number of registers to save is given in %al, so it's theoretically
20470   // possible to do an indirect jump trick to avoid saving all of them,
20471   // however this code takes a simpler approach and just executes all
20472   // of the stores if %al is non-zero. It's less code, and it's probably
20473   // easier on the hardware branch predictor, and stores aren't all that
20474   // expensive anyway.
20475
20476   // Create the new basic blocks. One block contains all the XMM stores,
20477   // and one block is the final destination regardless of whether any
20478   // stores were performed.
20479   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20480   MachineFunction *F = MBB->getParent();
20481   MachineFunction::iterator MBBIter = MBB;
20482   ++MBBIter;
20483   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20484   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20485   F->insert(MBBIter, XMMSaveMBB);
20486   F->insert(MBBIter, EndMBB);
20487
20488   // Transfer the remainder of MBB and its successor edges to EndMBB.
20489   EndMBB->splice(EndMBB->begin(), MBB,
20490                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20491   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20492
20493   // The original block will now fall through to the XMM save block.
20494   MBB->addSuccessor(XMMSaveMBB);
20495   // The XMMSaveMBB will fall through to the end block.
20496   XMMSaveMBB->addSuccessor(EndMBB);
20497
20498   // Now add the instructions.
20499   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20500   DebugLoc DL = MI->getDebugLoc();
20501
20502   unsigned CountReg = MI->getOperand(0).getReg();
20503   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20504   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20505
20506   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20507     // If %al is 0, branch around the XMM save block.
20508     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20509     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20510     MBB->addSuccessor(EndMBB);
20511   }
20512
20513   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20514   // that was just emitted, but clearly shouldn't be "saved".
20515   assert((MI->getNumOperands() <= 3 ||
20516           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20517           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20518          && "Expected last argument to be EFLAGS");
20519   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20520   // In the XMM save block, save all the XMM argument registers.
20521   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20522     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20523     MachineMemOperand *MMO = F->getMachineMemOperand(
20524         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20525         MachineMemOperand::MOStore,
20526         /*Size=*/16, /*Align=*/16);
20527     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20528       .addFrameIndex(RegSaveFrameIndex)
20529       .addImm(/*Scale=*/1)
20530       .addReg(/*IndexReg=*/0)
20531       .addImm(/*Disp=*/Offset)
20532       .addReg(/*Segment=*/0)
20533       .addReg(MI->getOperand(i).getReg())
20534       .addMemOperand(MMO);
20535   }
20536
20537   MI->eraseFromParent();   // The pseudo instruction is gone now.
20538
20539   return EndMBB;
20540 }
20541
20542 // The EFLAGS operand of SelectItr might be missing a kill marker
20543 // because there were multiple uses of EFLAGS, and ISel didn't know
20544 // which to mark. Figure out whether SelectItr should have had a
20545 // kill marker, and set it if it should. Returns the correct kill
20546 // marker value.
20547 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20548                                      MachineBasicBlock* BB,
20549                                      const TargetRegisterInfo* TRI) {
20550   // Scan forward through BB for a use/def of EFLAGS.
20551   MachineBasicBlock::iterator miI(std::next(SelectItr));
20552   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20553     const MachineInstr& mi = *miI;
20554     if (mi.readsRegister(X86::EFLAGS))
20555       return false;
20556     if (mi.definesRegister(X86::EFLAGS))
20557       break; // Should have kill-flag - update below.
20558   }
20559
20560   // If we hit the end of the block, check whether EFLAGS is live into a
20561   // successor.
20562   if (miI == BB->end()) {
20563     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20564                                           sEnd = BB->succ_end();
20565          sItr != sEnd; ++sItr) {
20566       MachineBasicBlock* succ = *sItr;
20567       if (succ->isLiveIn(X86::EFLAGS))
20568         return false;
20569     }
20570   }
20571
20572   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20573   // out. SelectMI should have a kill flag on EFLAGS.
20574   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20575   return true;
20576 }
20577
20578 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20579 // together with other CMOV pseudo-opcodes into a single basic-block with
20580 // conditional jump around it.
20581 static bool isCMOVPseudo(MachineInstr *MI) {
20582   switch (MI->getOpcode()) {
20583   case X86::CMOV_FR32:
20584   case X86::CMOV_FR64:
20585   case X86::CMOV_GR8:
20586   case X86::CMOV_GR16:
20587   case X86::CMOV_GR32:
20588   case X86::CMOV_RFP32:
20589   case X86::CMOV_RFP64:
20590   case X86::CMOV_RFP80:
20591   case X86::CMOV_V2F64:
20592   case X86::CMOV_V2I64:
20593   case X86::CMOV_V4F32:
20594   case X86::CMOV_V4F64:
20595   case X86::CMOV_V4I64:
20596   case X86::CMOV_V16F32:
20597   case X86::CMOV_V8F32:
20598   case X86::CMOV_V8F64:
20599   case X86::CMOV_V8I64:
20600   case X86::CMOV_V8I1:
20601   case X86::CMOV_V16I1:
20602   case X86::CMOV_V32I1:
20603   case X86::CMOV_V64I1:
20604     return true;
20605
20606   default:
20607     return false;
20608   }
20609 }
20610
20611 MachineBasicBlock *
20612 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20613                                      MachineBasicBlock *BB) const {
20614   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20615   DebugLoc DL = MI->getDebugLoc();
20616
20617   // To "insert" a SELECT_CC instruction, we actually have to insert the
20618   // diamond control-flow pattern.  The incoming instruction knows the
20619   // destination vreg to set, the condition code register to branch on, the
20620   // true/false values to select between, and a branch opcode to use.
20621   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20622   MachineFunction::iterator It = BB;
20623   ++It;
20624
20625   //  thisMBB:
20626   //  ...
20627   //   TrueVal = ...
20628   //   cmpTY ccX, r1, r2
20629   //   bCC copy1MBB
20630   //   fallthrough --> copy0MBB
20631   MachineBasicBlock *thisMBB = BB;
20632   MachineFunction *F = BB->getParent();
20633
20634   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20635   // as described above, by inserting a BB, and then making a PHI at the join
20636   // point to select the true and false operands of the CMOV in the PHI.
20637   //
20638   // The code also handles two different cases of multiple CMOV opcodes
20639   // in a row.
20640   //
20641   // Case 1:
20642   // In this case, there are multiple CMOVs in a row, all which are based on
20643   // the same condition setting (or the exact opposite condition setting).
20644   // In this case we can lower all the CMOVs using a single inserted BB, and
20645   // then make a number of PHIs at the join point to model the CMOVs. The only
20646   // trickiness here, is that in a case like:
20647   //
20648   // t2 = CMOV cond1 t1, f1
20649   // t3 = CMOV cond1 t2, f2
20650   //
20651   // when rewriting this into PHIs, we have to perform some renaming on the
20652   // temps since you cannot have a PHI operand refer to a PHI result earlier
20653   // in the same block.  The "simple" but wrong lowering would be:
20654   //
20655   // t2 = PHI t1(BB1), f1(BB2)
20656   // t3 = PHI t2(BB1), f2(BB2)
20657   //
20658   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20659   // renaming is to note that on the path through BB1, t2 is really just a
20660   // copy of t1, and do that renaming, properly generating:
20661   //
20662   // t2 = PHI t1(BB1), f1(BB2)
20663   // t3 = PHI t1(BB1), f2(BB2)
20664   //
20665   // Case 2, we lower cascaded CMOVs such as
20666   //
20667   //   (CMOV (CMOV F, T, cc1), T, cc2)
20668   //
20669   // to two successives branches.  For that, we look for another CMOV as the
20670   // following instruction.
20671   //
20672   // Without this, we would add a PHI between the two jumps, which ends up
20673   // creating a few copies all around. For instance, for
20674   //
20675   //    (sitofp (zext (fcmp une)))
20676   //
20677   // we would generate:
20678   //
20679   //         ucomiss %xmm1, %xmm0
20680   //         movss  <1.0f>, %xmm0
20681   //         movaps  %xmm0, %xmm1
20682   //         jne     .LBB5_2
20683   //         xorps   %xmm1, %xmm1
20684   // .LBB5_2:
20685   //         jp      .LBB5_4
20686   //         movaps  %xmm1, %xmm0
20687   // .LBB5_4:
20688   //         retq
20689   //
20690   // because this custom-inserter would have generated:
20691   //
20692   //   A
20693   //   | \
20694   //   |  B
20695   //   | /
20696   //   C
20697   //   | \
20698   //   |  D
20699   //   | /
20700   //   E
20701   //
20702   // A: X = ...; Y = ...
20703   // B: empty
20704   // C: Z = PHI [X, A], [Y, B]
20705   // D: empty
20706   // E: PHI [X, C], [Z, D]
20707   //
20708   // If we lower both CMOVs in a single step, we can instead generate:
20709   //
20710   //   A
20711   //   | \
20712   //   |  C
20713   //   | /|
20714   //   |/ |
20715   //   |  |
20716   //   |  D
20717   //   | /
20718   //   E
20719   //
20720   // A: X = ...; Y = ...
20721   // D: empty
20722   // E: PHI [X, A], [X, C], [Y, D]
20723   //
20724   // Which, in our sitofp/fcmp example, gives us something like:
20725   //
20726   //         ucomiss %xmm1, %xmm0
20727   //         movss  <1.0f>, %xmm0
20728   //         jne     .LBB5_4
20729   //         jp      .LBB5_4
20730   //         xorps   %xmm0, %xmm0
20731   // .LBB5_4:
20732   //         retq
20733   //
20734   MachineInstr *CascadedCMOV = nullptr;
20735   MachineInstr *LastCMOV = MI;
20736   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20737   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20738   MachineBasicBlock::iterator NextMIIt =
20739       std::next(MachineBasicBlock::iterator(MI));
20740
20741   // Check for case 1, where there are multiple CMOVs with the same condition
20742   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
20743   // number of jumps the most.
20744
20745   if (isCMOVPseudo(MI)) {
20746     // See if we have a string of CMOVS with the same condition.
20747     while (NextMIIt != BB->end() &&
20748            isCMOVPseudo(NextMIIt) &&
20749            (NextMIIt->getOperand(3).getImm() == CC ||
20750             NextMIIt->getOperand(3).getImm() == OppCC)) {
20751       LastCMOV = &*NextMIIt;
20752       ++NextMIIt;
20753     }
20754   }
20755
20756   // This checks for case 2, but only do this if we didn't already find
20757   // case 1, as indicated by LastCMOV == MI.
20758   if (LastCMOV == MI &&
20759       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20760       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20761       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20762     CascadedCMOV = &*NextMIIt;
20763   }
20764
20765   MachineBasicBlock *jcc1MBB = nullptr;
20766
20767   // If we have a cascaded CMOV, we lower it to two successive branches to
20768   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20769   if (CascadedCMOV) {
20770     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20771     F->insert(It, jcc1MBB);
20772     jcc1MBB->addLiveIn(X86::EFLAGS);
20773   }
20774
20775   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20776   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20777   F->insert(It, copy0MBB);
20778   F->insert(It, sinkMBB);
20779
20780   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20781   // live into the sink and copy blocks.
20782   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20783
20784   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20785   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20786       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20787     copy0MBB->addLiveIn(X86::EFLAGS);
20788     sinkMBB->addLiveIn(X86::EFLAGS);
20789   }
20790
20791   // Transfer the remainder of BB and its successor edges to sinkMBB.
20792   sinkMBB->splice(sinkMBB->begin(), BB,
20793                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20794   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20795
20796   // Add the true and fallthrough blocks as its successors.
20797   if (CascadedCMOV) {
20798     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20799     BB->addSuccessor(jcc1MBB);
20800
20801     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20802     // jump to the sinkMBB.
20803     jcc1MBB->addSuccessor(copy0MBB);
20804     jcc1MBB->addSuccessor(sinkMBB);
20805   } else {
20806     BB->addSuccessor(copy0MBB);
20807   }
20808
20809   // The true block target of the first (or only) branch is always sinkMBB.
20810   BB->addSuccessor(sinkMBB);
20811
20812   // Create the conditional branch instruction.
20813   unsigned Opc = X86::GetCondBranchFromCond(CC);
20814   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20815
20816   if (CascadedCMOV) {
20817     unsigned Opc2 = X86::GetCondBranchFromCond(
20818         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20819     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20820   }
20821
20822   //  copy0MBB:
20823   //   %FalseValue = ...
20824   //   # fallthrough to sinkMBB
20825   copy0MBB->addSuccessor(sinkMBB);
20826
20827   //  sinkMBB:
20828   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20829   //  ...
20830   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20831   MachineBasicBlock::iterator MIItEnd =
20832     std::next(MachineBasicBlock::iterator(LastCMOV));
20833   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20834   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20835   MachineInstrBuilder MIB;
20836
20837   // As we are creating the PHIs, we have to be careful if there is more than
20838   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
20839   // PHIs have to reference the individual true/false inputs from earlier PHIs.
20840   // That also means that PHI construction must work forward from earlier to
20841   // later, and that the code must maintain a mapping from earlier PHI's
20842   // destination registers, and the registers that went into the PHI.
20843
20844   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20845     unsigned DestReg = MIIt->getOperand(0).getReg();
20846     unsigned Op1Reg = MIIt->getOperand(1).getReg();
20847     unsigned Op2Reg = MIIt->getOperand(2).getReg();
20848
20849     // If this CMOV we are generating is the opposite condition from
20850     // the jump we generated, then we have to swap the operands for the
20851     // PHI that is going to be generated.
20852     if (MIIt->getOperand(3).getImm() == OppCC)
20853         std::swap(Op1Reg, Op2Reg);
20854
20855     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20856       Op1Reg = RegRewriteTable[Op1Reg].first;
20857
20858     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20859       Op2Reg = RegRewriteTable[Op2Reg].second;
20860
20861     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20862                   TII->get(X86::PHI), DestReg)
20863           .addReg(Op1Reg).addMBB(copy0MBB)
20864           .addReg(Op2Reg).addMBB(thisMBB);
20865
20866     // Add this PHI to the rewrite table.
20867     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20868   }
20869
20870   // If we have a cascaded CMOV, the second Jcc provides the same incoming
20871   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20872   if (CascadedCMOV) {
20873     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20874     // Copy the PHI result to the register defined by the second CMOV.
20875     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20876             DL, TII->get(TargetOpcode::COPY),
20877             CascadedCMOV->getOperand(0).getReg())
20878         .addReg(MI->getOperand(0).getReg());
20879     CascadedCMOV->eraseFromParent();
20880   }
20881
20882   // Now remove the CMOV(s).
20883   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20884     (MIIt++)->eraseFromParent();
20885
20886   return sinkMBB;
20887 }
20888
20889 MachineBasicBlock *
20890 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20891                                        MachineBasicBlock *BB) const {
20892   // Combine the following atomic floating-point modification pattern:
20893   //   a.store(reg OP a.load(acquire), release)
20894   // Transform them into:
20895   //   OPss (%gpr), %xmm
20896   //   movss %xmm, (%gpr)
20897   // Or sd equivalent for 64-bit operations.
20898   unsigned MOp, FOp;
20899   switch (MI->getOpcode()) {
20900   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20901   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20902   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20903   }
20904   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20905   DebugLoc DL = MI->getDebugLoc();
20906   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20907   unsigned MSrc = MI->getOperand(0).getReg();
20908   unsigned VSrc = MI->getOperand(5).getReg();
20909   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20910                                 .addReg(/*Base=*/MSrc)
20911                                 .addImm(/*Scale=*/1)
20912                                 .addReg(/*Index=*/0)
20913                                 .addImm(0)
20914                                 .addReg(0);
20915   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20916                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20917                           .addReg(VSrc)
20918                           .addReg(/*Base=*/MSrc)
20919                           .addImm(/*Scale=*/1)
20920                           .addReg(/*Index=*/0)
20921                           .addImm(/*Disp=*/0)
20922                           .addReg(/*Segment=*/0);
20923   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20924   MI->eraseFromParent(); // The pseudo instruction is gone now.
20925   return BB;
20926 }
20927
20928 MachineBasicBlock *
20929 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20930                                         MachineBasicBlock *BB) const {
20931   MachineFunction *MF = BB->getParent();
20932   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20933   DebugLoc DL = MI->getDebugLoc();
20934   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20935
20936   assert(MF->shouldSplitStack());
20937
20938   const bool Is64Bit = Subtarget->is64Bit();
20939   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20940
20941   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20942   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20943
20944   // BB:
20945   //  ... [Till the alloca]
20946   // If stacklet is not large enough, jump to mallocMBB
20947   //
20948   // bumpMBB:
20949   //  Allocate by subtracting from RSP
20950   //  Jump to continueMBB
20951   //
20952   // mallocMBB:
20953   //  Allocate by call to runtime
20954   //
20955   // continueMBB:
20956   //  ...
20957   //  [rest of original BB]
20958   //
20959
20960   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20961   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20962   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20963
20964   MachineRegisterInfo &MRI = MF->getRegInfo();
20965   const TargetRegisterClass *AddrRegClass =
20966       getRegClassFor(getPointerTy(MF->getDataLayout()));
20967
20968   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20969     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20970     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20971     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20972     sizeVReg = MI->getOperand(1).getReg(),
20973     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20974
20975   MachineFunction::iterator MBBIter = BB;
20976   ++MBBIter;
20977
20978   MF->insert(MBBIter, bumpMBB);
20979   MF->insert(MBBIter, mallocMBB);
20980   MF->insert(MBBIter, continueMBB);
20981
20982   continueMBB->splice(continueMBB->begin(), BB,
20983                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20984   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20985
20986   // Add code to the main basic block to check if the stack limit has been hit,
20987   // and if so, jump to mallocMBB otherwise to bumpMBB.
20988   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20989   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20990     .addReg(tmpSPVReg).addReg(sizeVReg);
20991   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20992     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20993     .addReg(SPLimitVReg);
20994   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20995
20996   // bumpMBB simply decreases the stack pointer, since we know the current
20997   // stacklet has enough space.
20998   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20999     .addReg(SPLimitVReg);
21000   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
21001     .addReg(SPLimitVReg);
21002   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21003
21004   // Calls into a routine in libgcc to allocate more space from the heap.
21005   const uint32_t *RegMask =
21006       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
21007   if (IsLP64) {
21008     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
21009       .addReg(sizeVReg);
21010     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21011       .addExternalSymbol("__morestack_allocate_stack_space")
21012       .addRegMask(RegMask)
21013       .addReg(X86::RDI, RegState::Implicit)
21014       .addReg(X86::RAX, RegState::ImplicitDefine);
21015   } else if (Is64Bit) {
21016     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
21017       .addReg(sizeVReg);
21018     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21019       .addExternalSymbol("__morestack_allocate_stack_space")
21020       .addRegMask(RegMask)
21021       .addReg(X86::EDI, RegState::Implicit)
21022       .addReg(X86::EAX, RegState::ImplicitDefine);
21023   } else {
21024     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
21025       .addImm(12);
21026     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
21027     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
21028       .addExternalSymbol("__morestack_allocate_stack_space")
21029       .addRegMask(RegMask)
21030       .addReg(X86::EAX, RegState::ImplicitDefine);
21031   }
21032
21033   if (!Is64Bit)
21034     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
21035       .addImm(16);
21036
21037   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
21038     .addReg(IsLP64 ? X86::RAX : X86::EAX);
21039   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21040
21041   // Set up the CFG correctly.
21042   BB->addSuccessor(bumpMBB);
21043   BB->addSuccessor(mallocMBB);
21044   mallocMBB->addSuccessor(continueMBB);
21045   bumpMBB->addSuccessor(continueMBB);
21046
21047   // Take care of the PHI nodes.
21048   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
21049           MI->getOperand(0).getReg())
21050     .addReg(mallocPtrVReg).addMBB(mallocMBB)
21051     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
21052
21053   // Delete the original pseudo instruction.
21054   MI->eraseFromParent();
21055
21056   // And we're done.
21057   return continueMBB;
21058 }
21059
21060 MachineBasicBlock *
21061 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
21062                                         MachineBasicBlock *BB) const {
21063   DebugLoc DL = MI->getDebugLoc();
21064
21065   assert(!Subtarget->isTargetMachO());
21066
21067   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
21068                                                     DL);
21069
21070   MI->eraseFromParent();   // The pseudo instruction is gone now.
21071   return BB;
21072 }
21073
21074 MachineBasicBlock *
21075 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
21076                                       MachineBasicBlock *BB) const {
21077   // This is pretty easy.  We're taking the value that we received from
21078   // our load from the relocation, sticking it in either RDI (x86-64)
21079   // or EAX and doing an indirect call.  The return value will then
21080   // be in the normal return register.
21081   MachineFunction *F = BB->getParent();
21082   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21083   DebugLoc DL = MI->getDebugLoc();
21084
21085   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
21086   assert(MI->getOperand(3).isGlobal() && "This should be a global");
21087
21088   // Get a register mask for the lowered call.
21089   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
21090   // proper register mask.
21091   const uint32_t *RegMask =
21092       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
21093   if (Subtarget->is64Bit()) {
21094     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21095                                       TII->get(X86::MOV64rm), X86::RDI)
21096     .addReg(X86::RIP)
21097     .addImm(0).addReg(0)
21098     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21099                       MI->getOperand(3).getTargetFlags())
21100     .addReg(0);
21101     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
21102     addDirectMem(MIB, X86::RDI);
21103     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
21104   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
21105     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21106                                       TII->get(X86::MOV32rm), X86::EAX)
21107     .addReg(0)
21108     .addImm(0).addReg(0)
21109     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21110                       MI->getOperand(3).getTargetFlags())
21111     .addReg(0);
21112     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21113     addDirectMem(MIB, X86::EAX);
21114     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21115   } else {
21116     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21117                                       TII->get(X86::MOV32rm), X86::EAX)
21118     .addReg(TII->getGlobalBaseReg(F))
21119     .addImm(0).addReg(0)
21120     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21121                       MI->getOperand(3).getTargetFlags())
21122     .addReg(0);
21123     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21124     addDirectMem(MIB, X86::EAX);
21125     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21126   }
21127
21128   MI->eraseFromParent(); // The pseudo instruction is gone now.
21129   return BB;
21130 }
21131
21132 MachineBasicBlock *
21133 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21134                                     MachineBasicBlock *MBB) const {
21135   DebugLoc DL = MI->getDebugLoc();
21136   MachineFunction *MF = MBB->getParent();
21137   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21138   MachineRegisterInfo &MRI = MF->getRegInfo();
21139
21140   const BasicBlock *BB = MBB->getBasicBlock();
21141   MachineFunction::iterator I = MBB;
21142   ++I;
21143
21144   // Memory Reference
21145   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21146   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21147
21148   unsigned DstReg;
21149   unsigned MemOpndSlot = 0;
21150
21151   unsigned CurOp = 0;
21152
21153   DstReg = MI->getOperand(CurOp++).getReg();
21154   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21155   assert(RC->hasType(MVT::i32) && "Invalid destination!");
21156   unsigned mainDstReg = MRI.createVirtualRegister(RC);
21157   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21158
21159   MemOpndSlot = CurOp;
21160
21161   MVT PVT = getPointerTy(MF->getDataLayout());
21162   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21163          "Invalid Pointer Size!");
21164
21165   // For v = setjmp(buf), we generate
21166   //
21167   // thisMBB:
21168   //  buf[LabelOffset] = restoreMBB
21169   //  SjLjSetup restoreMBB
21170   //
21171   // mainMBB:
21172   //  v_main = 0
21173   //
21174   // sinkMBB:
21175   //  v = phi(main, restore)
21176   //
21177   // restoreMBB:
21178   //  if base pointer being used, load it from frame
21179   //  v_restore = 1
21180
21181   MachineBasicBlock *thisMBB = MBB;
21182   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21183   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21184   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21185   MF->insert(I, mainMBB);
21186   MF->insert(I, sinkMBB);
21187   MF->push_back(restoreMBB);
21188
21189   MachineInstrBuilder MIB;
21190
21191   // Transfer the remainder of BB and its successor edges to sinkMBB.
21192   sinkMBB->splice(sinkMBB->begin(), MBB,
21193                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21194   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21195
21196   // thisMBB:
21197   unsigned PtrStoreOpc = 0;
21198   unsigned LabelReg = 0;
21199   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21200   Reloc::Model RM = MF->getTarget().getRelocationModel();
21201   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21202                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21203
21204   // Prepare IP either in reg or imm.
21205   if (!UseImmLabel) {
21206     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21207     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21208     LabelReg = MRI.createVirtualRegister(PtrRC);
21209     if (Subtarget->is64Bit()) {
21210       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21211               .addReg(X86::RIP)
21212               .addImm(0)
21213               .addReg(0)
21214               .addMBB(restoreMBB)
21215               .addReg(0);
21216     } else {
21217       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21218       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21219               .addReg(XII->getGlobalBaseReg(MF))
21220               .addImm(0)
21221               .addReg(0)
21222               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21223               .addReg(0);
21224     }
21225   } else
21226     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21227   // Store IP
21228   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21229   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21230     if (i == X86::AddrDisp)
21231       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21232     else
21233       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21234   }
21235   if (!UseImmLabel)
21236     MIB.addReg(LabelReg);
21237   else
21238     MIB.addMBB(restoreMBB);
21239   MIB.setMemRefs(MMOBegin, MMOEnd);
21240   // Setup
21241   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21242           .addMBB(restoreMBB);
21243
21244   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21245   MIB.addRegMask(RegInfo->getNoPreservedMask());
21246   thisMBB->addSuccessor(mainMBB);
21247   thisMBB->addSuccessor(restoreMBB);
21248
21249   // mainMBB:
21250   //  EAX = 0
21251   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21252   mainMBB->addSuccessor(sinkMBB);
21253
21254   // sinkMBB:
21255   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21256           TII->get(X86::PHI), DstReg)
21257     .addReg(mainDstReg).addMBB(mainMBB)
21258     .addReg(restoreDstReg).addMBB(restoreMBB);
21259
21260   // restoreMBB:
21261   if (RegInfo->hasBasePointer(*MF)) {
21262     const bool Uses64BitFramePtr =
21263         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21264     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21265     X86FI->setRestoreBasePointer(MF);
21266     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21267     unsigned BasePtr = RegInfo->getBaseRegister();
21268     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21269     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21270                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
21271       .setMIFlag(MachineInstr::FrameSetup);
21272   }
21273   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21274   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21275   restoreMBB->addSuccessor(sinkMBB);
21276
21277   MI->eraseFromParent();
21278   return sinkMBB;
21279 }
21280
21281 MachineBasicBlock *
21282 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21283                                      MachineBasicBlock *MBB) const {
21284   DebugLoc DL = MI->getDebugLoc();
21285   MachineFunction *MF = MBB->getParent();
21286   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21287   MachineRegisterInfo &MRI = MF->getRegInfo();
21288
21289   // Memory Reference
21290   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21291   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21292
21293   MVT PVT = getPointerTy(MF->getDataLayout());
21294   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21295          "Invalid Pointer Size!");
21296
21297   const TargetRegisterClass *RC =
21298     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21299   unsigned Tmp = MRI.createVirtualRegister(RC);
21300   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21301   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21302   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21303   unsigned SP = RegInfo->getStackRegister();
21304
21305   MachineInstrBuilder MIB;
21306
21307   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21308   const int64_t SPOffset = 2 * PVT.getStoreSize();
21309
21310   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21311   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21312
21313   // Reload FP
21314   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21315   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21316     MIB.addOperand(MI->getOperand(i));
21317   MIB.setMemRefs(MMOBegin, MMOEnd);
21318   // Reload IP
21319   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21320   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21321     if (i == X86::AddrDisp)
21322       MIB.addDisp(MI->getOperand(i), LabelOffset);
21323     else
21324       MIB.addOperand(MI->getOperand(i));
21325   }
21326   MIB.setMemRefs(MMOBegin, MMOEnd);
21327   // Reload SP
21328   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21329   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21330     if (i == X86::AddrDisp)
21331       MIB.addDisp(MI->getOperand(i), SPOffset);
21332     else
21333       MIB.addOperand(MI->getOperand(i));
21334   }
21335   MIB.setMemRefs(MMOBegin, MMOEnd);
21336   // Jump
21337   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21338
21339   MI->eraseFromParent();
21340   return MBB;
21341 }
21342
21343 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21344 // accumulator loops. Writing back to the accumulator allows the coalescer
21345 // to remove extra copies in the loop.
21346 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
21347 MachineBasicBlock *
21348 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21349                                  MachineBasicBlock *MBB) const {
21350   MachineOperand &AddendOp = MI->getOperand(3);
21351
21352   // Bail out early if the addend isn't a register - we can't switch these.
21353   if (!AddendOp.isReg())
21354     return MBB;
21355
21356   MachineFunction &MF = *MBB->getParent();
21357   MachineRegisterInfo &MRI = MF.getRegInfo();
21358
21359   // Check whether the addend is defined by a PHI:
21360   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21361   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21362   if (!AddendDef.isPHI())
21363     return MBB;
21364
21365   // Look for the following pattern:
21366   // loop:
21367   //   %addend = phi [%entry, 0], [%loop, %result]
21368   //   ...
21369   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21370
21371   // Replace with:
21372   //   loop:
21373   //   %addend = phi [%entry, 0], [%loop, %result]
21374   //   ...
21375   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21376
21377   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21378     assert(AddendDef.getOperand(i).isReg());
21379     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21380     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21381     if (&PHISrcInst == MI) {
21382       // Found a matching instruction.
21383       unsigned NewFMAOpc = 0;
21384       switch (MI->getOpcode()) {
21385         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21386         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21387         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21388         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21389         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21390         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21391         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21392         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21393         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21394         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21395         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21396         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21397         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21398         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21399         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21400         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21401         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21402         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21403         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21404         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21405
21406         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21407         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21408         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21409         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21410         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21411         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21412         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21413         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21414         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21415         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21416         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21417         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21418         default: llvm_unreachable("Unrecognized FMA variant.");
21419       }
21420
21421       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21422       MachineInstrBuilder MIB =
21423         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21424         .addOperand(MI->getOperand(0))
21425         .addOperand(MI->getOperand(3))
21426         .addOperand(MI->getOperand(2))
21427         .addOperand(MI->getOperand(1));
21428       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21429       MI->eraseFromParent();
21430     }
21431   }
21432
21433   return MBB;
21434 }
21435
21436 MachineBasicBlock *
21437 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21438                                                MachineBasicBlock *BB) const {
21439   switch (MI->getOpcode()) {
21440   default: llvm_unreachable("Unexpected instr type to insert");
21441   case X86::TAILJMPd64:
21442   case X86::TAILJMPr64:
21443   case X86::TAILJMPm64:
21444   case X86::TAILJMPd64_REX:
21445   case X86::TAILJMPr64_REX:
21446   case X86::TAILJMPm64_REX:
21447     llvm_unreachable("TAILJMP64 would not be touched here.");
21448   case X86::TCRETURNdi64:
21449   case X86::TCRETURNri64:
21450   case X86::TCRETURNmi64:
21451     return BB;
21452   case X86::WIN_ALLOCA:
21453     return EmitLoweredWinAlloca(MI, BB);
21454   case X86::SEG_ALLOCA_32:
21455   case X86::SEG_ALLOCA_64:
21456     return EmitLoweredSegAlloca(MI, BB);
21457   case X86::TLSCall_32:
21458   case X86::TLSCall_64:
21459     return EmitLoweredTLSCall(MI, BB);
21460   case X86::CMOV_FR32:
21461   case X86::CMOV_FR64:
21462   case X86::CMOV_GR8:
21463   case X86::CMOV_GR16:
21464   case X86::CMOV_GR32:
21465   case X86::CMOV_RFP32:
21466   case X86::CMOV_RFP64:
21467   case X86::CMOV_RFP80:
21468   case X86::CMOV_V2F64:
21469   case X86::CMOV_V2I64:
21470   case X86::CMOV_V4F32:
21471   case X86::CMOV_V4F64:
21472   case X86::CMOV_V4I64:
21473   case X86::CMOV_V16F32:
21474   case X86::CMOV_V8F32:
21475   case X86::CMOV_V8F64:
21476   case X86::CMOV_V8I64:
21477   case X86::CMOV_V8I1:
21478   case X86::CMOV_V16I1:
21479   case X86::CMOV_V32I1:
21480   case X86::CMOV_V64I1:
21481     return EmitLoweredSelect(MI, BB);
21482
21483   case X86::RELEASE_FADD32mr:
21484   case X86::RELEASE_FADD64mr:
21485     return EmitLoweredAtomicFP(MI, BB);
21486
21487   case X86::FP32_TO_INT16_IN_MEM:
21488   case X86::FP32_TO_INT32_IN_MEM:
21489   case X86::FP32_TO_INT64_IN_MEM:
21490   case X86::FP64_TO_INT16_IN_MEM:
21491   case X86::FP64_TO_INT32_IN_MEM:
21492   case X86::FP64_TO_INT64_IN_MEM:
21493   case X86::FP80_TO_INT16_IN_MEM:
21494   case X86::FP80_TO_INT32_IN_MEM:
21495   case X86::FP80_TO_INT64_IN_MEM: {
21496     MachineFunction *F = BB->getParent();
21497     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21498     DebugLoc DL = MI->getDebugLoc();
21499
21500     // Change the floating point control register to use "round towards zero"
21501     // mode when truncating to an integer value.
21502     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21503     addFrameReference(BuildMI(*BB, MI, DL,
21504                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21505
21506     // Load the old value of the high byte of the control word...
21507     unsigned OldCW =
21508       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21509     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21510                       CWFrameIdx);
21511
21512     // Set the high part to be round to zero...
21513     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21514       .addImm(0xC7F);
21515
21516     // Reload the modified control word now...
21517     addFrameReference(BuildMI(*BB, MI, DL,
21518                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21519
21520     // Restore the memory image of control word to original value
21521     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21522       .addReg(OldCW);
21523
21524     // Get the X86 opcode to use.
21525     unsigned Opc;
21526     switch (MI->getOpcode()) {
21527     default: llvm_unreachable("illegal opcode!");
21528     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21529     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21530     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21531     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21532     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21533     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21534     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21535     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21536     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21537     }
21538
21539     X86AddressMode AM;
21540     MachineOperand &Op = MI->getOperand(0);
21541     if (Op.isReg()) {
21542       AM.BaseType = X86AddressMode::RegBase;
21543       AM.Base.Reg = Op.getReg();
21544     } else {
21545       AM.BaseType = X86AddressMode::FrameIndexBase;
21546       AM.Base.FrameIndex = Op.getIndex();
21547     }
21548     Op = MI->getOperand(1);
21549     if (Op.isImm())
21550       AM.Scale = Op.getImm();
21551     Op = MI->getOperand(2);
21552     if (Op.isImm())
21553       AM.IndexReg = Op.getImm();
21554     Op = MI->getOperand(3);
21555     if (Op.isGlobal()) {
21556       AM.GV = Op.getGlobal();
21557     } else {
21558       AM.Disp = Op.getImm();
21559     }
21560     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21561                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21562
21563     // Reload the original control word now.
21564     addFrameReference(BuildMI(*BB, MI, DL,
21565                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21566
21567     MI->eraseFromParent();   // The pseudo instruction is gone now.
21568     return BB;
21569   }
21570     // String/text processing lowering.
21571   case X86::PCMPISTRM128REG:
21572   case X86::VPCMPISTRM128REG:
21573   case X86::PCMPISTRM128MEM:
21574   case X86::VPCMPISTRM128MEM:
21575   case X86::PCMPESTRM128REG:
21576   case X86::VPCMPESTRM128REG:
21577   case X86::PCMPESTRM128MEM:
21578   case X86::VPCMPESTRM128MEM:
21579     assert(Subtarget->hasSSE42() &&
21580            "Target must have SSE4.2 or AVX features enabled");
21581     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21582
21583   // String/text processing lowering.
21584   case X86::PCMPISTRIREG:
21585   case X86::VPCMPISTRIREG:
21586   case X86::PCMPISTRIMEM:
21587   case X86::VPCMPISTRIMEM:
21588   case X86::PCMPESTRIREG:
21589   case X86::VPCMPESTRIREG:
21590   case X86::PCMPESTRIMEM:
21591   case X86::VPCMPESTRIMEM:
21592     assert(Subtarget->hasSSE42() &&
21593            "Target must have SSE4.2 or AVX features enabled");
21594     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21595
21596   // Thread synchronization.
21597   case X86::MONITOR:
21598     return EmitMonitor(MI, BB, Subtarget);
21599
21600   // xbegin
21601   case X86::XBEGIN:
21602     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21603
21604   case X86::VASTART_SAVE_XMM_REGS:
21605     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21606
21607   case X86::VAARG_64:
21608     return EmitVAARG64WithCustomInserter(MI, BB);
21609
21610   case X86::EH_SjLj_SetJmp32:
21611   case X86::EH_SjLj_SetJmp64:
21612     return emitEHSjLjSetJmp(MI, BB);
21613
21614   case X86::EH_SjLj_LongJmp32:
21615   case X86::EH_SjLj_LongJmp64:
21616     return emitEHSjLjLongJmp(MI, BB);
21617
21618   case TargetOpcode::STATEPOINT:
21619     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21620     // this point in the process.  We diverge later.
21621     return emitPatchPoint(MI, BB);
21622
21623   case TargetOpcode::STACKMAP:
21624   case TargetOpcode::PATCHPOINT:
21625     return emitPatchPoint(MI, BB);
21626
21627   case X86::VFMADDPDr213r:
21628   case X86::VFMADDPSr213r:
21629   case X86::VFMADDSDr213r:
21630   case X86::VFMADDSSr213r:
21631   case X86::VFMSUBPDr213r:
21632   case X86::VFMSUBPSr213r:
21633   case X86::VFMSUBSDr213r:
21634   case X86::VFMSUBSSr213r:
21635   case X86::VFNMADDPDr213r:
21636   case X86::VFNMADDPSr213r:
21637   case X86::VFNMADDSDr213r:
21638   case X86::VFNMADDSSr213r:
21639   case X86::VFNMSUBPDr213r:
21640   case X86::VFNMSUBPSr213r:
21641   case X86::VFNMSUBSDr213r:
21642   case X86::VFNMSUBSSr213r:
21643   case X86::VFMADDSUBPDr213r:
21644   case X86::VFMADDSUBPSr213r:
21645   case X86::VFMSUBADDPDr213r:
21646   case X86::VFMSUBADDPSr213r:
21647   case X86::VFMADDPDr213rY:
21648   case X86::VFMADDPSr213rY:
21649   case X86::VFMSUBPDr213rY:
21650   case X86::VFMSUBPSr213rY:
21651   case X86::VFNMADDPDr213rY:
21652   case X86::VFNMADDPSr213rY:
21653   case X86::VFNMSUBPDr213rY:
21654   case X86::VFNMSUBPSr213rY:
21655   case X86::VFMADDSUBPDr213rY:
21656   case X86::VFMADDSUBPSr213rY:
21657   case X86::VFMSUBADDPDr213rY:
21658   case X86::VFMSUBADDPSr213rY:
21659     return emitFMA3Instr(MI, BB);
21660   }
21661 }
21662
21663 //===----------------------------------------------------------------------===//
21664 //                           X86 Optimization Hooks
21665 //===----------------------------------------------------------------------===//
21666
21667 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21668                                                       APInt &KnownZero,
21669                                                       APInt &KnownOne,
21670                                                       const SelectionDAG &DAG,
21671                                                       unsigned Depth) const {
21672   unsigned BitWidth = KnownZero.getBitWidth();
21673   unsigned Opc = Op.getOpcode();
21674   assert((Opc >= ISD::BUILTIN_OP_END ||
21675           Opc == ISD::INTRINSIC_WO_CHAIN ||
21676           Opc == ISD::INTRINSIC_W_CHAIN ||
21677           Opc == ISD::INTRINSIC_VOID) &&
21678          "Should use MaskedValueIsZero if you don't know whether Op"
21679          " is a target node!");
21680
21681   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21682   switch (Opc) {
21683   default: break;
21684   case X86ISD::ADD:
21685   case X86ISD::SUB:
21686   case X86ISD::ADC:
21687   case X86ISD::SBB:
21688   case X86ISD::SMUL:
21689   case X86ISD::UMUL:
21690   case X86ISD::INC:
21691   case X86ISD::DEC:
21692   case X86ISD::OR:
21693   case X86ISD::XOR:
21694   case X86ISD::AND:
21695     // These nodes' second result is a boolean.
21696     if (Op.getResNo() == 0)
21697       break;
21698     // Fallthrough
21699   case X86ISD::SETCC:
21700     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21701     break;
21702   case ISD::INTRINSIC_WO_CHAIN: {
21703     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21704     unsigned NumLoBits = 0;
21705     switch (IntId) {
21706     default: break;
21707     case Intrinsic::x86_sse_movmsk_ps:
21708     case Intrinsic::x86_avx_movmsk_ps_256:
21709     case Intrinsic::x86_sse2_movmsk_pd:
21710     case Intrinsic::x86_avx_movmsk_pd_256:
21711     case Intrinsic::x86_mmx_pmovmskb:
21712     case Intrinsic::x86_sse2_pmovmskb_128:
21713     case Intrinsic::x86_avx2_pmovmskb: {
21714       // High bits of movmskp{s|d}, pmovmskb are known zero.
21715       switch (IntId) {
21716         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21717         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21718         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21719         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21720         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21721         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21722         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21723         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21724       }
21725       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21726       break;
21727     }
21728     }
21729     break;
21730   }
21731   }
21732 }
21733
21734 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21735   SDValue Op,
21736   const SelectionDAG &,
21737   unsigned Depth) const {
21738   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21739   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21740     return Op.getValueType().getScalarType().getSizeInBits();
21741
21742   // Fallback case.
21743   return 1;
21744 }
21745
21746 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21747 /// node is a GlobalAddress + offset.
21748 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21749                                        const GlobalValue* &GA,
21750                                        int64_t &Offset) const {
21751   if (N->getOpcode() == X86ISD::Wrapper) {
21752     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21753       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21754       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21755       return true;
21756     }
21757   }
21758   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21759 }
21760
21761 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21762 /// same as extracting the high 128-bit part of 256-bit vector and then
21763 /// inserting the result into the low part of a new 256-bit vector
21764 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21765   EVT VT = SVOp->getValueType(0);
21766   unsigned NumElems = VT.getVectorNumElements();
21767
21768   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21769   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21770     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21771         SVOp->getMaskElt(j) >= 0)
21772       return false;
21773
21774   return true;
21775 }
21776
21777 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21778 /// same as extracting the low 128-bit part of 256-bit vector and then
21779 /// inserting the result into the high part of a new 256-bit vector
21780 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21781   EVT VT = SVOp->getValueType(0);
21782   unsigned NumElems = VT.getVectorNumElements();
21783
21784   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21785   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21786     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21787         SVOp->getMaskElt(j) >= 0)
21788       return false;
21789
21790   return true;
21791 }
21792
21793 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21794 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21795                                         TargetLowering::DAGCombinerInfo &DCI,
21796                                         const X86Subtarget* Subtarget) {
21797   SDLoc dl(N);
21798   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21799   SDValue V1 = SVOp->getOperand(0);
21800   SDValue V2 = SVOp->getOperand(1);
21801   EVT VT = SVOp->getValueType(0);
21802   unsigned NumElems = VT.getVectorNumElements();
21803
21804   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21805       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21806     //
21807     //                   0,0,0,...
21808     //                      |
21809     //    V      UNDEF    BUILD_VECTOR    UNDEF
21810     //     \      /           \           /
21811     //  CONCAT_VECTOR         CONCAT_VECTOR
21812     //         \                  /
21813     //          \                /
21814     //          RESULT: V + zero extended
21815     //
21816     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21817         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21818         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21819       return SDValue();
21820
21821     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21822       return SDValue();
21823
21824     // To match the shuffle mask, the first half of the mask should
21825     // be exactly the first vector, and all the rest a splat with the
21826     // first element of the second one.
21827     for (unsigned i = 0; i != NumElems/2; ++i)
21828       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21829           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21830         return SDValue();
21831
21832     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21833     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21834       if (Ld->hasNUsesOfValue(1, 0)) {
21835         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21836         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21837         SDValue ResNode =
21838           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21839                                   Ld->getMemoryVT(),
21840                                   Ld->getPointerInfo(),
21841                                   Ld->getAlignment(),
21842                                   false/*isVolatile*/, true/*ReadMem*/,
21843                                   false/*WriteMem*/);
21844
21845         // Make sure the newly-created LOAD is in the same position as Ld in
21846         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21847         // and update uses of Ld's output chain to use the TokenFactor.
21848         if (Ld->hasAnyUseOfValue(1)) {
21849           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21850                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21851           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21852           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21853                                  SDValue(ResNode.getNode(), 1));
21854         }
21855
21856         return DAG.getBitcast(VT, ResNode);
21857       }
21858     }
21859
21860     // Emit a zeroed vector and insert the desired subvector on its
21861     // first half.
21862     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21863     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21864     return DCI.CombineTo(N, InsV);
21865   }
21866
21867   //===--------------------------------------------------------------------===//
21868   // Combine some shuffles into subvector extracts and inserts:
21869   //
21870
21871   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21872   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21873     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21874     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21875     return DCI.CombineTo(N, InsV);
21876   }
21877
21878   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21879   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21880     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21881     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21882     return DCI.CombineTo(N, InsV);
21883   }
21884
21885   return SDValue();
21886 }
21887
21888 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21889 /// possible.
21890 ///
21891 /// This is the leaf of the recursive combinine below. When we have found some
21892 /// chain of single-use x86 shuffle instructions and accumulated the combined
21893 /// shuffle mask represented by them, this will try to pattern match that mask
21894 /// into either a single instruction if there is a special purpose instruction
21895 /// for this operation, or into a PSHUFB instruction which is a fully general
21896 /// instruction but should only be used to replace chains over a certain depth.
21897 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21898                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21899                                    TargetLowering::DAGCombinerInfo &DCI,
21900                                    const X86Subtarget *Subtarget) {
21901   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21902
21903   // Find the operand that enters the chain. Note that multiple uses are OK
21904   // here, we're not going to remove the operand we find.
21905   SDValue Input = Op.getOperand(0);
21906   while (Input.getOpcode() == ISD::BITCAST)
21907     Input = Input.getOperand(0);
21908
21909   MVT VT = Input.getSimpleValueType();
21910   MVT RootVT = Root.getSimpleValueType();
21911   SDLoc DL(Root);
21912
21913   // Just remove no-op shuffle masks.
21914   if (Mask.size() == 1) {
21915     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21916                   /*AddTo*/ true);
21917     return true;
21918   }
21919
21920   // Use the float domain if the operand type is a floating point type.
21921   bool FloatDomain = VT.isFloatingPoint();
21922
21923   // For floating point shuffles, we don't have free copies in the shuffle
21924   // instructions or the ability to load as part of the instruction, so
21925   // canonicalize their shuffles to UNPCK or MOV variants.
21926   //
21927   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21928   // vectors because it can have a load folded into it that UNPCK cannot. This
21929   // doesn't preclude something switching to the shorter encoding post-RA.
21930   //
21931   // FIXME: Should teach these routines about AVX vector widths.
21932   if (FloatDomain && VT.getSizeInBits() == 128) {
21933     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21934       bool Lo = Mask.equals({0, 0});
21935       unsigned Shuffle;
21936       MVT ShuffleVT;
21937       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21938       // is no slower than UNPCKLPD but has the option to fold the input operand
21939       // into even an unaligned memory load.
21940       if (Lo && Subtarget->hasSSE3()) {
21941         Shuffle = X86ISD::MOVDDUP;
21942         ShuffleVT = MVT::v2f64;
21943       } else {
21944         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21945         // than the UNPCK variants.
21946         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21947         ShuffleVT = MVT::v4f32;
21948       }
21949       if (Depth == 1 && Root->getOpcode() == Shuffle)
21950         return false; // Nothing to do!
21951       Op = DAG.getBitcast(ShuffleVT, Input);
21952       DCI.AddToWorklist(Op.getNode());
21953       if (Shuffle == X86ISD::MOVDDUP)
21954         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21955       else
21956         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21957       DCI.AddToWorklist(Op.getNode());
21958       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21959                     /*AddTo*/ true);
21960       return true;
21961     }
21962     if (Subtarget->hasSSE3() &&
21963         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21964       bool Lo = Mask.equals({0, 0, 2, 2});
21965       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21966       MVT ShuffleVT = MVT::v4f32;
21967       if (Depth == 1 && Root->getOpcode() == Shuffle)
21968         return false; // Nothing to do!
21969       Op = DAG.getBitcast(ShuffleVT, Input);
21970       DCI.AddToWorklist(Op.getNode());
21971       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21972       DCI.AddToWorklist(Op.getNode());
21973       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21974                     /*AddTo*/ true);
21975       return true;
21976     }
21977     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21978       bool Lo = Mask.equals({0, 0, 1, 1});
21979       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21980       MVT ShuffleVT = MVT::v4f32;
21981       if (Depth == 1 && Root->getOpcode() == Shuffle)
21982         return false; // Nothing to do!
21983       Op = DAG.getBitcast(ShuffleVT, Input);
21984       DCI.AddToWorklist(Op.getNode());
21985       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21986       DCI.AddToWorklist(Op.getNode());
21987       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21988                     /*AddTo*/ true);
21989       return true;
21990     }
21991   }
21992
21993   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21994   // variants as none of these have single-instruction variants that are
21995   // superior to the UNPCK formulation.
21996   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21997       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21998        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21999        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
22000        Mask.equals(
22001            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
22002     bool Lo = Mask[0] == 0;
22003     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22004     if (Depth == 1 && Root->getOpcode() == Shuffle)
22005       return false; // Nothing to do!
22006     MVT ShuffleVT;
22007     switch (Mask.size()) {
22008     case 8:
22009       ShuffleVT = MVT::v8i16;
22010       break;
22011     case 16:
22012       ShuffleVT = MVT::v16i8;
22013       break;
22014     default:
22015       llvm_unreachable("Impossible mask size!");
22016     };
22017     Op = DAG.getBitcast(ShuffleVT, Input);
22018     DCI.AddToWorklist(Op.getNode());
22019     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22020     DCI.AddToWorklist(Op.getNode());
22021     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22022                   /*AddTo*/ true);
22023     return true;
22024   }
22025
22026   // Don't try to re-form single instruction chains under any circumstances now
22027   // that we've done encoding canonicalization for them.
22028   if (Depth < 2)
22029     return false;
22030
22031   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
22032   // can replace them with a single PSHUFB instruction profitably. Intel's
22033   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
22034   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
22035   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
22036     SmallVector<SDValue, 16> PSHUFBMask;
22037     int NumBytes = VT.getSizeInBits() / 8;
22038     int Ratio = NumBytes / Mask.size();
22039     for (int i = 0; i < NumBytes; ++i) {
22040       if (Mask[i / Ratio] == SM_SentinelUndef) {
22041         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
22042         continue;
22043       }
22044       int M = Mask[i / Ratio] != SM_SentinelZero
22045                   ? Ratio * Mask[i / Ratio] + i % Ratio
22046                   : 255;
22047       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
22048     }
22049     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
22050     Op = DAG.getBitcast(ByteVT, Input);
22051     DCI.AddToWorklist(Op.getNode());
22052     SDValue PSHUFBMaskOp =
22053         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
22054     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
22055     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
22056     DCI.AddToWorklist(Op.getNode());
22057     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22058                   /*AddTo*/ true);
22059     return true;
22060   }
22061
22062   // Failed to find any combines.
22063   return false;
22064 }
22065
22066 /// \brief Fully generic combining of x86 shuffle instructions.
22067 ///
22068 /// This should be the last combine run over the x86 shuffle instructions. Once
22069 /// they have been fully optimized, this will recursively consider all chains
22070 /// of single-use shuffle instructions, build a generic model of the cumulative
22071 /// shuffle operation, and check for simpler instructions which implement this
22072 /// operation. We use this primarily for two purposes:
22073 ///
22074 /// 1) Collapse generic shuffles to specialized single instructions when
22075 ///    equivalent. In most cases, this is just an encoding size win, but
22076 ///    sometimes we will collapse multiple generic shuffles into a single
22077 ///    special-purpose shuffle.
22078 /// 2) Look for sequences of shuffle instructions with 3 or more total
22079 ///    instructions, and replace them with the slightly more expensive SSSE3
22080 ///    PSHUFB instruction if available. We do this as the last combining step
22081 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
22082 ///    a suitable short sequence of other instructions. The PHUFB will either
22083 ///    use a register or have to read from memory and so is slightly (but only
22084 ///    slightly) more expensive than the other shuffle instructions.
22085 ///
22086 /// Because this is inherently a quadratic operation (for each shuffle in
22087 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
22088 /// This should never be an issue in practice as the shuffle lowering doesn't
22089 /// produce sequences of more than 8 instructions.
22090 ///
22091 /// FIXME: We will currently miss some cases where the redundant shuffling
22092 /// would simplify under the threshold for PSHUFB formation because of
22093 /// combine-ordering. To fix this, we should do the redundant instruction
22094 /// combining in this recursive walk.
22095 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
22096                                           ArrayRef<int> RootMask,
22097                                           int Depth, bool HasPSHUFB,
22098                                           SelectionDAG &DAG,
22099                                           TargetLowering::DAGCombinerInfo &DCI,
22100                                           const X86Subtarget *Subtarget) {
22101   // Bound the depth of our recursive combine because this is ultimately
22102   // quadratic in nature.
22103   if (Depth > 8)
22104     return false;
22105
22106   // Directly rip through bitcasts to find the underlying operand.
22107   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
22108     Op = Op.getOperand(0);
22109
22110   MVT VT = Op.getSimpleValueType();
22111   if (!VT.isVector())
22112     return false; // Bail if we hit a non-vector.
22113
22114   assert(Root.getSimpleValueType().isVector() &&
22115          "Shuffles operate on vector types!");
22116   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
22117          "Can only combine shuffles of the same vector register size.");
22118
22119   if (!isTargetShuffle(Op.getOpcode()))
22120     return false;
22121   SmallVector<int, 16> OpMask;
22122   bool IsUnary;
22123   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
22124   // We only can combine unary shuffles which we can decode the mask for.
22125   if (!HaveMask || !IsUnary)
22126     return false;
22127
22128   assert(VT.getVectorNumElements() == OpMask.size() &&
22129          "Different mask size from vector size!");
22130   assert(((RootMask.size() > OpMask.size() &&
22131            RootMask.size() % OpMask.size() == 0) ||
22132           (OpMask.size() > RootMask.size() &&
22133            OpMask.size() % RootMask.size() == 0) ||
22134           OpMask.size() == RootMask.size()) &&
22135          "The smaller number of elements must divide the larger.");
22136   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22137   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22138   assert(((RootRatio == 1 && OpRatio == 1) ||
22139           (RootRatio == 1) != (OpRatio == 1)) &&
22140          "Must not have a ratio for both incoming and op masks!");
22141
22142   SmallVector<int, 16> Mask;
22143   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22144
22145   // Merge this shuffle operation's mask into our accumulated mask. Note that
22146   // this shuffle's mask will be the first applied to the input, followed by the
22147   // root mask to get us all the way to the root value arrangement. The reason
22148   // for this order is that we are recursing up the operation chain.
22149   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22150     int RootIdx = i / RootRatio;
22151     if (RootMask[RootIdx] < 0) {
22152       // This is a zero or undef lane, we're done.
22153       Mask.push_back(RootMask[RootIdx]);
22154       continue;
22155     }
22156
22157     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22158     int OpIdx = RootMaskedIdx / OpRatio;
22159     if (OpMask[OpIdx] < 0) {
22160       // The incoming lanes are zero or undef, it doesn't matter which ones we
22161       // are using.
22162       Mask.push_back(OpMask[OpIdx]);
22163       continue;
22164     }
22165
22166     // Ok, we have non-zero lanes, map them through.
22167     Mask.push_back(OpMask[OpIdx] * OpRatio +
22168                    RootMaskedIdx % OpRatio);
22169   }
22170
22171   // See if we can recurse into the operand to combine more things.
22172   switch (Op.getOpcode()) {
22173   case X86ISD::PSHUFB:
22174     HasPSHUFB = true;
22175   case X86ISD::PSHUFD:
22176   case X86ISD::PSHUFHW:
22177   case X86ISD::PSHUFLW:
22178     if (Op.getOperand(0).hasOneUse() &&
22179         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22180                                       HasPSHUFB, DAG, DCI, Subtarget))
22181       return true;
22182     break;
22183
22184   case X86ISD::UNPCKL:
22185   case X86ISD::UNPCKH:
22186     assert(Op.getOperand(0) == Op.getOperand(1) &&
22187            "We only combine unary shuffles!");
22188     // We can't check for single use, we have to check that this shuffle is the
22189     // only user.
22190     if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22191         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22192                                       HasPSHUFB, DAG, DCI, Subtarget))
22193       return true;
22194     break;
22195   }
22196
22197   // Minor canonicalization of the accumulated shuffle mask to make it easier
22198   // to match below. All this does is detect masks with squential pairs of
22199   // elements, and shrink them to the half-width mask. It does this in a loop
22200   // so it will reduce the size of the mask to the minimal width mask which
22201   // performs an equivalent shuffle.
22202   SmallVector<int, 16> WidenedMask;
22203   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22204     Mask = std::move(WidenedMask);
22205     WidenedMask.clear();
22206   }
22207
22208   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22209                                 Subtarget);
22210 }
22211
22212 /// \brief Get the PSHUF-style mask from PSHUF node.
22213 ///
22214 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22215 /// PSHUF-style masks that can be reused with such instructions.
22216 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22217   MVT VT = N.getSimpleValueType();
22218   SmallVector<int, 4> Mask;
22219   bool IsUnary;
22220   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22221   (void)HaveMask;
22222   assert(HaveMask);
22223
22224   // If we have more than 128-bits, only the low 128-bits of shuffle mask
22225   // matter. Check that the upper masks are repeats and remove them.
22226   if (VT.getSizeInBits() > 128) {
22227     int LaneElts = 128 / VT.getScalarSizeInBits();
22228 #ifndef NDEBUG
22229     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22230       for (int j = 0; j < LaneElts; ++j)
22231         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22232                "Mask doesn't repeat in high 128-bit lanes!");
22233 #endif
22234     Mask.resize(LaneElts);
22235   }
22236
22237   switch (N.getOpcode()) {
22238   case X86ISD::PSHUFD:
22239     return Mask;
22240   case X86ISD::PSHUFLW:
22241     Mask.resize(4);
22242     return Mask;
22243   case X86ISD::PSHUFHW:
22244     Mask.erase(Mask.begin(), Mask.begin() + 4);
22245     for (int &M : Mask)
22246       M -= 4;
22247     return Mask;
22248   default:
22249     llvm_unreachable("No valid shuffle instruction found!");
22250   }
22251 }
22252
22253 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22254 ///
22255 /// We walk up the chain and look for a combinable shuffle, skipping over
22256 /// shuffles that we could hoist this shuffle's transformation past without
22257 /// altering anything.
22258 static SDValue
22259 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22260                              SelectionDAG &DAG,
22261                              TargetLowering::DAGCombinerInfo &DCI) {
22262   assert(N.getOpcode() == X86ISD::PSHUFD &&
22263          "Called with something other than an x86 128-bit half shuffle!");
22264   SDLoc DL(N);
22265
22266   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22267   // of the shuffles in the chain so that we can form a fresh chain to replace
22268   // this one.
22269   SmallVector<SDValue, 8> Chain;
22270   SDValue V = N.getOperand(0);
22271   for (; V.hasOneUse(); V = V.getOperand(0)) {
22272     switch (V.getOpcode()) {
22273     default:
22274       return SDValue(); // Nothing combined!
22275
22276     case ISD::BITCAST:
22277       // Skip bitcasts as we always know the type for the target specific
22278       // instructions.
22279       continue;
22280
22281     case X86ISD::PSHUFD:
22282       // Found another dword shuffle.
22283       break;
22284
22285     case X86ISD::PSHUFLW:
22286       // Check that the low words (being shuffled) are the identity in the
22287       // dword shuffle, and the high words are self-contained.
22288       if (Mask[0] != 0 || Mask[1] != 1 ||
22289           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22290         return SDValue();
22291
22292       Chain.push_back(V);
22293       continue;
22294
22295     case X86ISD::PSHUFHW:
22296       // Check that the high words (being shuffled) are the identity in the
22297       // dword shuffle, and the low words are self-contained.
22298       if (Mask[2] != 2 || Mask[3] != 3 ||
22299           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22300         return SDValue();
22301
22302       Chain.push_back(V);
22303       continue;
22304
22305     case X86ISD::UNPCKL:
22306     case X86ISD::UNPCKH:
22307       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22308       // shuffle into a preceding word shuffle.
22309       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
22310           V.getSimpleValueType().getScalarType() != MVT::i16)
22311         return SDValue();
22312
22313       // Search for a half-shuffle which we can combine with.
22314       unsigned CombineOp =
22315           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22316       if (V.getOperand(0) != V.getOperand(1) ||
22317           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22318         return SDValue();
22319       Chain.push_back(V);
22320       V = V.getOperand(0);
22321       do {
22322         switch (V.getOpcode()) {
22323         default:
22324           return SDValue(); // Nothing to combine.
22325
22326         case X86ISD::PSHUFLW:
22327         case X86ISD::PSHUFHW:
22328           if (V.getOpcode() == CombineOp)
22329             break;
22330
22331           Chain.push_back(V);
22332
22333           // Fallthrough!
22334         case ISD::BITCAST:
22335           V = V.getOperand(0);
22336           continue;
22337         }
22338         break;
22339       } while (V.hasOneUse());
22340       break;
22341     }
22342     // Break out of the loop if we break out of the switch.
22343     break;
22344   }
22345
22346   if (!V.hasOneUse())
22347     // We fell out of the loop without finding a viable combining instruction.
22348     return SDValue();
22349
22350   // Merge this node's mask and our incoming mask.
22351   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22352   for (int &M : Mask)
22353     M = VMask[M];
22354   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22355                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22356
22357   // Rebuild the chain around this new shuffle.
22358   while (!Chain.empty()) {
22359     SDValue W = Chain.pop_back_val();
22360
22361     if (V.getValueType() != W.getOperand(0).getValueType())
22362       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
22363
22364     switch (W.getOpcode()) {
22365     default:
22366       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22367
22368     case X86ISD::UNPCKL:
22369     case X86ISD::UNPCKH:
22370       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22371       break;
22372
22373     case X86ISD::PSHUFD:
22374     case X86ISD::PSHUFLW:
22375     case X86ISD::PSHUFHW:
22376       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22377       break;
22378     }
22379   }
22380   if (V.getValueType() != N.getValueType())
22381     V = DAG.getBitcast(N.getValueType(), V);
22382
22383   // Return the new chain to replace N.
22384   return V;
22385 }
22386
22387 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
22388 /// pshufhw.
22389 ///
22390 /// We walk up the chain, skipping shuffles of the other half and looking
22391 /// through shuffles which switch halves trying to find a shuffle of the same
22392 /// pair of dwords.
22393 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22394                                         SelectionDAG &DAG,
22395                                         TargetLowering::DAGCombinerInfo &DCI) {
22396   assert(
22397       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22398       "Called with something other than an x86 128-bit half shuffle!");
22399   SDLoc DL(N);
22400   unsigned CombineOpcode = N.getOpcode();
22401
22402   // Walk up a single-use chain looking for a combinable shuffle.
22403   SDValue V = N.getOperand(0);
22404   for (; V.hasOneUse(); V = V.getOperand(0)) {
22405     switch (V.getOpcode()) {
22406     default:
22407       return false; // Nothing combined!
22408
22409     case ISD::BITCAST:
22410       // Skip bitcasts as we always know the type for the target specific
22411       // instructions.
22412       continue;
22413
22414     case X86ISD::PSHUFLW:
22415     case X86ISD::PSHUFHW:
22416       if (V.getOpcode() == CombineOpcode)
22417         break;
22418
22419       // Other-half shuffles are no-ops.
22420       continue;
22421     }
22422     // Break out of the loop if we break out of the switch.
22423     break;
22424   }
22425
22426   if (!V.hasOneUse())
22427     // We fell out of the loop without finding a viable combining instruction.
22428     return false;
22429
22430   // Combine away the bottom node as its shuffle will be accumulated into
22431   // a preceding shuffle.
22432   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22433
22434   // Record the old value.
22435   SDValue Old = V;
22436
22437   // Merge this node's mask and our incoming mask (adjusted to account for all
22438   // the pshufd instructions encountered).
22439   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22440   for (int &M : Mask)
22441     M = VMask[M];
22442   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22443                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22444
22445   // Check that the shuffles didn't cancel each other out. If not, we need to
22446   // combine to the new one.
22447   if (Old != V)
22448     // Replace the combinable shuffle with the combined one, updating all users
22449     // so that we re-evaluate the chain here.
22450     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22451
22452   return true;
22453 }
22454
22455 /// \brief Try to combine x86 target specific shuffles.
22456 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22457                                            TargetLowering::DAGCombinerInfo &DCI,
22458                                            const X86Subtarget *Subtarget) {
22459   SDLoc DL(N);
22460   MVT VT = N.getSimpleValueType();
22461   SmallVector<int, 4> Mask;
22462
22463   switch (N.getOpcode()) {
22464   case X86ISD::PSHUFD:
22465   case X86ISD::PSHUFLW:
22466   case X86ISD::PSHUFHW:
22467     Mask = getPSHUFShuffleMask(N);
22468     assert(Mask.size() == 4);
22469     break;
22470   default:
22471     return SDValue();
22472   }
22473
22474   // Nuke no-op shuffles that show up after combining.
22475   if (isNoopShuffleMask(Mask))
22476     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22477
22478   // Look for simplifications involving one or two shuffle instructions.
22479   SDValue V = N.getOperand(0);
22480   switch (N.getOpcode()) {
22481   default:
22482     break;
22483   case X86ISD::PSHUFLW:
22484   case X86ISD::PSHUFHW:
22485     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22486
22487     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22488       return SDValue(); // We combined away this shuffle, so we're done.
22489
22490     // See if this reduces to a PSHUFD which is no more expensive and can
22491     // combine with more operations. Note that it has to at least flip the
22492     // dwords as otherwise it would have been removed as a no-op.
22493     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22494       int DMask[] = {0, 1, 2, 3};
22495       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22496       DMask[DOffset + 0] = DOffset + 1;
22497       DMask[DOffset + 1] = DOffset + 0;
22498       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22499       V = DAG.getBitcast(DVT, V);
22500       DCI.AddToWorklist(V.getNode());
22501       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22502                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22503       DCI.AddToWorklist(V.getNode());
22504       return DAG.getBitcast(VT, V);
22505     }
22506
22507     // Look for shuffle patterns which can be implemented as a single unpack.
22508     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22509     // only works when we have a PSHUFD followed by two half-shuffles.
22510     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22511         (V.getOpcode() == X86ISD::PSHUFLW ||
22512          V.getOpcode() == X86ISD::PSHUFHW) &&
22513         V.getOpcode() != N.getOpcode() &&
22514         V.hasOneUse()) {
22515       SDValue D = V.getOperand(0);
22516       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22517         D = D.getOperand(0);
22518       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22519         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22520         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22521         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22522         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22523         int WordMask[8];
22524         for (int i = 0; i < 4; ++i) {
22525           WordMask[i + NOffset] = Mask[i] + NOffset;
22526           WordMask[i + VOffset] = VMask[i] + VOffset;
22527         }
22528         // Map the word mask through the DWord mask.
22529         int MappedMask[8];
22530         for (int i = 0; i < 8; ++i)
22531           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22532         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22533             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22534           // We can replace all three shuffles with an unpack.
22535           V = DAG.getBitcast(VT, D.getOperand(0));
22536           DCI.AddToWorklist(V.getNode());
22537           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22538                                                 : X86ISD::UNPCKH,
22539                              DL, VT, V, V);
22540         }
22541       }
22542     }
22543
22544     break;
22545
22546   case X86ISD::PSHUFD:
22547     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22548       return NewN;
22549
22550     break;
22551   }
22552
22553   return SDValue();
22554 }
22555
22556 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22557 ///
22558 /// We combine this directly on the abstract vector shuffle nodes so it is
22559 /// easier to generically match. We also insert dummy vector shuffle nodes for
22560 /// the operands which explicitly discard the lanes which are unused by this
22561 /// operation to try to flow through the rest of the combiner the fact that
22562 /// they're unused.
22563 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22564   SDLoc DL(N);
22565   EVT VT = N->getValueType(0);
22566
22567   // We only handle target-independent shuffles.
22568   // FIXME: It would be easy and harmless to use the target shuffle mask
22569   // extraction tool to support more.
22570   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22571     return SDValue();
22572
22573   auto *SVN = cast<ShuffleVectorSDNode>(N);
22574   ArrayRef<int> Mask = SVN->getMask();
22575   SDValue V1 = N->getOperand(0);
22576   SDValue V2 = N->getOperand(1);
22577
22578   // We require the first shuffle operand to be the SUB node, and the second to
22579   // be the ADD node.
22580   // FIXME: We should support the commuted patterns.
22581   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22582     return SDValue();
22583
22584   // If there are other uses of these operations we can't fold them.
22585   if (!V1->hasOneUse() || !V2->hasOneUse())
22586     return SDValue();
22587
22588   // Ensure that both operations have the same operands. Note that we can
22589   // commute the FADD operands.
22590   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22591   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22592       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22593     return SDValue();
22594
22595   // We're looking for blends between FADD and FSUB nodes. We insist on these
22596   // nodes being lined up in a specific expected pattern.
22597   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22598         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22599         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22600     return SDValue();
22601
22602   // Only specific types are legal at this point, assert so we notice if and
22603   // when these change.
22604   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22605           VT == MVT::v4f64) &&
22606          "Unknown vector type encountered!");
22607
22608   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22609 }
22610
22611 /// PerformShuffleCombine - Performs several different shuffle combines.
22612 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22613                                      TargetLowering::DAGCombinerInfo &DCI,
22614                                      const X86Subtarget *Subtarget) {
22615   SDLoc dl(N);
22616   SDValue N0 = N->getOperand(0);
22617   SDValue N1 = N->getOperand(1);
22618   EVT VT = N->getValueType(0);
22619
22620   // Don't create instructions with illegal types after legalize types has run.
22621   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22622   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22623     return SDValue();
22624
22625   // If we have legalized the vector types, look for blends of FADD and FSUB
22626   // nodes that we can fuse into an ADDSUB node.
22627   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22628     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22629       return AddSub;
22630
22631   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22632   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22633       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22634     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22635
22636   // During Type Legalization, when promoting illegal vector types,
22637   // the backend might introduce new shuffle dag nodes and bitcasts.
22638   //
22639   // This code performs the following transformation:
22640   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22641   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22642   //
22643   // We do this only if both the bitcast and the BINOP dag nodes have
22644   // one use. Also, perform this transformation only if the new binary
22645   // operation is legal. This is to avoid introducing dag nodes that
22646   // potentially need to be further expanded (or custom lowered) into a
22647   // less optimal sequence of dag nodes.
22648   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22649       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22650       N0.getOpcode() == ISD::BITCAST) {
22651     SDValue BC0 = N0.getOperand(0);
22652     EVT SVT = BC0.getValueType();
22653     unsigned Opcode = BC0.getOpcode();
22654     unsigned NumElts = VT.getVectorNumElements();
22655
22656     if (BC0.hasOneUse() && SVT.isVector() &&
22657         SVT.getVectorNumElements() * 2 == NumElts &&
22658         TLI.isOperationLegal(Opcode, VT)) {
22659       bool CanFold = false;
22660       switch (Opcode) {
22661       default : break;
22662       case ISD::ADD :
22663       case ISD::FADD :
22664       case ISD::SUB :
22665       case ISD::FSUB :
22666       case ISD::MUL :
22667       case ISD::FMUL :
22668         CanFold = true;
22669       }
22670
22671       unsigned SVTNumElts = SVT.getVectorNumElements();
22672       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22673       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22674         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22675       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22676         CanFold = SVOp->getMaskElt(i) < 0;
22677
22678       if (CanFold) {
22679         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22680         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22681         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22682         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22683       }
22684     }
22685   }
22686
22687   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22688   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22689   // consecutive, non-overlapping, and in the right order.
22690   SmallVector<SDValue, 16> Elts;
22691   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22692     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22693
22694   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22695     return LD;
22696
22697   if (isTargetShuffle(N->getOpcode())) {
22698     SDValue Shuffle =
22699         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22700     if (Shuffle.getNode())
22701       return Shuffle;
22702
22703     // Try recursively combining arbitrary sequences of x86 shuffle
22704     // instructions into higher-order shuffles. We do this after combining
22705     // specific PSHUF instruction sequences into their minimal form so that we
22706     // can evaluate how many specialized shuffle instructions are involved in
22707     // a particular chain.
22708     SmallVector<int, 1> NonceMask; // Just a placeholder.
22709     NonceMask.push_back(0);
22710     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22711                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22712                                       DCI, Subtarget))
22713       return SDValue(); // This routine will use CombineTo to replace N.
22714   }
22715
22716   return SDValue();
22717 }
22718
22719 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22720 /// specific shuffle of a load can be folded into a single element load.
22721 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22722 /// shuffles have been custom lowered so we need to handle those here.
22723 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22724                                          TargetLowering::DAGCombinerInfo &DCI) {
22725   if (DCI.isBeforeLegalizeOps())
22726     return SDValue();
22727
22728   SDValue InVec = N->getOperand(0);
22729   SDValue EltNo = N->getOperand(1);
22730
22731   if (!isa<ConstantSDNode>(EltNo))
22732     return SDValue();
22733
22734   EVT OriginalVT = InVec.getValueType();
22735
22736   if (InVec.getOpcode() == ISD::BITCAST) {
22737     // Don't duplicate a load with other uses.
22738     if (!InVec.hasOneUse())
22739       return SDValue();
22740     EVT BCVT = InVec.getOperand(0).getValueType();
22741     if (!BCVT.isVector() ||
22742         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22743       return SDValue();
22744     InVec = InVec.getOperand(0);
22745   }
22746
22747   EVT CurrentVT = InVec.getValueType();
22748
22749   if (!isTargetShuffle(InVec.getOpcode()))
22750     return SDValue();
22751
22752   // Don't duplicate a load with other uses.
22753   if (!InVec.hasOneUse())
22754     return SDValue();
22755
22756   SmallVector<int, 16> ShuffleMask;
22757   bool UnaryShuffle;
22758   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22759                             ShuffleMask, UnaryShuffle))
22760     return SDValue();
22761
22762   // Select the input vector, guarding against out of range extract vector.
22763   unsigned NumElems = CurrentVT.getVectorNumElements();
22764   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22765   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22766   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22767                                          : InVec.getOperand(1);
22768
22769   // If inputs to shuffle are the same for both ops, then allow 2 uses
22770   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22771                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22772
22773   if (LdNode.getOpcode() == ISD::BITCAST) {
22774     // Don't duplicate a load with other uses.
22775     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22776       return SDValue();
22777
22778     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22779     LdNode = LdNode.getOperand(0);
22780   }
22781
22782   if (!ISD::isNormalLoad(LdNode.getNode()))
22783     return SDValue();
22784
22785   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22786
22787   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22788     return SDValue();
22789
22790   EVT EltVT = N->getValueType(0);
22791   // If there's a bitcast before the shuffle, check if the load type and
22792   // alignment is valid.
22793   unsigned Align = LN0->getAlignment();
22794   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22795   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22796       EltVT.getTypeForEVT(*DAG.getContext()));
22797
22798   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22799     return SDValue();
22800
22801   // All checks match so transform back to vector_shuffle so that DAG combiner
22802   // can finish the job
22803   SDLoc dl(N);
22804
22805   // Create shuffle node taking into account the case that its a unary shuffle
22806   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22807                                    : InVec.getOperand(1);
22808   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22809                                  InVec.getOperand(0), Shuffle,
22810                                  &ShuffleMask[0]);
22811   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22812   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22813                      EltNo);
22814 }
22815
22816 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22817 /// special and don't usually play with other vector types, it's better to
22818 /// handle them early to be sure we emit efficient code by avoiding
22819 /// store-load conversions.
22820 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22821   if (N->getValueType(0) != MVT::x86mmx ||
22822       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22823       N->getOperand(0)->getValueType(0) != MVT::v2i32)
22824     return SDValue();
22825
22826   SDValue V = N->getOperand(0);
22827   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22828   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22829     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22830                        N->getValueType(0), V.getOperand(0));
22831
22832   return SDValue();
22833 }
22834
22835 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22836 /// generation and convert it from being a bunch of shuffles and extracts
22837 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22838 /// storing the value and loading scalars back, while for x64 we should
22839 /// use 64-bit extracts and shifts.
22840 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22841                                          TargetLowering::DAGCombinerInfo &DCI) {
22842   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22843     return NewOp;
22844
22845   SDValue InputVector = N->getOperand(0);
22846   SDLoc dl(InputVector);
22847   // Detect mmx to i32 conversion through a v2i32 elt extract.
22848   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22849       N->getValueType(0) == MVT::i32 &&
22850       InputVector.getValueType() == MVT::v2i32) {
22851
22852     // The bitcast source is a direct mmx result.
22853     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22854     if (MMXSrc.getValueType() == MVT::x86mmx)
22855       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22856                          N->getValueType(0),
22857                          InputVector.getNode()->getOperand(0));
22858
22859     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22860     SDValue MMXSrcOp = MMXSrc.getOperand(0);
22861     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22862         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22863         MMXSrcOp.getOpcode() == ISD::BITCAST &&
22864         MMXSrcOp.getValueType() == MVT::v1i64 &&
22865         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22866       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22867                          N->getValueType(0),
22868                          MMXSrcOp.getOperand(0));
22869   }
22870
22871   EVT VT = N->getValueType(0);
22872
22873   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22874       InputVector.getOpcode() == ISD::BITCAST &&
22875       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22876     uint64_t ExtractedElt =
22877           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22878     uint64_t InputValue =
22879           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22880     uint64_t Res = (InputValue >> ExtractedElt) & 1;
22881     return DAG.getConstant(Res, dl, MVT::i1);
22882   }
22883   // Only operate on vectors of 4 elements, where the alternative shuffling
22884   // gets to be more expensive.
22885   if (InputVector.getValueType() != MVT::v4i32)
22886     return SDValue();
22887
22888   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22889   // single use which is a sign-extend or zero-extend, and all elements are
22890   // used.
22891   SmallVector<SDNode *, 4> Uses;
22892   unsigned ExtractedElements = 0;
22893   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22894        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22895     if (UI.getUse().getResNo() != InputVector.getResNo())
22896       return SDValue();
22897
22898     SDNode *Extract = *UI;
22899     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22900       return SDValue();
22901
22902     if (Extract->getValueType(0) != MVT::i32)
22903       return SDValue();
22904     if (!Extract->hasOneUse())
22905       return SDValue();
22906     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22907         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22908       return SDValue();
22909     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22910       return SDValue();
22911
22912     // Record which element was extracted.
22913     ExtractedElements |=
22914       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22915
22916     Uses.push_back(Extract);
22917   }
22918
22919   // If not all the elements were used, this may not be worthwhile.
22920   if (ExtractedElements != 15)
22921     return SDValue();
22922
22923   // Ok, we've now decided to do the transformation.
22924   // If 64-bit shifts are legal, use the extract-shift sequence,
22925   // otherwise bounce the vector off the cache.
22926   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22927   SDValue Vals[4];
22928
22929   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22930     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22931     auto &DL = DAG.getDataLayout();
22932     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22933     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22934       DAG.getConstant(0, dl, VecIdxTy));
22935     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22936       DAG.getConstant(1, dl, VecIdxTy));
22937
22938     SDValue ShAmt = DAG.getConstant(
22939         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22940     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22941     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22942       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22943     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22944     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22945       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22946   } else {
22947     // Store the value to a temporary stack slot.
22948     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22949     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22950       MachinePointerInfo(), false, false, 0);
22951
22952     EVT ElementType = InputVector.getValueType().getVectorElementType();
22953     unsigned EltSize = ElementType.getSizeInBits() / 8;
22954
22955     // Replace each use (extract) with a load of the appropriate element.
22956     for (unsigned i = 0; i < 4; ++i) {
22957       uint64_t Offset = EltSize * i;
22958       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22959       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22960
22961       SDValue ScalarAddr =
22962           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22963
22964       // Load the scalar.
22965       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22966                             ScalarAddr, MachinePointerInfo(),
22967                             false, false, false, 0);
22968
22969     }
22970   }
22971
22972   // Replace the extracts
22973   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22974     UE = Uses.end(); UI != UE; ++UI) {
22975     SDNode *Extract = *UI;
22976
22977     SDValue Idx = Extract->getOperand(1);
22978     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22979     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22980   }
22981
22982   // The replacement was made in place; don't return anything.
22983   return SDValue();
22984 }
22985
22986 static SDValue
22987 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22988                                       const X86Subtarget *Subtarget) {
22989   SDLoc dl(N);
22990   SDValue Cond = N->getOperand(0);
22991   SDValue LHS = N->getOperand(1);
22992   SDValue RHS = N->getOperand(2);
22993
22994   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22995     SDValue CondSrc = Cond->getOperand(0);
22996     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22997       Cond = CondSrc->getOperand(0);
22998   }
22999
23000   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
23001     return SDValue();
23002
23003   // A vselect where all conditions and data are constants can be optimized into
23004   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
23005   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
23006       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
23007     return SDValue();
23008
23009   unsigned MaskValue = 0;
23010   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
23011     return SDValue();
23012
23013   MVT VT = N->getSimpleValueType(0);
23014   unsigned NumElems = VT.getVectorNumElements();
23015   SmallVector<int, 8> ShuffleMask(NumElems, -1);
23016   for (unsigned i = 0; i < NumElems; ++i) {
23017     // Be sure we emit undef where we can.
23018     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
23019       ShuffleMask[i] = -1;
23020     else
23021       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
23022   }
23023
23024   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23025   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
23026     return SDValue();
23027   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
23028 }
23029
23030 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
23031 /// nodes.
23032 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
23033                                     TargetLowering::DAGCombinerInfo &DCI,
23034                                     const X86Subtarget *Subtarget) {
23035   SDLoc DL(N);
23036   SDValue Cond = N->getOperand(0);
23037   // Get the LHS/RHS of the select.
23038   SDValue LHS = N->getOperand(1);
23039   SDValue RHS = N->getOperand(2);
23040   EVT VT = LHS.getValueType();
23041   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23042
23043   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
23044   // instructions match the semantics of the common C idiom x<y?x:y but not
23045   // x<=y?x:y, because of how they handle negative zero (which can be
23046   // ignored in unsafe-math mode).
23047   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
23048   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
23049       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
23050       (Subtarget->hasSSE2() ||
23051        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
23052     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23053
23054     unsigned Opcode = 0;
23055     // Check for x CC y ? x : y.
23056     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23057         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23058       switch (CC) {
23059       default: break;
23060       case ISD::SETULT:
23061         // Converting this to a min would handle NaNs incorrectly, and swapping
23062         // the operands would cause it to handle comparisons between positive
23063         // and negative zero incorrectly.
23064         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23065           if (!DAG.getTarget().Options.UnsafeFPMath &&
23066               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23067             break;
23068           std::swap(LHS, RHS);
23069         }
23070         Opcode = X86ISD::FMIN;
23071         break;
23072       case ISD::SETOLE:
23073         // Converting this to a min would handle comparisons between positive
23074         // and negative zero incorrectly.
23075         if (!DAG.getTarget().Options.UnsafeFPMath &&
23076             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23077           break;
23078         Opcode = X86ISD::FMIN;
23079         break;
23080       case ISD::SETULE:
23081         // Converting this to a min would handle both negative zeros and NaNs
23082         // incorrectly, but we can swap the operands to fix both.
23083         std::swap(LHS, RHS);
23084       case ISD::SETOLT:
23085       case ISD::SETLT:
23086       case ISD::SETLE:
23087         Opcode = X86ISD::FMIN;
23088         break;
23089
23090       case ISD::SETOGE:
23091         // Converting this to a max would handle comparisons between positive
23092         // and negative zero incorrectly.
23093         if (!DAG.getTarget().Options.UnsafeFPMath &&
23094             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23095           break;
23096         Opcode = X86ISD::FMAX;
23097         break;
23098       case ISD::SETUGT:
23099         // Converting this to a max would handle NaNs incorrectly, and swapping
23100         // the operands would cause it to handle comparisons between positive
23101         // and negative zero incorrectly.
23102         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23103           if (!DAG.getTarget().Options.UnsafeFPMath &&
23104               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23105             break;
23106           std::swap(LHS, RHS);
23107         }
23108         Opcode = X86ISD::FMAX;
23109         break;
23110       case ISD::SETUGE:
23111         // Converting this to a max would handle both negative zeros and NaNs
23112         // incorrectly, but we can swap the operands to fix both.
23113         std::swap(LHS, RHS);
23114       case ISD::SETOGT:
23115       case ISD::SETGT:
23116       case ISD::SETGE:
23117         Opcode = X86ISD::FMAX;
23118         break;
23119       }
23120     // Check for x CC y ? y : x -- a min/max with reversed arms.
23121     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
23122                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
23123       switch (CC) {
23124       default: break;
23125       case ISD::SETOGE:
23126         // Converting this to a min would handle comparisons between positive
23127         // and negative zero incorrectly, and swapping the operands would
23128         // cause it to handle NaNs incorrectly.
23129         if (!DAG.getTarget().Options.UnsafeFPMath &&
23130             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
23131           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23132             break;
23133           std::swap(LHS, RHS);
23134         }
23135         Opcode = X86ISD::FMIN;
23136         break;
23137       case ISD::SETUGT:
23138         // Converting this to a min would handle NaNs incorrectly.
23139         if (!DAG.getTarget().Options.UnsafeFPMath &&
23140             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23141           break;
23142         Opcode = X86ISD::FMIN;
23143         break;
23144       case ISD::SETUGE:
23145         // Converting this to a min would handle both negative zeros and NaNs
23146         // incorrectly, but we can swap the operands to fix both.
23147         std::swap(LHS, RHS);
23148       case ISD::SETOGT:
23149       case ISD::SETGT:
23150       case ISD::SETGE:
23151         Opcode = X86ISD::FMIN;
23152         break;
23153
23154       case ISD::SETULT:
23155         // Converting this to a max would handle NaNs incorrectly.
23156         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23157           break;
23158         Opcode = X86ISD::FMAX;
23159         break;
23160       case ISD::SETOLE:
23161         // Converting this to a max would handle comparisons between positive
23162         // and negative zero incorrectly, and swapping the operands would
23163         // cause it to handle NaNs incorrectly.
23164         if (!DAG.getTarget().Options.UnsafeFPMath &&
23165             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23166           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23167             break;
23168           std::swap(LHS, RHS);
23169         }
23170         Opcode = X86ISD::FMAX;
23171         break;
23172       case ISD::SETULE:
23173         // Converting this to a max would handle both negative zeros and NaNs
23174         // incorrectly, but we can swap the operands to fix both.
23175         std::swap(LHS, RHS);
23176       case ISD::SETOLT:
23177       case ISD::SETLT:
23178       case ISD::SETLE:
23179         Opcode = X86ISD::FMAX;
23180         break;
23181       }
23182     }
23183
23184     if (Opcode)
23185       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23186   }
23187
23188   EVT CondVT = Cond.getValueType();
23189   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23190       CondVT.getVectorElementType() == MVT::i1) {
23191     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23192     // lowering on KNL. In this case we convert it to
23193     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23194     // The same situation for all 128 and 256-bit vectors of i8 and i16.
23195     // Since SKX these selects have a proper lowering.
23196     EVT OpVT = LHS.getValueType();
23197     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23198         (OpVT.getVectorElementType() == MVT::i8 ||
23199          OpVT.getVectorElementType() == MVT::i16) &&
23200         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23201       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23202       DCI.AddToWorklist(Cond.getNode());
23203       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23204     }
23205   }
23206   // If this is a select between two integer constants, try to do some
23207   // optimizations.
23208   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23209     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23210       // Don't do this for crazy integer types.
23211       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23212         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23213         // so that TrueC (the true value) is larger than FalseC.
23214         bool NeedsCondInvert = false;
23215
23216         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23217             // Efficiently invertible.
23218             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
23219              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
23220               isa<ConstantSDNode>(Cond.getOperand(1))))) {
23221           NeedsCondInvert = true;
23222           std::swap(TrueC, FalseC);
23223         }
23224
23225         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
23226         if (FalseC->getAPIntValue() == 0 &&
23227             TrueC->getAPIntValue().isPowerOf2()) {
23228           if (NeedsCondInvert) // Invert the condition if needed.
23229             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23230                                DAG.getConstant(1, DL, Cond.getValueType()));
23231
23232           // Zero extend the condition if needed.
23233           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23234
23235           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23236           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23237                              DAG.getConstant(ShAmt, DL, MVT::i8));
23238         }
23239
23240         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23241         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23242           if (NeedsCondInvert) // Invert the condition if needed.
23243             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23244                                DAG.getConstant(1, DL, Cond.getValueType()));
23245
23246           // Zero extend the condition if needed.
23247           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23248                              FalseC->getValueType(0), Cond);
23249           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23250                              SDValue(FalseC, 0));
23251         }
23252
23253         // Optimize cases that will turn into an LEA instruction.  This requires
23254         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23255         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23256           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23257           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23258
23259           bool isFastMultiplier = false;
23260           if (Diff < 10) {
23261             switch ((unsigned char)Diff) {
23262               default: break;
23263               case 1:  // result = add base, cond
23264               case 2:  // result = lea base(    , cond*2)
23265               case 3:  // result = lea base(cond, cond*2)
23266               case 4:  // result = lea base(    , cond*4)
23267               case 5:  // result = lea base(cond, cond*4)
23268               case 8:  // result = lea base(    , cond*8)
23269               case 9:  // result = lea base(cond, cond*8)
23270                 isFastMultiplier = true;
23271                 break;
23272             }
23273           }
23274
23275           if (isFastMultiplier) {
23276             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23277             if (NeedsCondInvert) // Invert the condition if needed.
23278               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23279                                  DAG.getConstant(1, DL, Cond.getValueType()));
23280
23281             // Zero extend the condition if needed.
23282             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23283                                Cond);
23284             // Scale the condition by the difference.
23285             if (Diff != 1)
23286               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23287                                  DAG.getConstant(Diff, DL,
23288                                                  Cond.getValueType()));
23289
23290             // Add the base if non-zero.
23291             if (FalseC->getAPIntValue() != 0)
23292               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23293                                  SDValue(FalseC, 0));
23294             return Cond;
23295           }
23296         }
23297       }
23298   }
23299
23300   // Canonicalize max and min:
23301   // (x > y) ? x : y -> (x >= y) ? x : y
23302   // (x < y) ? x : y -> (x <= y) ? x : y
23303   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23304   // the need for an extra compare
23305   // against zero. e.g.
23306   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23307   // subl   %esi, %edi
23308   // testl  %edi, %edi
23309   // movl   $0, %eax
23310   // cmovgl %edi, %eax
23311   // =>
23312   // xorl   %eax, %eax
23313   // subl   %esi, $edi
23314   // cmovsl %eax, %edi
23315   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23316       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23317       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23318     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23319     switch (CC) {
23320     default: break;
23321     case ISD::SETLT:
23322     case ISD::SETGT: {
23323       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23324       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23325                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23326       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23327     }
23328     }
23329   }
23330
23331   // Early exit check
23332   if (!TLI.isTypeLegal(VT))
23333     return SDValue();
23334
23335   // Match VSELECTs into subs with unsigned saturation.
23336   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23337       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23338       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23339        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23340     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23341
23342     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23343     // left side invert the predicate to simplify logic below.
23344     SDValue Other;
23345     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23346       Other = RHS;
23347       CC = ISD::getSetCCInverse(CC, true);
23348     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23349       Other = LHS;
23350     }
23351
23352     if (Other.getNode() && Other->getNumOperands() == 2 &&
23353         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23354       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23355       SDValue CondRHS = Cond->getOperand(1);
23356
23357       // Look for a general sub with unsigned saturation first.
23358       // x >= y ? x-y : 0 --> subus x, y
23359       // x >  y ? x-y : 0 --> subus x, y
23360       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23361           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23362         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23363
23364       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23365         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23366           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23367             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23368               // If the RHS is a constant we have to reverse the const
23369               // canonicalization.
23370               // x > C-1 ? x+-C : 0 --> subus x, C
23371               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23372                   CondRHSConst->getAPIntValue() ==
23373                       (-OpRHSConst->getAPIntValue() - 1))
23374                 return DAG.getNode(
23375                     X86ISD::SUBUS, DL, VT, OpLHS,
23376                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
23377
23378           // Another special case: If C was a sign bit, the sub has been
23379           // canonicalized into a xor.
23380           // FIXME: Would it be better to use computeKnownBits to determine
23381           //        whether it's safe to decanonicalize the xor?
23382           // x s< 0 ? x^C : 0 --> subus x, C
23383           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23384               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23385               OpRHSConst->getAPIntValue().isSignBit())
23386             // Note that we have to rebuild the RHS constant here to ensure we
23387             // don't rely on particular values of undef lanes.
23388             return DAG.getNode(
23389                 X86ISD::SUBUS, DL, VT, OpLHS,
23390                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
23391         }
23392     }
23393   }
23394
23395   // Simplify vector selection if condition value type matches vselect
23396   // operand type
23397   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23398     assert(Cond.getValueType().isVector() &&
23399            "vector select expects a vector selector!");
23400
23401     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23402     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23403
23404     // Try invert the condition if true value is not all 1s and false value
23405     // is not all 0s.
23406     if (!TValIsAllOnes && !FValIsAllZeros &&
23407         // Check if the selector will be produced by CMPP*/PCMP*
23408         Cond.getOpcode() == ISD::SETCC &&
23409         // Check if SETCC has already been promoted
23410         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23411             CondVT) {
23412       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23413       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23414
23415       if (TValIsAllZeros || FValIsAllOnes) {
23416         SDValue CC = Cond.getOperand(2);
23417         ISD::CondCode NewCC =
23418           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23419                                Cond.getOperand(0).getValueType().isInteger());
23420         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23421         std::swap(LHS, RHS);
23422         TValIsAllOnes = FValIsAllOnes;
23423         FValIsAllZeros = TValIsAllZeros;
23424       }
23425     }
23426
23427     if (TValIsAllOnes || FValIsAllZeros) {
23428       SDValue Ret;
23429
23430       if (TValIsAllOnes && FValIsAllZeros)
23431         Ret = Cond;
23432       else if (TValIsAllOnes)
23433         Ret =
23434             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23435       else if (FValIsAllZeros)
23436         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23437                           DAG.getBitcast(CondVT, LHS));
23438
23439       return DAG.getBitcast(VT, Ret);
23440     }
23441   }
23442
23443   // We should generate an X86ISD::BLENDI from a vselect if its argument
23444   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23445   // constants. This specific pattern gets generated when we split a
23446   // selector for a 512 bit vector in a machine without AVX512 (but with
23447   // 256-bit vectors), during legalization:
23448   //
23449   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23450   //
23451   // Iff we find this pattern and the build_vectors are built from
23452   // constants, we translate the vselect into a shuffle_vector that we
23453   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23454   if ((N->getOpcode() == ISD::VSELECT ||
23455        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23456       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23457     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23458     if (Shuffle.getNode())
23459       return Shuffle;
23460   }
23461
23462   // If this is a *dynamic* select (non-constant condition) and we can match
23463   // this node with one of the variable blend instructions, restructure the
23464   // condition so that the blends can use the high bit of each element and use
23465   // SimplifyDemandedBits to simplify the condition operand.
23466   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23467       !DCI.isBeforeLegalize() &&
23468       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23469     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23470
23471     // Don't optimize vector selects that map to mask-registers.
23472     if (BitWidth == 1)
23473       return SDValue();
23474
23475     // We can only handle the cases where VSELECT is directly legal on the
23476     // subtarget. We custom lower VSELECT nodes with constant conditions and
23477     // this makes it hard to see whether a dynamic VSELECT will correctly
23478     // lower, so we both check the operation's status and explicitly handle the
23479     // cases where a *dynamic* blend will fail even though a constant-condition
23480     // blend could be custom lowered.
23481     // FIXME: We should find a better way to handle this class of problems.
23482     // Potentially, we should combine constant-condition vselect nodes
23483     // pre-legalization into shuffles and not mark as many types as custom
23484     // lowered.
23485     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23486       return SDValue();
23487     // FIXME: We don't support i16-element blends currently. We could and
23488     // should support them by making *all* the bits in the condition be set
23489     // rather than just the high bit and using an i8-element blend.
23490     if (VT.getScalarType() == MVT::i16)
23491       return SDValue();
23492     // Dynamic blending was only available from SSE4.1 onward.
23493     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23494       return SDValue();
23495     // Byte blends are only available in AVX2
23496     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23497         !Subtarget->hasAVX2())
23498       return SDValue();
23499
23500     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23501     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23502
23503     APInt KnownZero, KnownOne;
23504     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23505                                           DCI.isBeforeLegalizeOps());
23506     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23507         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23508                                  TLO)) {
23509       // If we changed the computation somewhere in the DAG, this change
23510       // will affect all users of Cond.
23511       // Make sure it is fine and update all the nodes so that we do not
23512       // use the generic VSELECT anymore. Otherwise, we may perform
23513       // wrong optimizations as we messed up with the actual expectation
23514       // for the vector boolean values.
23515       if (Cond != TLO.Old) {
23516         // Check all uses of that condition operand to check whether it will be
23517         // consumed by non-BLEND instructions, which may depend on all bits are
23518         // set properly.
23519         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23520              I != E; ++I)
23521           if (I->getOpcode() != ISD::VSELECT)
23522             // TODO: Add other opcodes eventually lowered into BLEND.
23523             return SDValue();
23524
23525         // Update all the users of the condition, before committing the change,
23526         // so that the VSELECT optimizations that expect the correct vector
23527         // boolean value will not be triggered.
23528         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23529              I != E; ++I)
23530           DAG.ReplaceAllUsesOfValueWith(
23531               SDValue(*I, 0),
23532               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23533                           Cond, I->getOperand(1), I->getOperand(2)));
23534         DCI.CommitTargetLoweringOpt(TLO);
23535         return SDValue();
23536       }
23537       // At this point, only Cond is changed. Change the condition
23538       // just for N to keep the opportunity to optimize all other
23539       // users their own way.
23540       DAG.ReplaceAllUsesOfValueWith(
23541           SDValue(N, 0),
23542           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23543                       TLO.New, N->getOperand(1), N->getOperand(2)));
23544       return SDValue();
23545     }
23546   }
23547
23548   return SDValue();
23549 }
23550
23551 // Check whether a boolean test is testing a boolean value generated by
23552 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23553 // code.
23554 //
23555 // Simplify the following patterns:
23556 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23557 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23558 // to (Op EFLAGS Cond)
23559 //
23560 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23561 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23562 // to (Op EFLAGS !Cond)
23563 //
23564 // where Op could be BRCOND or CMOV.
23565 //
23566 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23567   // Quit if not CMP and SUB with its value result used.
23568   if (Cmp.getOpcode() != X86ISD::CMP &&
23569       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23570       return SDValue();
23571
23572   // Quit if not used as a boolean value.
23573   if (CC != X86::COND_E && CC != X86::COND_NE)
23574     return SDValue();
23575
23576   // Check CMP operands. One of them should be 0 or 1 and the other should be
23577   // an SetCC or extended from it.
23578   SDValue Op1 = Cmp.getOperand(0);
23579   SDValue Op2 = Cmp.getOperand(1);
23580
23581   SDValue SetCC;
23582   const ConstantSDNode* C = nullptr;
23583   bool needOppositeCond = (CC == X86::COND_E);
23584   bool checkAgainstTrue = false; // Is it a comparison against 1?
23585
23586   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23587     SetCC = Op2;
23588   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23589     SetCC = Op1;
23590   else // Quit if all operands are not constants.
23591     return SDValue();
23592
23593   if (C->getZExtValue() == 1) {
23594     needOppositeCond = !needOppositeCond;
23595     checkAgainstTrue = true;
23596   } else if (C->getZExtValue() != 0)
23597     // Quit if the constant is neither 0 or 1.
23598     return SDValue();
23599
23600   bool truncatedToBoolWithAnd = false;
23601   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23602   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23603          SetCC.getOpcode() == ISD::TRUNCATE ||
23604          SetCC.getOpcode() == ISD::AND) {
23605     if (SetCC.getOpcode() == ISD::AND) {
23606       int OpIdx = -1;
23607       ConstantSDNode *CS;
23608       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23609           CS->getZExtValue() == 1)
23610         OpIdx = 1;
23611       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23612           CS->getZExtValue() == 1)
23613         OpIdx = 0;
23614       if (OpIdx == -1)
23615         break;
23616       SetCC = SetCC.getOperand(OpIdx);
23617       truncatedToBoolWithAnd = true;
23618     } else
23619       SetCC = SetCC.getOperand(0);
23620   }
23621
23622   switch (SetCC.getOpcode()) {
23623   case X86ISD::SETCC_CARRY:
23624     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23625     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23626     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23627     // truncated to i1 using 'and'.
23628     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23629       break;
23630     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23631            "Invalid use of SETCC_CARRY!");
23632     // FALL THROUGH
23633   case X86ISD::SETCC:
23634     // Set the condition code or opposite one if necessary.
23635     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23636     if (needOppositeCond)
23637       CC = X86::GetOppositeBranchCondition(CC);
23638     return SetCC.getOperand(1);
23639   case X86ISD::CMOV: {
23640     // Check whether false/true value has canonical one, i.e. 0 or 1.
23641     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23642     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23643     // Quit if true value is not a constant.
23644     if (!TVal)
23645       return SDValue();
23646     // Quit if false value is not a constant.
23647     if (!FVal) {
23648       SDValue Op = SetCC.getOperand(0);
23649       // Skip 'zext' or 'trunc' node.
23650       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23651           Op.getOpcode() == ISD::TRUNCATE)
23652         Op = Op.getOperand(0);
23653       // A special case for rdrand/rdseed, where 0 is set if false cond is
23654       // found.
23655       if ((Op.getOpcode() != X86ISD::RDRAND &&
23656            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23657         return SDValue();
23658     }
23659     // Quit if false value is not the constant 0 or 1.
23660     bool FValIsFalse = true;
23661     if (FVal && FVal->getZExtValue() != 0) {
23662       if (FVal->getZExtValue() != 1)
23663         return SDValue();
23664       // If FVal is 1, opposite cond is needed.
23665       needOppositeCond = !needOppositeCond;
23666       FValIsFalse = false;
23667     }
23668     // Quit if TVal is not the constant opposite of FVal.
23669     if (FValIsFalse && TVal->getZExtValue() != 1)
23670       return SDValue();
23671     if (!FValIsFalse && TVal->getZExtValue() != 0)
23672       return SDValue();
23673     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23674     if (needOppositeCond)
23675       CC = X86::GetOppositeBranchCondition(CC);
23676     return SetCC.getOperand(3);
23677   }
23678   }
23679
23680   return SDValue();
23681 }
23682
23683 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23684 /// Match:
23685 ///   (X86or (X86setcc) (X86setcc))
23686 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
23687 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23688                                            X86::CondCode &CC1, SDValue &Flags,
23689                                            bool &isAnd) {
23690   if (Cond->getOpcode() == X86ISD::CMP) {
23691     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23692     if (!CondOp1C || !CondOp1C->isNullValue())
23693       return false;
23694
23695     Cond = Cond->getOperand(0);
23696   }
23697
23698   isAnd = false;
23699
23700   SDValue SetCC0, SetCC1;
23701   switch (Cond->getOpcode()) {
23702   default: return false;
23703   case ISD::AND:
23704   case X86ISD::AND:
23705     isAnd = true;
23706     // fallthru
23707   case ISD::OR:
23708   case X86ISD::OR:
23709     SetCC0 = Cond->getOperand(0);
23710     SetCC1 = Cond->getOperand(1);
23711     break;
23712   };
23713
23714   // Make sure we have SETCC nodes, using the same flags value.
23715   if (SetCC0.getOpcode() != X86ISD::SETCC ||
23716       SetCC1.getOpcode() != X86ISD::SETCC ||
23717       SetCC0->getOperand(1) != SetCC1->getOperand(1))
23718     return false;
23719
23720   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23721   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23722   Flags = SetCC0->getOperand(1);
23723   return true;
23724 }
23725
23726 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23727 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23728                                   TargetLowering::DAGCombinerInfo &DCI,
23729                                   const X86Subtarget *Subtarget) {
23730   SDLoc DL(N);
23731
23732   // If the flag operand isn't dead, don't touch this CMOV.
23733   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23734     return SDValue();
23735
23736   SDValue FalseOp = N->getOperand(0);
23737   SDValue TrueOp = N->getOperand(1);
23738   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23739   SDValue Cond = N->getOperand(3);
23740
23741   if (CC == X86::COND_E || CC == X86::COND_NE) {
23742     switch (Cond.getOpcode()) {
23743     default: break;
23744     case X86ISD::BSR:
23745     case X86ISD::BSF:
23746       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23747       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23748         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23749     }
23750   }
23751
23752   SDValue Flags;
23753
23754   Flags = checkBoolTestSetCCCombine(Cond, CC);
23755   if (Flags.getNode() &&
23756       // Extra check as FCMOV only supports a subset of X86 cond.
23757       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23758     SDValue Ops[] = { FalseOp, TrueOp,
23759                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23760     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23761   }
23762
23763   // If this is a select between two integer constants, try to do some
23764   // optimizations.  Note that the operands are ordered the opposite of SELECT
23765   // operands.
23766   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23767     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23768       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23769       // larger than FalseC (the false value).
23770       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23771         CC = X86::GetOppositeBranchCondition(CC);
23772         std::swap(TrueC, FalseC);
23773         std::swap(TrueOp, FalseOp);
23774       }
23775
23776       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23777       // This is efficient for any integer data type (including i8/i16) and
23778       // shift amount.
23779       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23780         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23781                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23782
23783         // Zero extend the condition if needed.
23784         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23785
23786         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23787         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23788                            DAG.getConstant(ShAmt, DL, MVT::i8));
23789         if (N->getNumValues() == 2)  // Dead flag value?
23790           return DCI.CombineTo(N, Cond, SDValue());
23791         return Cond;
23792       }
23793
23794       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23795       // for any integer data type, including i8/i16.
23796       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23797         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23798                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23799
23800         // Zero extend the condition if needed.
23801         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23802                            FalseC->getValueType(0), Cond);
23803         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23804                            SDValue(FalseC, 0));
23805
23806         if (N->getNumValues() == 2)  // Dead flag value?
23807           return DCI.CombineTo(N, Cond, SDValue());
23808         return Cond;
23809       }
23810
23811       // Optimize cases that will turn into an LEA instruction.  This requires
23812       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23813       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23814         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23815         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23816
23817         bool isFastMultiplier = false;
23818         if (Diff < 10) {
23819           switch ((unsigned char)Diff) {
23820           default: break;
23821           case 1:  // result = add base, cond
23822           case 2:  // result = lea base(    , cond*2)
23823           case 3:  // result = lea base(cond, cond*2)
23824           case 4:  // result = lea base(    , cond*4)
23825           case 5:  // result = lea base(cond, cond*4)
23826           case 8:  // result = lea base(    , cond*8)
23827           case 9:  // result = lea base(cond, cond*8)
23828             isFastMultiplier = true;
23829             break;
23830           }
23831         }
23832
23833         if (isFastMultiplier) {
23834           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23835           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23836                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23837           // Zero extend the condition if needed.
23838           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23839                              Cond);
23840           // Scale the condition by the difference.
23841           if (Diff != 1)
23842             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23843                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23844
23845           // Add the base if non-zero.
23846           if (FalseC->getAPIntValue() != 0)
23847             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23848                                SDValue(FalseC, 0));
23849           if (N->getNumValues() == 2)  // Dead flag value?
23850             return DCI.CombineTo(N, Cond, SDValue());
23851           return Cond;
23852         }
23853       }
23854     }
23855   }
23856
23857   // Handle these cases:
23858   //   (select (x != c), e, c) -> select (x != c), e, x),
23859   //   (select (x == c), c, e) -> select (x == c), x, e)
23860   // where the c is an integer constant, and the "select" is the combination
23861   // of CMOV and CMP.
23862   //
23863   // The rationale for this change is that the conditional-move from a constant
23864   // needs two instructions, however, conditional-move from a register needs
23865   // only one instruction.
23866   //
23867   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23868   //  some instruction-combining opportunities. This opt needs to be
23869   //  postponed as late as possible.
23870   //
23871   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23872     // the DCI.xxxx conditions are provided to postpone the optimization as
23873     // late as possible.
23874
23875     ConstantSDNode *CmpAgainst = nullptr;
23876     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23877         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23878         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23879
23880       if (CC == X86::COND_NE &&
23881           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23882         CC = X86::GetOppositeBranchCondition(CC);
23883         std::swap(TrueOp, FalseOp);
23884       }
23885
23886       if (CC == X86::COND_E &&
23887           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23888         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23889                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23890         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23891       }
23892     }
23893   }
23894
23895   // Fold and/or of setcc's to double CMOV:
23896   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23897   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23898   //
23899   // This combine lets us generate:
23900   //   cmovcc1 (jcc1 if we don't have CMOV)
23901   //   cmovcc2 (same)
23902   // instead of:
23903   //   setcc1
23904   //   setcc2
23905   //   and/or
23906   //   cmovne (jne if we don't have CMOV)
23907   // When we can't use the CMOV instruction, it might increase branch
23908   // mispredicts.
23909   // When we can use CMOV, or when there is no mispredict, this improves
23910   // throughput and reduces register pressure.
23911   //
23912   if (CC == X86::COND_NE) {
23913     SDValue Flags;
23914     X86::CondCode CC0, CC1;
23915     bool isAndSetCC;
23916     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23917       if (isAndSetCC) {
23918         std::swap(FalseOp, TrueOp);
23919         CC0 = X86::GetOppositeBranchCondition(CC0);
23920         CC1 = X86::GetOppositeBranchCondition(CC1);
23921       }
23922
23923       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23924         Flags};
23925       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23926       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23927       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23928       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23929       return CMOV;
23930     }
23931   }
23932
23933   return SDValue();
23934 }
23935
23936 /// PerformMulCombine - Optimize a single multiply with constant into two
23937 /// in order to implement it with two cheaper instructions, e.g.
23938 /// LEA + SHL, LEA + LEA.
23939 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23940                                  TargetLowering::DAGCombinerInfo &DCI) {
23941   // An imul is usually smaller than the alternative sequence.
23942   if (DAG.getMachineFunction().getFunction()->optForMinSize())
23943     return SDValue();
23944
23945   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23946     return SDValue();
23947
23948   EVT VT = N->getValueType(0);
23949   if (VT != MVT::i64 && VT != MVT::i32)
23950     return SDValue();
23951
23952   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23953   if (!C)
23954     return SDValue();
23955   uint64_t MulAmt = C->getZExtValue();
23956   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23957     return SDValue();
23958
23959   uint64_t MulAmt1 = 0;
23960   uint64_t MulAmt2 = 0;
23961   if ((MulAmt % 9) == 0) {
23962     MulAmt1 = 9;
23963     MulAmt2 = MulAmt / 9;
23964   } else if ((MulAmt % 5) == 0) {
23965     MulAmt1 = 5;
23966     MulAmt2 = MulAmt / 5;
23967   } else if ((MulAmt % 3) == 0) {
23968     MulAmt1 = 3;
23969     MulAmt2 = MulAmt / 3;
23970   }
23971   if (MulAmt2 &&
23972       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23973     SDLoc DL(N);
23974
23975     if (isPowerOf2_64(MulAmt2) &&
23976         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23977       // If second multiplifer is pow2, issue it first. We want the multiply by
23978       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23979       // is an add.
23980       std::swap(MulAmt1, MulAmt2);
23981
23982     SDValue NewMul;
23983     if (isPowerOf2_64(MulAmt1))
23984       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23985                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23986     else
23987       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23988                            DAG.getConstant(MulAmt1, DL, VT));
23989
23990     if (isPowerOf2_64(MulAmt2))
23991       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23992                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23993     else
23994       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23995                            DAG.getConstant(MulAmt2, DL, VT));
23996
23997     // Do not add new nodes to DAG combiner worklist.
23998     DCI.CombineTo(N, NewMul, false);
23999   }
24000   return SDValue();
24001 }
24002
24003 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
24004   SDValue N0 = N->getOperand(0);
24005   SDValue N1 = N->getOperand(1);
24006   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
24007   EVT VT = N0.getValueType();
24008
24009   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
24010   // since the result of setcc_c is all zero's or all ones.
24011   if (VT.isInteger() && !VT.isVector() &&
24012       N1C && N0.getOpcode() == ISD::AND &&
24013       N0.getOperand(1).getOpcode() == ISD::Constant) {
24014     SDValue N00 = N0.getOperand(0);
24015     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
24016     APInt ShAmt = N1C->getAPIntValue();
24017     Mask = Mask.shl(ShAmt);
24018     bool MaskOK = false;
24019     // We can handle cases concerning bit-widening nodes containing setcc_c if
24020     // we carefully interrogate the mask to make sure we are semantics
24021     // preserving.
24022     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
24023     // of the underlying setcc_c operation if the setcc_c was zero extended.
24024     // Consider the following example:
24025     //   zext(setcc_c)                 -> i32 0x0000FFFF
24026     //   c1                            -> i32 0x0000FFFF
24027     //   c2                            -> i32 0x00000001
24028     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
24029     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
24030     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24031       MaskOK = true;
24032     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
24033                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24034       MaskOK = true;
24035     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
24036                 N00.getOpcode() == ISD::ANY_EXTEND) &&
24037                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24038       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
24039     }
24040     if (MaskOK && Mask != 0) {
24041       SDLoc DL(N);
24042       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
24043     }
24044   }
24045
24046   // Hardware support for vector shifts is sparse which makes us scalarize the
24047   // vector operations in many cases. Also, on sandybridge ADD is faster than
24048   // shl.
24049   // (shl V, 1) -> add V,V
24050   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
24051     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
24052       assert(N0.getValueType().isVector() && "Invalid vector shift type");
24053       // We shift all of the values by one. In many cases we do not have
24054       // hardware support for this operation. This is better expressed as an ADD
24055       // of two values.
24056       if (N1SplatC->getAPIntValue() == 1)
24057         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
24058     }
24059
24060   return SDValue();
24061 }
24062
24063 /// \brief Returns a vector of 0s if the node in input is a vector logical
24064 /// shift by a constant amount which is known to be bigger than or equal
24065 /// to the vector element size in bits.
24066 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
24067                                       const X86Subtarget *Subtarget) {
24068   EVT VT = N->getValueType(0);
24069
24070   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
24071       (!Subtarget->hasInt256() ||
24072        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
24073     return SDValue();
24074
24075   SDValue Amt = N->getOperand(1);
24076   SDLoc DL(N);
24077   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
24078     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
24079       APInt ShiftAmt = AmtSplat->getAPIntValue();
24080       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
24081
24082       // SSE2/AVX2 logical shifts always return a vector of 0s
24083       // if the shift amount is bigger than or equal to
24084       // the element size. The constant shift amount will be
24085       // encoded as a 8-bit immediate.
24086       if (ShiftAmt.trunc(8).uge(MaxAmount))
24087         return getZeroVector(VT, Subtarget, DAG, DL);
24088     }
24089
24090   return SDValue();
24091 }
24092
24093 /// PerformShiftCombine - Combine shifts.
24094 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
24095                                    TargetLowering::DAGCombinerInfo &DCI,
24096                                    const X86Subtarget *Subtarget) {
24097   if (N->getOpcode() == ISD::SHL)
24098     if (SDValue V = PerformSHLCombine(N, DAG))
24099       return V;
24100
24101   // Try to fold this logical shift into a zero vector.
24102   if (N->getOpcode() != ISD::SRA)
24103     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
24104       return V;
24105
24106   return SDValue();
24107 }
24108
24109 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
24110 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
24111 // and friends.  Likewise for OR -> CMPNEQSS.
24112 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
24113                             TargetLowering::DAGCombinerInfo &DCI,
24114                             const X86Subtarget *Subtarget) {
24115   unsigned opcode;
24116
24117   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
24118   // we're requiring SSE2 for both.
24119   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
24120     SDValue N0 = N->getOperand(0);
24121     SDValue N1 = N->getOperand(1);
24122     SDValue CMP0 = N0->getOperand(1);
24123     SDValue CMP1 = N1->getOperand(1);
24124     SDLoc DL(N);
24125
24126     // The SETCCs should both refer to the same CMP.
24127     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
24128       return SDValue();
24129
24130     SDValue CMP00 = CMP0->getOperand(0);
24131     SDValue CMP01 = CMP0->getOperand(1);
24132     EVT     VT    = CMP00.getValueType();
24133
24134     if (VT == MVT::f32 || VT == MVT::f64) {
24135       bool ExpectingFlags = false;
24136       // Check for any users that want flags:
24137       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
24138            !ExpectingFlags && UI != UE; ++UI)
24139         switch (UI->getOpcode()) {
24140         default:
24141         case ISD::BR_CC:
24142         case ISD::BRCOND:
24143         case ISD::SELECT:
24144           ExpectingFlags = true;
24145           break;
24146         case ISD::CopyToReg:
24147         case ISD::SIGN_EXTEND:
24148         case ISD::ZERO_EXTEND:
24149         case ISD::ANY_EXTEND:
24150           break;
24151         }
24152
24153       if (!ExpectingFlags) {
24154         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24155         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24156
24157         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24158           X86::CondCode tmp = cc0;
24159           cc0 = cc1;
24160           cc1 = tmp;
24161         }
24162
24163         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
24164             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24165           // FIXME: need symbolic constants for these magic numbers.
24166           // See X86ATTInstPrinter.cpp:printSSECC().
24167           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24168           if (Subtarget->hasAVX512()) {
24169             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24170                                          CMP01,
24171                                          DAG.getConstant(x86cc, DL, MVT::i8));
24172             if (N->getValueType(0) != MVT::i1)
24173               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24174                                  FSetCC);
24175             return FSetCC;
24176           }
24177           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24178                                               CMP00.getValueType(), CMP00, CMP01,
24179                                               DAG.getConstant(x86cc, DL,
24180                                                               MVT::i8));
24181
24182           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24183           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24184
24185           if (is64BitFP && !Subtarget->is64Bit()) {
24186             // On a 32-bit target, we cannot bitcast the 64-bit float to a
24187             // 64-bit integer, since that's not a legal type. Since
24188             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24189             // bits, but can do this little dance to extract the lowest 32 bits
24190             // and work with those going forward.
24191             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24192                                            OnesOrZeroesF);
24193             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
24194             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24195                                         Vector32, DAG.getIntPtrConstant(0, DL));
24196             IntVT = MVT::i32;
24197           }
24198
24199           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
24200           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24201                                       DAG.getConstant(1, DL, IntVT));
24202           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
24203                                               ANDed);
24204           return OneBitOfTruth;
24205         }
24206       }
24207     }
24208   }
24209   return SDValue();
24210 }
24211
24212 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24213 /// so it can be folded inside ANDNP.
24214 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24215   EVT VT = N->getValueType(0);
24216
24217   // Match direct AllOnes for 128 and 256-bit vectors
24218   if (ISD::isBuildVectorAllOnes(N))
24219     return true;
24220
24221   // Look through a bit convert.
24222   if (N->getOpcode() == ISD::BITCAST)
24223     N = N->getOperand(0).getNode();
24224
24225   // Sometimes the operand may come from a insert_subvector building a 256-bit
24226   // allones vector
24227   if (VT.is256BitVector() &&
24228       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24229     SDValue V1 = N->getOperand(0);
24230     SDValue V2 = N->getOperand(1);
24231
24232     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24233         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24234         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24235         ISD::isBuildVectorAllOnes(V2.getNode()))
24236       return true;
24237   }
24238
24239   return false;
24240 }
24241
24242 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24243 // register. In most cases we actually compare or select YMM-sized registers
24244 // and mixing the two types creates horrible code. This method optimizes
24245 // some of the transition sequences.
24246 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24247                                  TargetLowering::DAGCombinerInfo &DCI,
24248                                  const X86Subtarget *Subtarget) {
24249   EVT VT = N->getValueType(0);
24250   if (!VT.is256BitVector())
24251     return SDValue();
24252
24253   assert((N->getOpcode() == ISD::ANY_EXTEND ||
24254           N->getOpcode() == ISD::ZERO_EXTEND ||
24255           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24256
24257   SDValue Narrow = N->getOperand(0);
24258   EVT NarrowVT = Narrow->getValueType(0);
24259   if (!NarrowVT.is128BitVector())
24260     return SDValue();
24261
24262   if (Narrow->getOpcode() != ISD::XOR &&
24263       Narrow->getOpcode() != ISD::AND &&
24264       Narrow->getOpcode() != ISD::OR)
24265     return SDValue();
24266
24267   SDValue N0  = Narrow->getOperand(0);
24268   SDValue N1  = Narrow->getOperand(1);
24269   SDLoc DL(Narrow);
24270
24271   // The Left side has to be a trunc.
24272   if (N0.getOpcode() != ISD::TRUNCATE)
24273     return SDValue();
24274
24275   // The type of the truncated inputs.
24276   EVT WideVT = N0->getOperand(0)->getValueType(0);
24277   if (WideVT != VT)
24278     return SDValue();
24279
24280   // The right side has to be a 'trunc' or a constant vector.
24281   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24282   ConstantSDNode *RHSConstSplat = nullptr;
24283   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24284     RHSConstSplat = RHSBV->getConstantSplatNode();
24285   if (!RHSTrunc && !RHSConstSplat)
24286     return SDValue();
24287
24288   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24289
24290   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24291     return SDValue();
24292
24293   // Set N0 and N1 to hold the inputs to the new wide operation.
24294   N0 = N0->getOperand(0);
24295   if (RHSConstSplat) {
24296     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24297                      SDValue(RHSConstSplat, 0));
24298     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24299     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24300   } else if (RHSTrunc) {
24301     N1 = N1->getOperand(0);
24302   }
24303
24304   // Generate the wide operation.
24305   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24306   unsigned Opcode = N->getOpcode();
24307   switch (Opcode) {
24308   case ISD::ANY_EXTEND:
24309     return Op;
24310   case ISD::ZERO_EXTEND: {
24311     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24312     APInt Mask = APInt::getAllOnesValue(InBits);
24313     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24314     return DAG.getNode(ISD::AND, DL, VT,
24315                        Op, DAG.getConstant(Mask, DL, VT));
24316   }
24317   case ISD::SIGN_EXTEND:
24318     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24319                        Op, DAG.getValueType(NarrowVT));
24320   default:
24321     llvm_unreachable("Unexpected opcode");
24322   }
24323 }
24324
24325 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
24326                                  TargetLowering::DAGCombinerInfo &DCI,
24327                                  const X86Subtarget *Subtarget) {
24328   SDValue N0 = N->getOperand(0);
24329   SDValue N1 = N->getOperand(1);
24330   SDLoc DL(N);
24331
24332   // A vector zext_in_reg may be represented as a shuffle,
24333   // feeding into a bitcast (this represents anyext) feeding into
24334   // an and with a mask.
24335   // We'd like to try to combine that into a shuffle with zero
24336   // plus a bitcast, removing the and.
24337   if (N0.getOpcode() != ISD::BITCAST ||
24338       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
24339     return SDValue();
24340
24341   // The other side of the AND should be a splat of 2^C, where C
24342   // is the number of bits in the source type.
24343   if (N1.getOpcode() == ISD::BITCAST)
24344     N1 = N1.getOperand(0);
24345   if (N1.getOpcode() != ISD::BUILD_VECTOR)
24346     return SDValue();
24347   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
24348
24349   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
24350   EVT SrcType = Shuffle->getValueType(0);
24351
24352   // We expect a single-source shuffle
24353   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
24354     return SDValue();
24355
24356   unsigned SrcSize = SrcType.getScalarSizeInBits();
24357
24358   APInt SplatValue, SplatUndef;
24359   unsigned SplatBitSize;
24360   bool HasAnyUndefs;
24361   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
24362                                 SplatBitSize, HasAnyUndefs))
24363     return SDValue();
24364
24365   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
24366   // Make sure the splat matches the mask we expect
24367   if (SplatBitSize > ResSize ||
24368       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
24369     return SDValue();
24370
24371   // Make sure the input and output size make sense
24372   if (SrcSize >= ResSize || ResSize % SrcSize)
24373     return SDValue();
24374
24375   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
24376   // The number of u's between each two values depends on the ratio between
24377   // the source and dest type.
24378   unsigned ZextRatio = ResSize / SrcSize;
24379   bool IsZext = true;
24380   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
24381     if (i % ZextRatio) {
24382       if (Shuffle->getMaskElt(i) > 0) {
24383         // Expected undef
24384         IsZext = false;
24385         break;
24386       }
24387     } else {
24388       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
24389         // Expected element number
24390         IsZext = false;
24391         break;
24392       }
24393     }
24394   }
24395
24396   if (!IsZext)
24397     return SDValue();
24398
24399   // Ok, perform the transformation - replace the shuffle with
24400   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24401   // (instead of undef) where the k elements come from the zero vector.
24402   SmallVector<int, 8> Mask;
24403   unsigned NumElems = SrcType.getVectorNumElements();
24404   for (unsigned i = 0; i < NumElems; ++i)
24405     if (i % ZextRatio)
24406       Mask.push_back(NumElems);
24407     else
24408       Mask.push_back(i / ZextRatio);
24409
24410   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24411     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24412   return DAG.getBitcast(N0.getValueType(), NewShuffle);
24413 }
24414
24415 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24416                                  TargetLowering::DAGCombinerInfo &DCI,
24417                                  const X86Subtarget *Subtarget) {
24418   if (DCI.isBeforeLegalizeOps())
24419     return SDValue();
24420
24421   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24422     return Zext;
24423
24424   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24425     return R;
24426
24427   EVT VT = N->getValueType(0);
24428   SDValue N0 = N->getOperand(0);
24429   SDValue N1 = N->getOperand(1);
24430   SDLoc DL(N);
24431
24432   // Create BEXTR instructions
24433   // BEXTR is ((X >> imm) & (2**size-1))
24434   if (VT == MVT::i32 || VT == MVT::i64) {
24435     // Check for BEXTR.
24436     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24437         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24438       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24439       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24440       if (MaskNode && ShiftNode) {
24441         uint64_t Mask = MaskNode->getZExtValue();
24442         uint64_t Shift = ShiftNode->getZExtValue();
24443         if (isMask_64(Mask)) {
24444           uint64_t MaskSize = countPopulation(Mask);
24445           if (Shift + MaskSize <= VT.getSizeInBits())
24446             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24447                                DAG.getConstant(Shift | (MaskSize << 8), DL,
24448                                                VT));
24449         }
24450       }
24451     } // BEXTR
24452
24453     return SDValue();
24454   }
24455
24456   // Want to form ANDNP nodes:
24457   // 1) In the hopes of then easily combining them with OR and AND nodes
24458   //    to form PBLEND/PSIGN.
24459   // 2) To match ANDN packed intrinsics
24460   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24461     return SDValue();
24462
24463   // Check LHS for vnot
24464   if (N0.getOpcode() == ISD::XOR &&
24465       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24466       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24467     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24468
24469   // Check RHS for vnot
24470   if (N1.getOpcode() == ISD::XOR &&
24471       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24472       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24473     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24474
24475   return SDValue();
24476 }
24477
24478 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24479                                 TargetLowering::DAGCombinerInfo &DCI,
24480                                 const X86Subtarget *Subtarget) {
24481   if (DCI.isBeforeLegalizeOps())
24482     return SDValue();
24483
24484   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24485     return R;
24486
24487   SDValue N0 = N->getOperand(0);
24488   SDValue N1 = N->getOperand(1);
24489   EVT VT = N->getValueType(0);
24490
24491   // look for psign/blend
24492   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24493     if (!Subtarget->hasSSSE3() ||
24494         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24495       return SDValue();
24496
24497     // Canonicalize pandn to RHS
24498     if (N0.getOpcode() == X86ISD::ANDNP)
24499       std::swap(N0, N1);
24500     // or (and (m, y), (pandn m, x))
24501     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24502       SDValue Mask = N1.getOperand(0);
24503       SDValue X    = N1.getOperand(1);
24504       SDValue Y;
24505       if (N0.getOperand(0) == Mask)
24506         Y = N0.getOperand(1);
24507       if (N0.getOperand(1) == Mask)
24508         Y = N0.getOperand(0);
24509
24510       // Check to see if the mask appeared in both the AND and ANDNP and
24511       if (!Y.getNode())
24512         return SDValue();
24513
24514       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24515       // Look through mask bitcast.
24516       if (Mask.getOpcode() == ISD::BITCAST)
24517         Mask = Mask.getOperand(0);
24518       if (X.getOpcode() == ISD::BITCAST)
24519         X = X.getOperand(0);
24520       if (Y.getOpcode() == ISD::BITCAST)
24521         Y = Y.getOperand(0);
24522
24523       EVT MaskVT = Mask.getValueType();
24524
24525       // Validate that the Mask operand is a vector sra node.
24526       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24527       // there is no psrai.b
24528       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24529       unsigned SraAmt = ~0;
24530       if (Mask.getOpcode() == ISD::SRA) {
24531         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24532           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24533             SraAmt = AmtConst->getZExtValue();
24534       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24535         SDValue SraC = Mask.getOperand(1);
24536         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24537       }
24538       if ((SraAmt + 1) != EltBits)
24539         return SDValue();
24540
24541       SDLoc DL(N);
24542
24543       // Now we know we at least have a plendvb with the mask val.  See if
24544       // we can form a psignb/w/d.
24545       // psign = x.type == y.type == mask.type && y = sub(0, x);
24546       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24547           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24548           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24549         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24550                "Unsupported VT for PSIGN");
24551         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24552         return DAG.getBitcast(VT, Mask);
24553       }
24554       // PBLENDVB only available on SSE 4.1
24555       if (!Subtarget->hasSSE41())
24556         return SDValue();
24557
24558       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24559
24560       X = DAG.getBitcast(BlendVT, X);
24561       Y = DAG.getBitcast(BlendVT, Y);
24562       Mask = DAG.getBitcast(BlendVT, Mask);
24563       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24564       return DAG.getBitcast(VT, Mask);
24565     }
24566   }
24567
24568   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24569     return SDValue();
24570
24571   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24572   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24573
24574   // SHLD/SHRD instructions have lower register pressure, but on some
24575   // platforms they have higher latency than the equivalent
24576   // series of shifts/or that would otherwise be generated.
24577   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24578   // have higher latencies and we are not optimizing for size.
24579   if (!OptForSize && Subtarget->isSHLDSlow())
24580     return SDValue();
24581
24582   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24583     std::swap(N0, N1);
24584   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24585     return SDValue();
24586   if (!N0.hasOneUse() || !N1.hasOneUse())
24587     return SDValue();
24588
24589   SDValue ShAmt0 = N0.getOperand(1);
24590   if (ShAmt0.getValueType() != MVT::i8)
24591     return SDValue();
24592   SDValue ShAmt1 = N1.getOperand(1);
24593   if (ShAmt1.getValueType() != MVT::i8)
24594     return SDValue();
24595   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24596     ShAmt0 = ShAmt0.getOperand(0);
24597   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24598     ShAmt1 = ShAmt1.getOperand(0);
24599
24600   SDLoc DL(N);
24601   unsigned Opc = X86ISD::SHLD;
24602   SDValue Op0 = N0.getOperand(0);
24603   SDValue Op1 = N1.getOperand(0);
24604   if (ShAmt0.getOpcode() == ISD::SUB) {
24605     Opc = X86ISD::SHRD;
24606     std::swap(Op0, Op1);
24607     std::swap(ShAmt0, ShAmt1);
24608   }
24609
24610   unsigned Bits = VT.getSizeInBits();
24611   if (ShAmt1.getOpcode() == ISD::SUB) {
24612     SDValue Sum = ShAmt1.getOperand(0);
24613     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24614       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24615       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24616         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24617       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24618         return DAG.getNode(Opc, DL, VT,
24619                            Op0, Op1,
24620                            DAG.getNode(ISD::TRUNCATE, DL,
24621                                        MVT::i8, ShAmt0));
24622     }
24623   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24624     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24625     if (ShAmt0C &&
24626         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24627       return DAG.getNode(Opc, DL, VT,
24628                          N0.getOperand(0), N1.getOperand(0),
24629                          DAG.getNode(ISD::TRUNCATE, DL,
24630                                        MVT::i8, ShAmt0));
24631   }
24632
24633   return SDValue();
24634 }
24635
24636 // Generate NEG and CMOV for integer abs.
24637 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24638   EVT VT = N->getValueType(0);
24639
24640   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24641   // 8-bit integer abs to NEG and CMOV.
24642   if (VT.isInteger() && VT.getSizeInBits() == 8)
24643     return SDValue();
24644
24645   SDValue N0 = N->getOperand(0);
24646   SDValue N1 = N->getOperand(1);
24647   SDLoc DL(N);
24648
24649   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24650   // and change it to SUB and CMOV.
24651   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24652       N0.getOpcode() == ISD::ADD &&
24653       N0.getOperand(1) == N1 &&
24654       N1.getOpcode() == ISD::SRA &&
24655       N1.getOperand(0) == N0.getOperand(0))
24656     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24657       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24658         // Generate SUB & CMOV.
24659         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24660                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24661
24662         SDValue Ops[] = { N0.getOperand(0), Neg,
24663                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24664                           SDValue(Neg.getNode(), 1) };
24665         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24666       }
24667   return SDValue();
24668 }
24669
24670 // Try to turn tests against the signbit in the form of:
24671 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24672 // into:
24673 //   SETGT(X, -1)
24674 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24675   // This is only worth doing if the output type is i8.
24676   if (N->getValueType(0) != MVT::i8)
24677     return SDValue();
24678
24679   SDValue N0 = N->getOperand(0);
24680   SDValue N1 = N->getOperand(1);
24681
24682   // We should be performing an xor against a truncated shift.
24683   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24684     return SDValue();
24685
24686   // Make sure we are performing an xor against one.
24687   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24688     return SDValue();
24689
24690   // SetCC on x86 zero extends so only act on this if it's a logical shift.
24691   SDValue Shift = N0.getOperand(0);
24692   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24693     return SDValue();
24694
24695   // Make sure we are truncating from one of i16, i32 or i64.
24696   EVT ShiftTy = Shift.getValueType();
24697   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24698     return SDValue();
24699
24700   // Make sure the shift amount extracts the sign bit.
24701   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24702       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24703     return SDValue();
24704
24705   // Create a greater-than comparison against -1.
24706   // N.B. Using SETGE against 0 works but we want a canonical looking
24707   // comparison, using SETGT matches up with what TranslateX86CC.
24708   SDLoc DL(N);
24709   SDValue ShiftOp = Shift.getOperand(0);
24710   EVT ShiftOpTy = ShiftOp.getValueType();
24711   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24712                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24713   return Cond;
24714 }
24715
24716 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24717                                  TargetLowering::DAGCombinerInfo &DCI,
24718                                  const X86Subtarget *Subtarget) {
24719   if (DCI.isBeforeLegalizeOps())
24720     return SDValue();
24721
24722   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24723     return RV;
24724
24725   if (Subtarget->hasCMov())
24726     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24727       return RV;
24728
24729   return SDValue();
24730 }
24731
24732 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24733 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24734                                   TargetLowering::DAGCombinerInfo &DCI,
24735                                   const X86Subtarget *Subtarget) {
24736   LoadSDNode *Ld = cast<LoadSDNode>(N);
24737   EVT RegVT = Ld->getValueType(0);
24738   EVT MemVT = Ld->getMemoryVT();
24739   SDLoc dl(Ld);
24740   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24741
24742   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24743   // into two 16-byte operations.
24744   ISD::LoadExtType Ext = Ld->getExtensionType();
24745   bool Fast;
24746   unsigned AddressSpace = Ld->getAddressSpace();
24747   unsigned Alignment = Ld->getAlignment();
24748   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
24749       Ext == ISD::NON_EXTLOAD &&
24750       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
24751                              AddressSpace, Alignment, &Fast) && !Fast) {
24752     unsigned NumElems = RegVT.getVectorNumElements();
24753     if (NumElems < 2)
24754       return SDValue();
24755
24756     SDValue Ptr = Ld->getBasePtr();
24757     SDValue Increment =
24758         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24759
24760     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24761                                   NumElems/2);
24762     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24763                                 Ld->getPointerInfo(), Ld->isVolatile(),
24764                                 Ld->isNonTemporal(), Ld->isInvariant(),
24765                                 Alignment);
24766     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24767     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24768                                 Ld->getPointerInfo(), Ld->isVolatile(),
24769                                 Ld->isNonTemporal(), Ld->isInvariant(),
24770                                 std::min(16U, Alignment));
24771     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24772                              Load1.getValue(1),
24773                              Load2.getValue(1));
24774
24775     SDValue NewVec = DAG.getUNDEF(RegVT);
24776     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24777     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24778     return DCI.CombineTo(N, NewVec, TF, true);
24779   }
24780
24781   return SDValue();
24782 }
24783
24784 /// PerformMLOADCombine - Resolve extending loads
24785 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24786                                    TargetLowering::DAGCombinerInfo &DCI,
24787                                    const X86Subtarget *Subtarget) {
24788   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24789   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24790     return SDValue();
24791
24792   EVT VT = Mld->getValueType(0);
24793   unsigned NumElems = VT.getVectorNumElements();
24794   EVT LdVT = Mld->getMemoryVT();
24795   SDLoc dl(Mld);
24796
24797   assert(LdVT != VT && "Cannot extend to the same type");
24798   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24799   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24800   // From, To sizes and ElemCount must be pow of two
24801   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24802     "Unexpected size for extending masked load");
24803
24804   unsigned SizeRatio  = ToSz / FromSz;
24805   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24806
24807   // Create a type on which we perform the shuffle
24808   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24809           LdVT.getScalarType(), NumElems*SizeRatio);
24810   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24811
24812   // Convert Src0 value
24813   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24814   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24815     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24816     for (unsigned i = 0; i != NumElems; ++i)
24817       ShuffleVec[i] = i * SizeRatio;
24818
24819     // Can't shuffle using an illegal type.
24820     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24821             && "WideVecVT should be legal");
24822     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24823                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24824   }
24825   // Prepare the new mask
24826   SDValue NewMask;
24827   SDValue Mask = Mld->getMask();
24828   if (Mask.getValueType() == VT) {
24829     // Mask and original value have the same type
24830     NewMask = DAG.getBitcast(WideVecVT, Mask);
24831     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24832     for (unsigned i = 0; i != NumElems; ++i)
24833       ShuffleVec[i] = i * SizeRatio;
24834     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24835       ShuffleVec[i] = NumElems*SizeRatio;
24836     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24837                                    DAG.getConstant(0, dl, WideVecVT),
24838                                    &ShuffleVec[0]);
24839   }
24840   else {
24841     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24842     unsigned WidenNumElts = NumElems*SizeRatio;
24843     unsigned MaskNumElts = VT.getVectorNumElements();
24844     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24845                                      WidenNumElts);
24846
24847     unsigned NumConcat = WidenNumElts / MaskNumElts;
24848     SmallVector<SDValue, 16> Ops(NumConcat);
24849     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24850     Ops[0] = Mask;
24851     for (unsigned i = 1; i != NumConcat; ++i)
24852       Ops[i] = ZeroVal;
24853
24854     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24855   }
24856
24857   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24858                                      Mld->getBasePtr(), NewMask, WideSrc0,
24859                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24860                                      ISD::NON_EXTLOAD);
24861   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24862   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24863
24864 }
24865 /// PerformMSTORECombine - Resolve truncating stores
24866 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24867                                     const X86Subtarget *Subtarget) {
24868   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24869   if (!Mst->isTruncatingStore())
24870     return SDValue();
24871
24872   EVT VT = Mst->getValue().getValueType();
24873   unsigned NumElems = VT.getVectorNumElements();
24874   EVT StVT = Mst->getMemoryVT();
24875   SDLoc dl(Mst);
24876
24877   assert(StVT != VT && "Cannot truncate to the same type");
24878   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24879   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24880
24881   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24882
24883   // The truncating store is legal in some cases. For example
24884   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24885   // are designated for truncate store.
24886   // In this case we don't need any further transformations.
24887   if (TLI.isTruncStoreLegal(VT, StVT))
24888     return SDValue();
24889
24890   // From, To sizes and ElemCount must be pow of two
24891   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24892     "Unexpected size for truncating masked store");
24893   // We are going to use the original vector elt for storing.
24894   // Accumulated smaller vector elements must be a multiple of the store size.
24895   assert (((NumElems * FromSz) % ToSz) == 0 &&
24896           "Unexpected ratio for truncating masked store");
24897
24898   unsigned SizeRatio  = FromSz / ToSz;
24899   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24900
24901   // Create a type on which we perform the shuffle
24902   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24903           StVT.getScalarType(), NumElems*SizeRatio);
24904
24905   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24906
24907   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24908   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24909   for (unsigned i = 0; i != NumElems; ++i)
24910     ShuffleVec[i] = i * SizeRatio;
24911
24912   // Can't shuffle using an illegal type.
24913   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24914           && "WideVecVT should be legal");
24915
24916   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24917                                         DAG.getUNDEF(WideVecVT),
24918                                         &ShuffleVec[0]);
24919
24920   SDValue NewMask;
24921   SDValue Mask = Mst->getMask();
24922   if (Mask.getValueType() == VT) {
24923     // Mask and original value have the same type
24924     NewMask = DAG.getBitcast(WideVecVT, Mask);
24925     for (unsigned i = 0; i != NumElems; ++i)
24926       ShuffleVec[i] = i * SizeRatio;
24927     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24928       ShuffleVec[i] = NumElems*SizeRatio;
24929     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24930                                    DAG.getConstant(0, dl, WideVecVT),
24931                                    &ShuffleVec[0]);
24932   }
24933   else {
24934     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24935     unsigned WidenNumElts = NumElems*SizeRatio;
24936     unsigned MaskNumElts = VT.getVectorNumElements();
24937     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24938                                      WidenNumElts);
24939
24940     unsigned NumConcat = WidenNumElts / MaskNumElts;
24941     SmallVector<SDValue, 16> Ops(NumConcat);
24942     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24943     Ops[0] = Mask;
24944     for (unsigned i = 1; i != NumConcat; ++i)
24945       Ops[i] = ZeroVal;
24946
24947     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24948   }
24949
24950   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24951                             NewMask, StVT, Mst->getMemOperand(), false);
24952 }
24953 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24954 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24955                                    const X86Subtarget *Subtarget) {
24956   StoreSDNode *St = cast<StoreSDNode>(N);
24957   EVT VT = St->getValue().getValueType();
24958   EVT StVT = St->getMemoryVT();
24959   SDLoc dl(St);
24960   SDValue StoredVal = St->getOperand(1);
24961   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24962
24963   // If we are saving a concatenation of two XMM registers and 32-byte stores
24964   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24965   bool Fast;
24966   unsigned AddressSpace = St->getAddressSpace();
24967   unsigned Alignment = St->getAlignment();
24968   if (VT.is256BitVector() && StVT == VT &&
24969       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
24970                              AddressSpace, Alignment, &Fast) && !Fast) {
24971     unsigned NumElems = VT.getVectorNumElements();
24972     if (NumElems < 2)
24973       return SDValue();
24974
24975     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24976     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24977
24978     SDValue Stride =
24979         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24980     SDValue Ptr0 = St->getBasePtr();
24981     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24982
24983     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24984                                 St->getPointerInfo(), St->isVolatile(),
24985                                 St->isNonTemporal(), Alignment);
24986     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24987                                 St->getPointerInfo(), St->isVolatile(),
24988                                 St->isNonTemporal(),
24989                                 std::min(16U, Alignment));
24990     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24991   }
24992
24993   // Optimize trunc store (of multiple scalars) to shuffle and store.
24994   // First, pack all of the elements in one place. Next, store to memory
24995   // in fewer chunks.
24996   if (St->isTruncatingStore() && VT.isVector()) {
24997     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24998     unsigned NumElems = VT.getVectorNumElements();
24999     assert(StVT != VT && "Cannot truncate to the same type");
25000     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25001     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25002
25003     // The truncating store is legal in some cases. For example
25004     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25005     // are designated for truncate store.
25006     // In this case we don't need any further transformations.
25007     if (TLI.isTruncStoreLegal(VT, StVT))
25008       return SDValue();
25009
25010     // From, To sizes and ElemCount must be pow of two
25011     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
25012     // We are going to use the original vector elt for storing.
25013     // Accumulated smaller vector elements must be a multiple of the store size.
25014     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
25015
25016     unsigned SizeRatio  = FromSz / ToSz;
25017
25018     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25019
25020     // Create a type on which we perform the shuffle
25021     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25022             StVT.getScalarType(), NumElems*SizeRatio);
25023
25024     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25025
25026     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
25027     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
25028     for (unsigned i = 0; i != NumElems; ++i)
25029       ShuffleVec[i] = i * SizeRatio;
25030
25031     // Can't shuffle using an illegal type.
25032     if (!TLI.isTypeLegal(WideVecVT))
25033       return SDValue();
25034
25035     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25036                                          DAG.getUNDEF(WideVecVT),
25037                                          &ShuffleVec[0]);
25038     // At this point all of the data is stored at the bottom of the
25039     // register. We now need to save it to mem.
25040
25041     // Find the largest store unit
25042     MVT StoreType = MVT::i8;
25043     for (MVT Tp : MVT::integer_valuetypes()) {
25044       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
25045         StoreType = Tp;
25046     }
25047
25048     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
25049     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
25050         (64 <= NumElems * ToSz))
25051       StoreType = MVT::f64;
25052
25053     // Bitcast the original vector into a vector of store-size units
25054     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
25055             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
25056     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
25057     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
25058     SmallVector<SDValue, 8> Chains;
25059     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
25060                                         TLI.getPointerTy(DAG.getDataLayout()));
25061     SDValue Ptr = St->getBasePtr();
25062
25063     // Perform one or more big stores into memory.
25064     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
25065       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
25066                                    StoreType, ShuffWide,
25067                                    DAG.getIntPtrConstant(i, dl));
25068       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
25069                                 St->getPointerInfo(), St->isVolatile(),
25070                                 St->isNonTemporal(), St->getAlignment());
25071       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25072       Chains.push_back(Ch);
25073     }
25074
25075     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
25076   }
25077
25078   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
25079   // the FP state in cases where an emms may be missing.
25080   // A preferable solution to the general problem is to figure out the right
25081   // places to insert EMMS.  This qualifies as a quick hack.
25082
25083   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
25084   if (VT.getSizeInBits() != 64)
25085     return SDValue();
25086
25087   const Function *F = DAG.getMachineFunction().getFunction();
25088   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
25089   bool F64IsLegal =
25090       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
25091   if ((VT.isVector() ||
25092        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
25093       isa<LoadSDNode>(St->getValue()) &&
25094       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
25095       St->getChain().hasOneUse() && !St->isVolatile()) {
25096     SDNode* LdVal = St->getValue().getNode();
25097     LoadSDNode *Ld = nullptr;
25098     int TokenFactorIndex = -1;
25099     SmallVector<SDValue, 8> Ops;
25100     SDNode* ChainVal = St->getChain().getNode();
25101     // Must be a store of a load.  We currently handle two cases:  the load
25102     // is a direct child, and it's under an intervening TokenFactor.  It is
25103     // possible to dig deeper under nested TokenFactors.
25104     if (ChainVal == LdVal)
25105       Ld = cast<LoadSDNode>(St->getChain());
25106     else if (St->getValue().hasOneUse() &&
25107              ChainVal->getOpcode() == ISD::TokenFactor) {
25108       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
25109         if (ChainVal->getOperand(i).getNode() == LdVal) {
25110           TokenFactorIndex = i;
25111           Ld = cast<LoadSDNode>(St->getValue());
25112         } else
25113           Ops.push_back(ChainVal->getOperand(i));
25114       }
25115     }
25116
25117     if (!Ld || !ISD::isNormalLoad(Ld))
25118       return SDValue();
25119
25120     // If this is not the MMX case, i.e. we are just turning i64 load/store
25121     // into f64 load/store, avoid the transformation if there are multiple
25122     // uses of the loaded value.
25123     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
25124       return SDValue();
25125
25126     SDLoc LdDL(Ld);
25127     SDLoc StDL(N);
25128     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
25129     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
25130     // pair instead.
25131     if (Subtarget->is64Bit() || F64IsLegal) {
25132       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
25133       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
25134                                   Ld->getPointerInfo(), Ld->isVolatile(),
25135                                   Ld->isNonTemporal(), Ld->isInvariant(),
25136                                   Ld->getAlignment());
25137       SDValue NewChain = NewLd.getValue(1);
25138       if (TokenFactorIndex != -1) {
25139         Ops.push_back(NewChain);
25140         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25141       }
25142       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
25143                           St->getPointerInfo(),
25144                           St->isVolatile(), St->isNonTemporal(),
25145                           St->getAlignment());
25146     }
25147
25148     // Otherwise, lower to two pairs of 32-bit loads / stores.
25149     SDValue LoAddr = Ld->getBasePtr();
25150     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
25151                                  DAG.getConstant(4, LdDL, MVT::i32));
25152
25153     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
25154                                Ld->getPointerInfo(),
25155                                Ld->isVolatile(), Ld->isNonTemporal(),
25156                                Ld->isInvariant(), Ld->getAlignment());
25157     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
25158                                Ld->getPointerInfo().getWithOffset(4),
25159                                Ld->isVolatile(), Ld->isNonTemporal(),
25160                                Ld->isInvariant(),
25161                                MinAlign(Ld->getAlignment(), 4));
25162
25163     SDValue NewChain = LoLd.getValue(1);
25164     if (TokenFactorIndex != -1) {
25165       Ops.push_back(LoLd);
25166       Ops.push_back(HiLd);
25167       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25168     }
25169
25170     LoAddr = St->getBasePtr();
25171     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
25172                          DAG.getConstant(4, StDL, MVT::i32));
25173
25174     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
25175                                 St->getPointerInfo(),
25176                                 St->isVolatile(), St->isNonTemporal(),
25177                                 St->getAlignment());
25178     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
25179                                 St->getPointerInfo().getWithOffset(4),
25180                                 St->isVolatile(),
25181                                 St->isNonTemporal(),
25182                                 MinAlign(St->getAlignment(), 4));
25183     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
25184   }
25185
25186   // This is similar to the above case, but here we handle a scalar 64-bit
25187   // integer store that is extracted from a vector on a 32-bit target.
25188   // If we have SSE2, then we can treat it like a floating-point double
25189   // to get past legalization. The execution dependencies fixup pass will
25190   // choose the optimal machine instruction for the store if this really is
25191   // an integer or v2f32 rather than an f64.
25192   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
25193       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
25194     SDValue OldExtract = St->getOperand(1);
25195     SDValue ExtOp0 = OldExtract.getOperand(0);
25196     unsigned VecSize = ExtOp0.getValueSizeInBits();
25197     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
25198     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
25199     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
25200                                      BitCast, OldExtract.getOperand(1));
25201     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
25202                         St->getPointerInfo(), St->isVolatile(),
25203                         St->isNonTemporal(), St->getAlignment());
25204   }
25205
25206   return SDValue();
25207 }
25208
25209 /// Return 'true' if this vector operation is "horizontal"
25210 /// and return the operands for the horizontal operation in LHS and RHS.  A
25211 /// horizontal operation performs the binary operation on successive elements
25212 /// of its first operand, then on successive elements of its second operand,
25213 /// returning the resulting values in a vector.  For example, if
25214 ///   A = < float a0, float a1, float a2, float a3 >
25215 /// and
25216 ///   B = < float b0, float b1, float b2, float b3 >
25217 /// then the result of doing a horizontal operation on A and B is
25218 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
25219 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
25220 /// A horizontal-op B, for some already available A and B, and if so then LHS is
25221 /// set to A, RHS to B, and the routine returns 'true'.
25222 /// Note that the binary operation should have the property that if one of the
25223 /// operands is UNDEF then the result is UNDEF.
25224 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
25225   // Look for the following pattern: if
25226   //   A = < float a0, float a1, float a2, float a3 >
25227   //   B = < float b0, float b1, float b2, float b3 >
25228   // and
25229   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
25230   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
25231   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
25232   // which is A horizontal-op B.
25233
25234   // At least one of the operands should be a vector shuffle.
25235   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
25236       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
25237     return false;
25238
25239   MVT VT = LHS.getSimpleValueType();
25240
25241   assert((VT.is128BitVector() || VT.is256BitVector()) &&
25242          "Unsupported vector type for horizontal add/sub");
25243
25244   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
25245   // operate independently on 128-bit lanes.
25246   unsigned NumElts = VT.getVectorNumElements();
25247   unsigned NumLanes = VT.getSizeInBits()/128;
25248   unsigned NumLaneElts = NumElts / NumLanes;
25249   assert((NumLaneElts % 2 == 0) &&
25250          "Vector type should have an even number of elements in each lane");
25251   unsigned HalfLaneElts = NumLaneElts/2;
25252
25253   // View LHS in the form
25254   //   LHS = VECTOR_SHUFFLE A, B, LMask
25255   // If LHS is not a shuffle then pretend it is the shuffle
25256   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
25257   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
25258   // type VT.
25259   SDValue A, B;
25260   SmallVector<int, 16> LMask(NumElts);
25261   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25262     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
25263       A = LHS.getOperand(0);
25264     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
25265       B = LHS.getOperand(1);
25266     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
25267     std::copy(Mask.begin(), Mask.end(), LMask.begin());
25268   } else {
25269     if (LHS.getOpcode() != ISD::UNDEF)
25270       A = LHS;
25271     for (unsigned i = 0; i != NumElts; ++i)
25272       LMask[i] = i;
25273   }
25274
25275   // Likewise, view RHS in the form
25276   //   RHS = VECTOR_SHUFFLE C, D, RMask
25277   SDValue C, D;
25278   SmallVector<int, 16> RMask(NumElts);
25279   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25280     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
25281       C = RHS.getOperand(0);
25282     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
25283       D = RHS.getOperand(1);
25284     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
25285     std::copy(Mask.begin(), Mask.end(), RMask.begin());
25286   } else {
25287     if (RHS.getOpcode() != ISD::UNDEF)
25288       C = RHS;
25289     for (unsigned i = 0; i != NumElts; ++i)
25290       RMask[i] = i;
25291   }
25292
25293   // Check that the shuffles are both shuffling the same vectors.
25294   if (!(A == C && B == D) && !(A == D && B == C))
25295     return false;
25296
25297   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
25298   if (!A.getNode() && !B.getNode())
25299     return false;
25300
25301   // If A and B occur in reverse order in RHS, then "swap" them (which means
25302   // rewriting the mask).
25303   if (A != C)
25304     ShuffleVectorSDNode::commuteMask(RMask);
25305
25306   // At this point LHS and RHS are equivalent to
25307   //   LHS = VECTOR_SHUFFLE A, B, LMask
25308   //   RHS = VECTOR_SHUFFLE A, B, RMask
25309   // Check that the masks correspond to performing a horizontal operation.
25310   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
25311     for (unsigned i = 0; i != NumLaneElts; ++i) {
25312       int LIdx = LMask[i+l], RIdx = RMask[i+l];
25313
25314       // Ignore any UNDEF components.
25315       if (LIdx < 0 || RIdx < 0 ||
25316           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
25317           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
25318         continue;
25319
25320       // Check that successive elements are being operated on.  If not, this is
25321       // not a horizontal operation.
25322       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
25323       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
25324       if (!(LIdx == Index && RIdx == Index + 1) &&
25325           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
25326         return false;
25327     }
25328   }
25329
25330   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
25331   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
25332   return true;
25333 }
25334
25335 /// Do target-specific dag combines on floating point adds.
25336 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
25337                                   const X86Subtarget *Subtarget) {
25338   EVT VT = N->getValueType(0);
25339   SDValue LHS = N->getOperand(0);
25340   SDValue RHS = N->getOperand(1);
25341
25342   // Try to synthesize horizontal adds from adds of shuffles.
25343   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25344        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25345       isHorizontalBinOp(LHS, RHS, true))
25346     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
25347   return SDValue();
25348 }
25349
25350 /// Do target-specific dag combines on floating point subs.
25351 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
25352                                   const X86Subtarget *Subtarget) {
25353   EVT VT = N->getValueType(0);
25354   SDValue LHS = N->getOperand(0);
25355   SDValue RHS = N->getOperand(1);
25356
25357   // Try to synthesize horizontal subs from subs of shuffles.
25358   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25359        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25360       isHorizontalBinOp(LHS, RHS, false))
25361     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
25362   return SDValue();
25363 }
25364
25365 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
25366 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
25367                                  const X86Subtarget *Subtarget) {
25368   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
25369
25370   // F[X]OR(0.0, x) -> x
25371   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25372     if (C->getValueAPF().isPosZero())
25373       return N->getOperand(1);
25374
25375   // F[X]OR(x, 0.0) -> x
25376   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25377     if (C->getValueAPF().isPosZero())
25378       return N->getOperand(0);
25379
25380   EVT VT = N->getValueType(0);
25381   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
25382     SDLoc dl(N);
25383     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
25384     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
25385
25386     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
25387     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
25388     unsigned IntOpcode = (N->getOpcode() == X86ISD::FOR) ? ISD::OR : ISD::XOR;
25389     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
25390     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
25391   }
25392   return SDValue();
25393 }
25394
25395 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
25396 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
25397   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
25398
25399   // Only perform optimizations if UnsafeMath is used.
25400   if (!DAG.getTarget().Options.UnsafeFPMath)
25401     return SDValue();
25402
25403   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25404   // into FMINC and FMAXC, which are Commutative operations.
25405   unsigned NewOp = 0;
25406   switch (N->getOpcode()) {
25407     default: llvm_unreachable("unknown opcode");
25408     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
25409     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
25410   }
25411
25412   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25413                      N->getOperand(0), N->getOperand(1));
25414 }
25415
25416 /// Do target-specific dag combines on X86ISD::FAND nodes.
25417 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25418   // FAND(0.0, x) -> 0.0
25419   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25420     if (C->getValueAPF().isPosZero())
25421       return N->getOperand(0);
25422
25423   // FAND(x, 0.0) -> 0.0
25424   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25425     if (C->getValueAPF().isPosZero())
25426       return N->getOperand(1);
25427
25428   return SDValue();
25429 }
25430
25431 /// Do target-specific dag combines on X86ISD::FANDN nodes
25432 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25433   // FANDN(0.0, x) -> x
25434   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25435     if (C->getValueAPF().isPosZero())
25436       return N->getOperand(1);
25437
25438   // FANDN(x, 0.0) -> 0.0
25439   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25440     if (C->getValueAPF().isPosZero())
25441       return N->getOperand(1);
25442
25443   return SDValue();
25444 }
25445
25446 static SDValue PerformBTCombine(SDNode *N,
25447                                 SelectionDAG &DAG,
25448                                 TargetLowering::DAGCombinerInfo &DCI) {
25449   // BT ignores high bits in the bit index operand.
25450   SDValue Op1 = N->getOperand(1);
25451   if (Op1.hasOneUse()) {
25452     unsigned BitWidth = Op1.getValueSizeInBits();
25453     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25454     APInt KnownZero, KnownOne;
25455     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25456                                           !DCI.isBeforeLegalizeOps());
25457     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25458     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25459         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25460       DCI.CommitTargetLoweringOpt(TLO);
25461   }
25462   return SDValue();
25463 }
25464
25465 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25466   SDValue Op = N->getOperand(0);
25467   if (Op.getOpcode() == ISD::BITCAST)
25468     Op = Op.getOperand(0);
25469   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25470   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25471       VT.getVectorElementType().getSizeInBits() ==
25472       OpVT.getVectorElementType().getSizeInBits()) {
25473     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25474   }
25475   return SDValue();
25476 }
25477
25478 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25479                                                const X86Subtarget *Subtarget) {
25480   EVT VT = N->getValueType(0);
25481   if (!VT.isVector())
25482     return SDValue();
25483
25484   SDValue N0 = N->getOperand(0);
25485   SDValue N1 = N->getOperand(1);
25486   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25487   SDLoc dl(N);
25488
25489   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25490   // both SSE and AVX2 since there is no sign-extended shift right
25491   // operation on a vector with 64-bit elements.
25492   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25493   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25494   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25495       N0.getOpcode() == ISD::SIGN_EXTEND)) {
25496     SDValue N00 = N0.getOperand(0);
25497
25498     // EXTLOAD has a better solution on AVX2,
25499     // it may be replaced with X86ISD::VSEXT node.
25500     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25501       if (!ISD::isNormalLoad(N00.getNode()))
25502         return SDValue();
25503
25504     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25505         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25506                                   N00, N1);
25507       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25508     }
25509   }
25510   return SDValue();
25511 }
25512
25513 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25514                                   TargetLowering::DAGCombinerInfo &DCI,
25515                                   const X86Subtarget *Subtarget) {
25516   SDValue N0 = N->getOperand(0);
25517   EVT VT = N->getValueType(0);
25518   EVT SVT = VT.getScalarType();
25519   EVT InVT = N0.getValueType();
25520   EVT InSVT = InVT.getScalarType();
25521   SDLoc DL(N);
25522
25523   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25524   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25525   // This exposes the sext to the sdivrem lowering, so that it directly extends
25526   // from AH (which we otherwise need to do contortions to access).
25527   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25528       InVT == MVT::i8 && VT == MVT::i32) {
25529     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25530     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25531                             N0.getOperand(0), N0.getOperand(1));
25532     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25533     return R.getValue(1);
25534   }
25535
25536   if (!DCI.isBeforeLegalizeOps()) {
25537     if (InVT == MVT::i1) {
25538       SDValue Zero = DAG.getConstant(0, DL, VT);
25539       SDValue AllOnes =
25540         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25541       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25542     }
25543     return SDValue();
25544   }
25545
25546   if (VT.isVector() && Subtarget->hasSSE2()) {
25547     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25548       EVT InVT = N.getValueType();
25549       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25550                                    Size / InVT.getScalarSizeInBits());
25551       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25552                                     DAG.getUNDEF(InVT));
25553       Opnds[0] = N;
25554       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25555     };
25556
25557     // If target-size is less than 128-bits, extend to a type that would extend
25558     // to 128 bits, extend that and extract the original target vector.
25559     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25560         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25561         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25562       unsigned Scale = 128 / VT.getSizeInBits();
25563       EVT ExVT =
25564           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25565       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25566       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25567       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25568                          DAG.getIntPtrConstant(0, DL));
25569     }
25570
25571     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25572     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25573     if (VT.getSizeInBits() == 128 &&
25574         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25575         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25576       SDValue ExOp = ExtendVecSize(DL, N0, 128);
25577       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25578     }
25579
25580     // On pre-AVX2 targets, split into 128-bit nodes of
25581     // ISD::SIGN_EXTEND_VECTOR_INREG.
25582     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25583         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25584         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25585       unsigned NumVecs = VT.getSizeInBits() / 128;
25586       unsigned NumSubElts = 128 / SVT.getSizeInBits();
25587       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25588       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25589
25590       SmallVector<SDValue, 8> Opnds;
25591       for (unsigned i = 0, Offset = 0; i != NumVecs;
25592            ++i, Offset += NumSubElts) {
25593         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25594                                      DAG.getIntPtrConstant(Offset, DL));
25595         SrcVec = ExtendVecSize(DL, SrcVec, 128);
25596         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25597         Opnds.push_back(SrcVec);
25598       }
25599       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25600     }
25601   }
25602
25603   if (!Subtarget->hasFp256())
25604     return SDValue();
25605
25606   if (VT.isVector() && VT.getSizeInBits() == 256)
25607     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25608       return R;
25609
25610   return SDValue();
25611 }
25612
25613 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25614                                  const X86Subtarget* Subtarget) {
25615   SDLoc dl(N);
25616   EVT VT = N->getValueType(0);
25617
25618   // Let legalize expand this if it isn't a legal type yet.
25619   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25620     return SDValue();
25621
25622   EVT ScalarVT = VT.getScalarType();
25623   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25624       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25625        !Subtarget->hasAVX512()))
25626     return SDValue();
25627
25628   SDValue A = N->getOperand(0);
25629   SDValue B = N->getOperand(1);
25630   SDValue C = N->getOperand(2);
25631
25632   bool NegA = (A.getOpcode() == ISD::FNEG);
25633   bool NegB = (B.getOpcode() == ISD::FNEG);
25634   bool NegC = (C.getOpcode() == ISD::FNEG);
25635
25636   // Negative multiplication when NegA xor NegB
25637   bool NegMul = (NegA != NegB);
25638   if (NegA)
25639     A = A.getOperand(0);
25640   if (NegB)
25641     B = B.getOperand(0);
25642   if (NegC)
25643     C = C.getOperand(0);
25644
25645   unsigned Opcode;
25646   if (!NegMul)
25647     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25648   else
25649     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25650
25651   return DAG.getNode(Opcode, dl, VT, A, B, C);
25652 }
25653
25654 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25655                                   TargetLowering::DAGCombinerInfo &DCI,
25656                                   const X86Subtarget *Subtarget) {
25657   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
25658   //           (and (i32 x86isd::setcc_carry), 1)
25659   // This eliminates the zext. This transformation is necessary because
25660   // ISD::SETCC is always legalized to i8.
25661   SDLoc dl(N);
25662   SDValue N0 = N->getOperand(0);
25663   EVT VT = N->getValueType(0);
25664
25665   if (N0.getOpcode() == ISD::AND &&
25666       N0.hasOneUse() &&
25667       N0.getOperand(0).hasOneUse()) {
25668     SDValue N00 = N0.getOperand(0);
25669     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25670       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25671       if (!C || C->getZExtValue() != 1)
25672         return SDValue();
25673       return DAG.getNode(ISD::AND, dl, VT,
25674                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25675                                      N00.getOperand(0), N00.getOperand(1)),
25676                          DAG.getConstant(1, dl, VT));
25677     }
25678   }
25679
25680   if (N0.getOpcode() == ISD::TRUNCATE &&
25681       N0.hasOneUse() &&
25682       N0.getOperand(0).hasOneUse()) {
25683     SDValue N00 = N0.getOperand(0);
25684     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25685       return DAG.getNode(ISD::AND, dl, VT,
25686                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25687                                      N00.getOperand(0), N00.getOperand(1)),
25688                          DAG.getConstant(1, dl, VT));
25689     }
25690   }
25691
25692   if (VT.is256BitVector())
25693     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25694       return R;
25695
25696   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25697   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25698   // This exposes the zext to the udivrem lowering, so that it directly extends
25699   // from AH (which we otherwise need to do contortions to access).
25700   if (N0.getOpcode() == ISD::UDIVREM &&
25701       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25702       (VT == MVT::i32 || VT == MVT::i64)) {
25703     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25704     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25705                             N0.getOperand(0), N0.getOperand(1));
25706     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25707     return R.getValue(1);
25708   }
25709
25710   return SDValue();
25711 }
25712
25713 // Optimize x == -y --> x+y == 0
25714 //          x != -y --> x+y != 0
25715 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25716                                       const X86Subtarget* Subtarget) {
25717   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25718   SDValue LHS = N->getOperand(0);
25719   SDValue RHS = N->getOperand(1);
25720   EVT VT = N->getValueType(0);
25721   SDLoc DL(N);
25722
25723   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25724     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25725       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25726         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25727                                    LHS.getOperand(1));
25728         return DAG.getSetCC(DL, N->getValueType(0), addV,
25729                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25730       }
25731   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25732     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25733       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25734         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25735                                    RHS.getOperand(1));
25736         return DAG.getSetCC(DL, N->getValueType(0), addV,
25737                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25738       }
25739
25740   if (VT.getScalarType() == MVT::i1 &&
25741       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25742     bool IsSEXT0 =
25743         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25744         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25745     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25746
25747     if (!IsSEXT0 || !IsVZero1) {
25748       // Swap the operands and update the condition code.
25749       std::swap(LHS, RHS);
25750       CC = ISD::getSetCCSwappedOperands(CC);
25751
25752       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25753                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25754       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25755     }
25756
25757     if (IsSEXT0 && IsVZero1) {
25758       assert(VT == LHS.getOperand(0).getValueType() &&
25759              "Uexpected operand type");
25760       if (CC == ISD::SETGT)
25761         return DAG.getConstant(0, DL, VT);
25762       if (CC == ISD::SETLE)
25763         return DAG.getConstant(1, DL, VT);
25764       if (CC == ISD::SETEQ || CC == ISD::SETGE)
25765         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25766
25767       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25768              "Unexpected condition code!");
25769       return LHS.getOperand(0);
25770     }
25771   }
25772
25773   return SDValue();
25774 }
25775
25776 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25777                                          SelectionDAG &DAG) {
25778   SDLoc dl(Load);
25779   MVT VT = Load->getSimpleValueType(0);
25780   MVT EVT = VT.getVectorElementType();
25781   SDValue Addr = Load->getOperand(1);
25782   SDValue NewAddr = DAG.getNode(
25783       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25784       DAG.getConstant(Index * EVT.getStoreSize(), dl,
25785                       Addr.getSimpleValueType()));
25786
25787   SDValue NewLoad =
25788       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25789                   DAG.getMachineFunction().getMachineMemOperand(
25790                       Load->getMemOperand(), 0, EVT.getStoreSize()));
25791   return NewLoad;
25792 }
25793
25794 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25795                                       const X86Subtarget *Subtarget) {
25796   SDLoc dl(N);
25797   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25798   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25799          "X86insertps is only defined for v4x32");
25800
25801   SDValue Ld = N->getOperand(1);
25802   if (MayFoldLoad(Ld)) {
25803     // Extract the countS bits from the immediate so we can get the proper
25804     // address when narrowing the vector load to a specific element.
25805     // When the second source op is a memory address, insertps doesn't use
25806     // countS and just gets an f32 from that address.
25807     unsigned DestIndex =
25808         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25809
25810     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25811
25812     // Create this as a scalar to vector to match the instruction pattern.
25813     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25814     // countS bits are ignored when loading from memory on insertps, which
25815     // means we don't need to explicitly set them to 0.
25816     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25817                        LoadScalarToVector, N->getOperand(2));
25818   }
25819   return SDValue();
25820 }
25821
25822 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25823   SDValue V0 = N->getOperand(0);
25824   SDValue V1 = N->getOperand(1);
25825   SDLoc DL(N);
25826   EVT VT = N->getValueType(0);
25827
25828   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25829   // operands and changing the mask to 1. This saves us a bunch of
25830   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25831   // x86InstrInfo knows how to commute this back after instruction selection
25832   // if it would help register allocation.
25833
25834   // TODO: If optimizing for size or a processor that doesn't suffer from
25835   // partial register update stalls, this should be transformed into a MOVSD
25836   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25837
25838   if (VT == MVT::v2f64)
25839     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25840       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25841         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25842         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25843       }
25844
25845   return SDValue();
25846 }
25847
25848 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25849 // as "sbb reg,reg", since it can be extended without zext and produces
25850 // an all-ones bit which is more useful than 0/1 in some cases.
25851 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25852                                MVT VT) {
25853   if (VT == MVT::i8)
25854     return DAG.getNode(ISD::AND, DL, VT,
25855                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25856                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25857                                    EFLAGS),
25858                        DAG.getConstant(1, DL, VT));
25859   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25860   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25861                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25862                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25863                                  EFLAGS));
25864 }
25865
25866 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25867 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25868                                    TargetLowering::DAGCombinerInfo &DCI,
25869                                    const X86Subtarget *Subtarget) {
25870   SDLoc DL(N);
25871   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25872   SDValue EFLAGS = N->getOperand(1);
25873
25874   if (CC == X86::COND_A) {
25875     // Try to convert COND_A into COND_B in an attempt to facilitate
25876     // materializing "setb reg".
25877     //
25878     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25879     // cannot take an immediate as its first operand.
25880     //
25881     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25882         EFLAGS.getValueType().isInteger() &&
25883         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25884       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25885                                    EFLAGS.getNode()->getVTList(),
25886                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25887       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25888       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25889     }
25890   }
25891
25892   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25893   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25894   // cases.
25895   if (CC == X86::COND_B)
25896     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25897
25898   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25899     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25900     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25901   }
25902
25903   return SDValue();
25904 }
25905
25906 // Optimize branch condition evaluation.
25907 //
25908 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25909                                     TargetLowering::DAGCombinerInfo &DCI,
25910                                     const X86Subtarget *Subtarget) {
25911   SDLoc DL(N);
25912   SDValue Chain = N->getOperand(0);
25913   SDValue Dest = N->getOperand(1);
25914   SDValue EFLAGS = N->getOperand(3);
25915   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25916
25917   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25918     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25919     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25920                        Flags);
25921   }
25922
25923   return SDValue();
25924 }
25925
25926 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25927                                                          SelectionDAG &DAG) {
25928   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25929   // optimize away operation when it's from a constant.
25930   //
25931   // The general transformation is:
25932   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25933   //       AND(VECTOR_CMP(x,y), constant2)
25934   //    constant2 = UNARYOP(constant)
25935
25936   // Early exit if this isn't a vector operation, the operand of the
25937   // unary operation isn't a bitwise AND, or if the sizes of the operations
25938   // aren't the same.
25939   EVT VT = N->getValueType(0);
25940   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25941       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25942       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25943     return SDValue();
25944
25945   // Now check that the other operand of the AND is a constant. We could
25946   // make the transformation for non-constant splats as well, but it's unclear
25947   // that would be a benefit as it would not eliminate any operations, just
25948   // perform one more step in scalar code before moving to the vector unit.
25949   if (BuildVectorSDNode *BV =
25950           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25951     // Bail out if the vector isn't a constant.
25952     if (!BV->isConstant())
25953       return SDValue();
25954
25955     // Everything checks out. Build up the new and improved node.
25956     SDLoc DL(N);
25957     EVT IntVT = BV->getValueType(0);
25958     // Create a new constant of the appropriate type for the transformed
25959     // DAG.
25960     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25961     // The AND node needs bitcasts to/from an integer vector type around it.
25962     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25963     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25964                                  N->getOperand(0)->getOperand(0), MaskConst);
25965     SDValue Res = DAG.getBitcast(VT, NewAnd);
25966     return Res;
25967   }
25968
25969   return SDValue();
25970 }
25971
25972 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25973                                         const X86Subtarget *Subtarget) {
25974   SDValue Op0 = N->getOperand(0);
25975   EVT VT = N->getValueType(0);
25976   EVT InVT = Op0.getValueType();
25977   EVT InSVT = InVT.getScalarType();
25978   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25979
25980   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25981   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25982   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25983     SDLoc dl(N);
25984     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25985                                  InVT.getVectorNumElements());
25986     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25987
25988     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25989       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25990
25991     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25992   }
25993
25994   return SDValue();
25995 }
25996
25997 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25998                                         const X86Subtarget *Subtarget) {
25999   // First try to optimize away the conversion entirely when it's
26000   // conditionally from a constant. Vectors only.
26001   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
26002     return Res;
26003
26004   // Now move on to more general possibilities.
26005   SDValue Op0 = N->getOperand(0);
26006   EVT VT = N->getValueType(0);
26007   EVT InVT = Op0.getValueType();
26008   EVT InSVT = InVT.getScalarType();
26009
26010   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
26011   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
26012   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26013     SDLoc dl(N);
26014     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26015                                  InVT.getVectorNumElements());
26016     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
26017     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26018   }
26019
26020   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
26021   // a 32-bit target where SSE doesn't support i64->FP operations.
26022   if (Op0.getOpcode() == ISD::LOAD) {
26023     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
26024     EVT LdVT = Ld->getValueType(0);
26025
26026     // This transformation is not supported if the result type is f16
26027     if (VT == MVT::f16)
26028       return SDValue();
26029
26030     if (!Ld->isVolatile() && !VT.isVector() &&
26031         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
26032         !Subtarget->is64Bit() && LdVT == MVT::i64) {
26033       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
26034           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
26035       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
26036       return FILDChain;
26037     }
26038   }
26039   return SDValue();
26040 }
26041
26042 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
26043 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
26044                                  X86TargetLowering::DAGCombinerInfo &DCI) {
26045   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
26046   // the result is either zero or one (depending on the input carry bit).
26047   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
26048   if (X86::isZeroNode(N->getOperand(0)) &&
26049       X86::isZeroNode(N->getOperand(1)) &&
26050       // We don't have a good way to replace an EFLAGS use, so only do this when
26051       // dead right now.
26052       SDValue(N, 1).use_empty()) {
26053     SDLoc DL(N);
26054     EVT VT = N->getValueType(0);
26055     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
26056     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
26057                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
26058                                            DAG.getConstant(X86::COND_B, DL,
26059                                                            MVT::i8),
26060                                            N->getOperand(2)),
26061                                DAG.getConstant(1, DL, VT));
26062     return DCI.CombineTo(N, Res1, CarryOut);
26063   }
26064
26065   return SDValue();
26066 }
26067
26068 // fold (add Y, (sete  X, 0)) -> adc  0, Y
26069 //      (add Y, (setne X, 0)) -> sbb -1, Y
26070 //      (sub (sete  X, 0), Y) -> sbb  0, Y
26071 //      (sub (setne X, 0), Y) -> adc -1, Y
26072 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
26073   SDLoc DL(N);
26074
26075   // Look through ZExts.
26076   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
26077   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
26078     return SDValue();
26079
26080   SDValue SetCC = Ext.getOperand(0);
26081   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
26082     return SDValue();
26083
26084   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
26085   if (CC != X86::COND_E && CC != X86::COND_NE)
26086     return SDValue();
26087
26088   SDValue Cmp = SetCC.getOperand(1);
26089   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
26090       !X86::isZeroNode(Cmp.getOperand(1)) ||
26091       !Cmp.getOperand(0).getValueType().isInteger())
26092     return SDValue();
26093
26094   SDValue CmpOp0 = Cmp.getOperand(0);
26095   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
26096                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
26097
26098   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
26099   if (CC == X86::COND_NE)
26100     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
26101                        DL, OtherVal.getValueType(), OtherVal,
26102                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
26103                        NewCmp);
26104   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
26105                      DL, OtherVal.getValueType(), OtherVal,
26106                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
26107 }
26108
26109 /// PerformADDCombine - Do target-specific dag combines on integer adds.
26110 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
26111                                  const X86Subtarget *Subtarget) {
26112   EVT VT = N->getValueType(0);
26113   SDValue Op0 = N->getOperand(0);
26114   SDValue Op1 = N->getOperand(1);
26115
26116   // Try to synthesize horizontal adds from adds of shuffles.
26117   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26118        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26119       isHorizontalBinOp(Op0, Op1, true))
26120     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
26121
26122   return OptimizeConditionalInDecrement(N, DAG);
26123 }
26124
26125 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
26126                                  const X86Subtarget *Subtarget) {
26127   SDValue Op0 = N->getOperand(0);
26128   SDValue Op1 = N->getOperand(1);
26129
26130   // X86 can't encode an immediate LHS of a sub. See if we can push the
26131   // negation into a preceding instruction.
26132   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
26133     // If the RHS of the sub is a XOR with one use and a constant, invert the
26134     // immediate. Then add one to the LHS of the sub so we can turn
26135     // X-Y -> X+~Y+1, saving one register.
26136     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
26137         isa<ConstantSDNode>(Op1.getOperand(1))) {
26138       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
26139       EVT VT = Op0.getValueType();
26140       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
26141                                    Op1.getOperand(0),
26142                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
26143       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
26144                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
26145     }
26146   }
26147
26148   // Try to synthesize horizontal adds from adds of shuffles.
26149   EVT VT = N->getValueType(0);
26150   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26151        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26152       isHorizontalBinOp(Op0, Op1, true))
26153     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
26154
26155   return OptimizeConditionalInDecrement(N, DAG);
26156 }
26157
26158 /// performVZEXTCombine - Performs build vector combines
26159 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
26160                                    TargetLowering::DAGCombinerInfo &DCI,
26161                                    const X86Subtarget *Subtarget) {
26162   SDLoc DL(N);
26163   MVT VT = N->getSimpleValueType(0);
26164   SDValue Op = N->getOperand(0);
26165   MVT OpVT = Op.getSimpleValueType();
26166   MVT OpEltVT = OpVT.getVectorElementType();
26167   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
26168
26169   // (vzext (bitcast (vzext (x)) -> (vzext x)
26170   SDValue V = Op;
26171   while (V.getOpcode() == ISD::BITCAST)
26172     V = V.getOperand(0);
26173
26174   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
26175     MVT InnerVT = V.getSimpleValueType();
26176     MVT InnerEltVT = InnerVT.getVectorElementType();
26177
26178     // If the element sizes match exactly, we can just do one larger vzext. This
26179     // is always an exact type match as vzext operates on integer types.
26180     if (OpEltVT == InnerEltVT) {
26181       assert(OpVT == InnerVT && "Types must match for vzext!");
26182       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
26183     }
26184
26185     // The only other way we can combine them is if only a single element of the
26186     // inner vzext is used in the input to the outer vzext.
26187     if (InnerEltVT.getSizeInBits() < InputBits)
26188       return SDValue();
26189
26190     // In this case, the inner vzext is completely dead because we're going to
26191     // only look at bits inside of the low element. Just do the outer vzext on
26192     // a bitcast of the input to the inner.
26193     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
26194   }
26195
26196   // Check if we can bypass extracting and re-inserting an element of an input
26197   // vector. Essentially:
26198   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
26199   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
26200       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
26201       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
26202     SDValue ExtractedV = V.getOperand(0);
26203     SDValue OrigV = ExtractedV.getOperand(0);
26204     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
26205       if (ExtractIdx->getZExtValue() == 0) {
26206         MVT OrigVT = OrigV.getSimpleValueType();
26207         // Extract a subvector if necessary...
26208         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
26209           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
26210           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
26211                                     OrigVT.getVectorNumElements() / Ratio);
26212           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
26213                               DAG.getIntPtrConstant(0, DL));
26214         }
26215         Op = DAG.getBitcast(OpVT, OrigV);
26216         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
26217       }
26218   }
26219
26220   return SDValue();
26221 }
26222
26223 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
26224                                              DAGCombinerInfo &DCI) const {
26225   SelectionDAG &DAG = DCI.DAG;
26226   switch (N->getOpcode()) {
26227   default: break;
26228   case ISD::EXTRACT_VECTOR_ELT:
26229     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
26230   case ISD::VSELECT:
26231   case ISD::SELECT:
26232   case X86ISD::SHRUNKBLEND:
26233     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
26234   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
26235   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
26236   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
26237   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
26238   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
26239   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
26240   case ISD::SHL:
26241   case ISD::SRA:
26242   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
26243   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
26244   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
26245   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
26246   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
26247   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
26248   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
26249   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
26250   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
26251   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
26252   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
26253   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
26254   case X86ISD::FXOR:
26255   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
26256   case X86ISD::FMIN:
26257   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
26258   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
26259   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
26260   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
26261   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
26262   case ISD::ANY_EXTEND:
26263   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
26264   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
26265   case ISD::SIGN_EXTEND_INREG:
26266     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
26267   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
26268   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
26269   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
26270   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
26271   case X86ISD::SHUFP:       // Handle all target specific shuffles
26272   case X86ISD::PALIGNR:
26273   case X86ISD::UNPCKH:
26274   case X86ISD::UNPCKL:
26275   case X86ISD::MOVHLPS:
26276   case X86ISD::MOVLHPS:
26277   case X86ISD::PSHUFB:
26278   case X86ISD::PSHUFD:
26279   case X86ISD::PSHUFHW:
26280   case X86ISD::PSHUFLW:
26281   case X86ISD::MOVSS:
26282   case X86ISD::MOVSD:
26283   case X86ISD::VPERMILPI:
26284   case X86ISD::VPERM2X128:
26285   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
26286   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
26287   case X86ISD::INSERTPS: {
26288     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
26289       return PerformINSERTPSCombine(N, DAG, Subtarget);
26290     break;
26291   }
26292   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
26293   }
26294
26295   return SDValue();
26296 }
26297
26298 /// isTypeDesirableForOp - Return true if the target has native support for
26299 /// the specified value type and it is 'desirable' to use the type for the
26300 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
26301 /// instruction encodings are longer and some i16 instructions are slow.
26302 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
26303   if (!isTypeLegal(VT))
26304     return false;
26305   if (VT != MVT::i16)
26306     return true;
26307
26308   switch (Opc) {
26309   default:
26310     return true;
26311   case ISD::LOAD:
26312   case ISD::SIGN_EXTEND:
26313   case ISD::ZERO_EXTEND:
26314   case ISD::ANY_EXTEND:
26315   case ISD::SHL:
26316   case ISD::SRL:
26317   case ISD::SUB:
26318   case ISD::ADD:
26319   case ISD::MUL:
26320   case ISD::AND:
26321   case ISD::OR:
26322   case ISD::XOR:
26323     return false;
26324   }
26325 }
26326
26327 /// IsDesirableToPromoteOp - This method query the target whether it is
26328 /// beneficial for dag combiner to promote the specified node. If true, it
26329 /// should return the desired promotion type by reference.
26330 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
26331   EVT VT = Op.getValueType();
26332   if (VT != MVT::i16)
26333     return false;
26334
26335   bool Promote = false;
26336   bool Commute = false;
26337   switch (Op.getOpcode()) {
26338   default: break;
26339   case ISD::LOAD: {
26340     LoadSDNode *LD = cast<LoadSDNode>(Op);
26341     // If the non-extending load has a single use and it's not live out, then it
26342     // might be folded.
26343     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
26344                                                      Op.hasOneUse()*/) {
26345       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
26346              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
26347         // The only case where we'd want to promote LOAD (rather then it being
26348         // promoted as an operand is when it's only use is liveout.
26349         if (UI->getOpcode() != ISD::CopyToReg)
26350           return false;
26351       }
26352     }
26353     Promote = true;
26354     break;
26355   }
26356   case ISD::SIGN_EXTEND:
26357   case ISD::ZERO_EXTEND:
26358   case ISD::ANY_EXTEND:
26359     Promote = true;
26360     break;
26361   case ISD::SHL:
26362   case ISD::SRL: {
26363     SDValue N0 = Op.getOperand(0);
26364     // Look out for (store (shl (load), x)).
26365     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
26366       return false;
26367     Promote = true;
26368     break;
26369   }
26370   case ISD::ADD:
26371   case ISD::MUL:
26372   case ISD::AND:
26373   case ISD::OR:
26374   case ISD::XOR:
26375     Commute = true;
26376     // fallthrough
26377   case ISD::SUB: {
26378     SDValue N0 = Op.getOperand(0);
26379     SDValue N1 = Op.getOperand(1);
26380     if (!Commute && MayFoldLoad(N1))
26381       return false;
26382     // Avoid disabling potential load folding opportunities.
26383     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
26384       return false;
26385     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
26386       return false;
26387     Promote = true;
26388   }
26389   }
26390
26391   PVT = MVT::i32;
26392   return Promote;
26393 }
26394
26395 //===----------------------------------------------------------------------===//
26396 //                           X86 Inline Assembly Support
26397 //===----------------------------------------------------------------------===//
26398
26399 // Helper to match a string separated by whitespace.
26400 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
26401   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
26402
26403   for (StringRef Piece : Pieces) {
26404     if (!S.startswith(Piece)) // Check if the piece matches.
26405       return false;
26406
26407     S = S.substr(Piece.size());
26408     StringRef::size_type Pos = S.find_first_not_of(" \t");
26409     if (Pos == 0) // We matched a prefix.
26410       return false;
26411
26412     S = S.substr(Pos);
26413   }
26414
26415   return S.empty();
26416 }
26417
26418 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26419
26420   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26421     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26422         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26423         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26424
26425       if (AsmPieces.size() == 3)
26426         return true;
26427       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26428         return true;
26429     }
26430   }
26431   return false;
26432 }
26433
26434 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26435   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26436
26437   std::string AsmStr = IA->getAsmString();
26438
26439   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26440   if (!Ty || Ty->getBitWidth() % 16 != 0)
26441     return false;
26442
26443   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26444   SmallVector<StringRef, 4> AsmPieces;
26445   SplitString(AsmStr, AsmPieces, ";\n");
26446
26447   switch (AsmPieces.size()) {
26448   default: return false;
26449   case 1:
26450     // FIXME: this should verify that we are targeting a 486 or better.  If not,
26451     // we will turn this bswap into something that will be lowered to logical
26452     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
26453     // lower so don't worry about this.
26454     // bswap $0
26455     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26456         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26457         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26458         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26459         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26460         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26461       // No need to check constraints, nothing other than the equivalent of
26462       // "=r,0" would be valid here.
26463       return IntrinsicLowering::LowerToByteSwap(CI);
26464     }
26465
26466     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
26467     if (CI->getType()->isIntegerTy(16) &&
26468         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26469         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26470          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26471       AsmPieces.clear();
26472       StringRef ConstraintsStr = IA->getConstraintString();
26473       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26474       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26475       if (clobbersFlagRegisters(AsmPieces))
26476         return IntrinsicLowering::LowerToByteSwap(CI);
26477     }
26478     break;
26479   case 3:
26480     if (CI->getType()->isIntegerTy(32) &&
26481         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26482         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26483         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26484         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26485       AsmPieces.clear();
26486       StringRef ConstraintsStr = IA->getConstraintString();
26487       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26488       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26489       if (clobbersFlagRegisters(AsmPieces))
26490         return IntrinsicLowering::LowerToByteSwap(CI);
26491     }
26492
26493     if (CI->getType()->isIntegerTy(64)) {
26494       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26495       if (Constraints.size() >= 2 &&
26496           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26497           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26498         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
26499         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26500             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26501             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26502           return IntrinsicLowering::LowerToByteSwap(CI);
26503       }
26504     }
26505     break;
26506   }
26507   return false;
26508 }
26509
26510 /// getConstraintType - Given a constraint letter, return the type of
26511 /// constraint it is for this target.
26512 X86TargetLowering::ConstraintType
26513 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26514   if (Constraint.size() == 1) {
26515     switch (Constraint[0]) {
26516     case 'R':
26517     case 'q':
26518     case 'Q':
26519     case 'f':
26520     case 't':
26521     case 'u':
26522     case 'y':
26523     case 'x':
26524     case 'Y':
26525     case 'l':
26526       return C_RegisterClass;
26527     case 'a':
26528     case 'b':
26529     case 'c':
26530     case 'd':
26531     case 'S':
26532     case 'D':
26533     case 'A':
26534       return C_Register;
26535     case 'I':
26536     case 'J':
26537     case 'K':
26538     case 'L':
26539     case 'M':
26540     case 'N':
26541     case 'G':
26542     case 'C':
26543     case 'e':
26544     case 'Z':
26545       return C_Other;
26546     default:
26547       break;
26548     }
26549   }
26550   return TargetLowering::getConstraintType(Constraint);
26551 }
26552
26553 /// Examine constraint type and operand type and determine a weight value.
26554 /// This object must already have been set up with the operand type
26555 /// and the current alternative constraint selected.
26556 TargetLowering::ConstraintWeight
26557   X86TargetLowering::getSingleConstraintMatchWeight(
26558     AsmOperandInfo &info, const char *constraint) const {
26559   ConstraintWeight weight = CW_Invalid;
26560   Value *CallOperandVal = info.CallOperandVal;
26561     // If we don't have a value, we can't do a match,
26562     // but allow it at the lowest weight.
26563   if (!CallOperandVal)
26564     return CW_Default;
26565   Type *type = CallOperandVal->getType();
26566   // Look at the constraint type.
26567   switch (*constraint) {
26568   default:
26569     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26570   case 'R':
26571   case 'q':
26572   case 'Q':
26573   case 'a':
26574   case 'b':
26575   case 'c':
26576   case 'd':
26577   case 'S':
26578   case 'D':
26579   case 'A':
26580     if (CallOperandVal->getType()->isIntegerTy())
26581       weight = CW_SpecificReg;
26582     break;
26583   case 'f':
26584   case 't':
26585   case 'u':
26586     if (type->isFloatingPointTy())
26587       weight = CW_SpecificReg;
26588     break;
26589   case 'y':
26590     if (type->isX86_MMXTy() && Subtarget->hasMMX())
26591       weight = CW_SpecificReg;
26592     break;
26593   case 'x':
26594   case 'Y':
26595     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26596         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26597       weight = CW_Register;
26598     break;
26599   case 'I':
26600     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26601       if (C->getZExtValue() <= 31)
26602         weight = CW_Constant;
26603     }
26604     break;
26605   case 'J':
26606     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26607       if (C->getZExtValue() <= 63)
26608         weight = CW_Constant;
26609     }
26610     break;
26611   case 'K':
26612     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26613       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26614         weight = CW_Constant;
26615     }
26616     break;
26617   case 'L':
26618     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26619       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26620         weight = CW_Constant;
26621     }
26622     break;
26623   case 'M':
26624     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26625       if (C->getZExtValue() <= 3)
26626         weight = CW_Constant;
26627     }
26628     break;
26629   case 'N':
26630     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26631       if (C->getZExtValue() <= 0xff)
26632         weight = CW_Constant;
26633     }
26634     break;
26635   case 'G':
26636   case 'C':
26637     if (isa<ConstantFP>(CallOperandVal)) {
26638       weight = CW_Constant;
26639     }
26640     break;
26641   case 'e':
26642     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26643       if ((C->getSExtValue() >= -0x80000000LL) &&
26644           (C->getSExtValue() <= 0x7fffffffLL))
26645         weight = CW_Constant;
26646     }
26647     break;
26648   case 'Z':
26649     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26650       if (C->getZExtValue() <= 0xffffffff)
26651         weight = CW_Constant;
26652     }
26653     break;
26654   }
26655   return weight;
26656 }
26657
26658 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26659 /// with another that has more specific requirements based on the type of the
26660 /// corresponding operand.
26661 const char *X86TargetLowering::
26662 LowerXConstraint(EVT ConstraintVT) const {
26663   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26664   // 'f' like normal targets.
26665   if (ConstraintVT.isFloatingPoint()) {
26666     if (Subtarget->hasSSE2())
26667       return "Y";
26668     if (Subtarget->hasSSE1())
26669       return "x";
26670   }
26671
26672   return TargetLowering::LowerXConstraint(ConstraintVT);
26673 }
26674
26675 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26676 /// vector.  If it is invalid, don't add anything to Ops.
26677 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26678                                                      std::string &Constraint,
26679                                                      std::vector<SDValue>&Ops,
26680                                                      SelectionDAG &DAG) const {
26681   SDValue Result;
26682
26683   // Only support length 1 constraints for now.
26684   if (Constraint.length() > 1) return;
26685
26686   char ConstraintLetter = Constraint[0];
26687   switch (ConstraintLetter) {
26688   default: break;
26689   case 'I':
26690     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26691       if (C->getZExtValue() <= 31) {
26692         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26693                                        Op.getValueType());
26694         break;
26695       }
26696     }
26697     return;
26698   case 'J':
26699     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26700       if (C->getZExtValue() <= 63) {
26701         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26702                                        Op.getValueType());
26703         break;
26704       }
26705     }
26706     return;
26707   case 'K':
26708     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26709       if (isInt<8>(C->getSExtValue())) {
26710         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26711                                        Op.getValueType());
26712         break;
26713       }
26714     }
26715     return;
26716   case 'L':
26717     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26718       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26719           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26720         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26721                                        Op.getValueType());
26722         break;
26723       }
26724     }
26725     return;
26726   case 'M':
26727     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26728       if (C->getZExtValue() <= 3) {
26729         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26730                                        Op.getValueType());
26731         break;
26732       }
26733     }
26734     return;
26735   case 'N':
26736     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26737       if (C->getZExtValue() <= 255) {
26738         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26739                                        Op.getValueType());
26740         break;
26741       }
26742     }
26743     return;
26744   case 'O':
26745     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26746       if (C->getZExtValue() <= 127) {
26747         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26748                                        Op.getValueType());
26749         break;
26750       }
26751     }
26752     return;
26753   case 'e': {
26754     // 32-bit signed value
26755     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26756       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26757                                            C->getSExtValue())) {
26758         // Widen to 64 bits here to get it sign extended.
26759         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26760         break;
26761       }
26762     // FIXME gcc accepts some relocatable values here too, but only in certain
26763     // memory models; it's complicated.
26764     }
26765     return;
26766   }
26767   case 'Z': {
26768     // 32-bit unsigned value
26769     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26770       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26771                                            C->getZExtValue())) {
26772         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26773                                        Op.getValueType());
26774         break;
26775       }
26776     }
26777     // FIXME gcc accepts some relocatable values here too, but only in certain
26778     // memory models; it's complicated.
26779     return;
26780   }
26781   case 'i': {
26782     // Literal immediates are always ok.
26783     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26784       // Widen to 64 bits here to get it sign extended.
26785       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26786       break;
26787     }
26788
26789     // In any sort of PIC mode addresses need to be computed at runtime by
26790     // adding in a register or some sort of table lookup.  These can't
26791     // be used as immediates.
26792     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26793       return;
26794
26795     // If we are in non-pic codegen mode, we allow the address of a global (with
26796     // an optional displacement) to be used with 'i'.
26797     GlobalAddressSDNode *GA = nullptr;
26798     int64_t Offset = 0;
26799
26800     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26801     while (1) {
26802       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26803         Offset += GA->getOffset();
26804         break;
26805       } else if (Op.getOpcode() == ISD::ADD) {
26806         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26807           Offset += C->getZExtValue();
26808           Op = Op.getOperand(0);
26809           continue;
26810         }
26811       } else if (Op.getOpcode() == ISD::SUB) {
26812         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26813           Offset += -C->getZExtValue();
26814           Op = Op.getOperand(0);
26815           continue;
26816         }
26817       }
26818
26819       // Otherwise, this isn't something we can handle, reject it.
26820       return;
26821     }
26822
26823     const GlobalValue *GV = GA->getGlobal();
26824     // If we require an extra load to get this address, as in PIC mode, we
26825     // can't accept it.
26826     if (isGlobalStubReference(
26827             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26828       return;
26829
26830     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26831                                         GA->getValueType(0), Offset);
26832     break;
26833   }
26834   }
26835
26836   if (Result.getNode()) {
26837     Ops.push_back(Result);
26838     return;
26839   }
26840   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26841 }
26842
26843 std::pair<unsigned, const TargetRegisterClass *>
26844 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26845                                                 StringRef Constraint,
26846                                                 MVT VT) const {
26847   // First, see if this is a constraint that directly corresponds to an LLVM
26848   // register class.
26849   if (Constraint.size() == 1) {
26850     // GCC Constraint Letters
26851     switch (Constraint[0]) {
26852     default: break;
26853       // TODO: Slight differences here in allocation order and leaving
26854       // RIP in the class. Do they matter any more here than they do
26855       // in the normal allocation?
26856     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26857       if (Subtarget->is64Bit()) {
26858         if (VT == MVT::i32 || VT == MVT::f32)
26859           return std::make_pair(0U, &X86::GR32RegClass);
26860         if (VT == MVT::i16)
26861           return std::make_pair(0U, &X86::GR16RegClass);
26862         if (VT == MVT::i8 || VT == MVT::i1)
26863           return std::make_pair(0U, &X86::GR8RegClass);
26864         if (VT == MVT::i64 || VT == MVT::f64)
26865           return std::make_pair(0U, &X86::GR64RegClass);
26866         break;
26867       }
26868       // 32-bit fallthrough
26869     case 'Q':   // Q_REGS
26870       if (VT == MVT::i32 || VT == MVT::f32)
26871         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26872       if (VT == MVT::i16)
26873         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26874       if (VT == MVT::i8 || VT == MVT::i1)
26875         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26876       if (VT == MVT::i64)
26877         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26878       break;
26879     case 'r':   // GENERAL_REGS
26880     case 'l':   // INDEX_REGS
26881       if (VT == MVT::i8 || VT == MVT::i1)
26882         return std::make_pair(0U, &X86::GR8RegClass);
26883       if (VT == MVT::i16)
26884         return std::make_pair(0U, &X86::GR16RegClass);
26885       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26886         return std::make_pair(0U, &X86::GR32RegClass);
26887       return std::make_pair(0U, &X86::GR64RegClass);
26888     case 'R':   // LEGACY_REGS
26889       if (VT == MVT::i8 || VT == MVT::i1)
26890         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26891       if (VT == MVT::i16)
26892         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26893       if (VT == MVT::i32 || !Subtarget->is64Bit())
26894         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26895       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26896     case 'f':  // FP Stack registers.
26897       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26898       // value to the correct fpstack register class.
26899       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26900         return std::make_pair(0U, &X86::RFP32RegClass);
26901       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26902         return std::make_pair(0U, &X86::RFP64RegClass);
26903       return std::make_pair(0U, &X86::RFP80RegClass);
26904     case 'y':   // MMX_REGS if MMX allowed.
26905       if (!Subtarget->hasMMX()) break;
26906       return std::make_pair(0U, &X86::VR64RegClass);
26907     case 'Y':   // SSE_REGS if SSE2 allowed
26908       if (!Subtarget->hasSSE2()) break;
26909       // FALL THROUGH.
26910     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26911       if (!Subtarget->hasSSE1()) break;
26912
26913       switch (VT.SimpleTy) {
26914       default: break;
26915       // Scalar SSE types.
26916       case MVT::f32:
26917       case MVT::i32:
26918         return std::make_pair(0U, &X86::FR32RegClass);
26919       case MVT::f64:
26920       case MVT::i64:
26921         return std::make_pair(0U, &X86::FR64RegClass);
26922       // Vector types.
26923       case MVT::v16i8:
26924       case MVT::v8i16:
26925       case MVT::v4i32:
26926       case MVT::v2i64:
26927       case MVT::v4f32:
26928       case MVT::v2f64:
26929         return std::make_pair(0U, &X86::VR128RegClass);
26930       // AVX types.
26931       case MVT::v32i8:
26932       case MVT::v16i16:
26933       case MVT::v8i32:
26934       case MVT::v4i64:
26935       case MVT::v8f32:
26936       case MVT::v4f64:
26937         return std::make_pair(0U, &X86::VR256RegClass);
26938       case MVT::v8f64:
26939       case MVT::v16f32:
26940       case MVT::v16i32:
26941       case MVT::v8i64:
26942         return std::make_pair(0U, &X86::VR512RegClass);
26943       }
26944       break;
26945     }
26946   }
26947
26948   // Use the default implementation in TargetLowering to convert the register
26949   // constraint into a member of a register class.
26950   std::pair<unsigned, const TargetRegisterClass*> Res;
26951   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26952
26953   // Not found as a standard register?
26954   if (!Res.second) {
26955     // Map st(0) -> st(7) -> ST0
26956     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26957         tolower(Constraint[1]) == 's' &&
26958         tolower(Constraint[2]) == 't' &&
26959         Constraint[3] == '(' &&
26960         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26961         Constraint[5] == ')' &&
26962         Constraint[6] == '}') {
26963
26964       Res.first = X86::FP0+Constraint[4]-'0';
26965       Res.second = &X86::RFP80RegClass;
26966       return Res;
26967     }
26968
26969     // GCC allows "st(0)" to be called just plain "st".
26970     if (StringRef("{st}").equals_lower(Constraint)) {
26971       Res.first = X86::FP0;
26972       Res.second = &X86::RFP80RegClass;
26973       return Res;
26974     }
26975
26976     // flags -> EFLAGS
26977     if (StringRef("{flags}").equals_lower(Constraint)) {
26978       Res.first = X86::EFLAGS;
26979       Res.second = &X86::CCRRegClass;
26980       return Res;
26981     }
26982
26983     // 'A' means EAX + EDX.
26984     if (Constraint == "A") {
26985       Res.first = X86::EAX;
26986       Res.second = &X86::GR32_ADRegClass;
26987       return Res;
26988     }
26989     return Res;
26990   }
26991
26992   // Otherwise, check to see if this is a register class of the wrong value
26993   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26994   // turn into {ax},{dx}.
26995   // MVT::Other is used to specify clobber names.
26996   if (Res.second->hasType(VT) || VT == MVT::Other)
26997     return Res;   // Correct type already, nothing to do.
26998
26999   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
27000   // return "eax". This should even work for things like getting 64bit integer
27001   // registers when given an f64 type.
27002   const TargetRegisterClass *Class = Res.second;
27003   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
27004       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
27005     unsigned Size = VT.getSizeInBits();
27006     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
27007                                   : Size == 16 ? MVT::i16
27008                                   : Size == 32 ? MVT::i32
27009                                   : Size == 64 ? MVT::i64
27010                                   : MVT::Other;
27011     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
27012     if (DestReg > 0) {
27013       Res.first = DestReg;
27014       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
27015                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
27016                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
27017                  : &X86::GR64RegClass;
27018       assert(Res.second->contains(Res.first) && "Register in register class");
27019     } else {
27020       // No register found/type mismatch.
27021       Res.first = 0;
27022       Res.second = nullptr;
27023     }
27024   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
27025              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
27026              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
27027              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
27028              Class == &X86::VR512RegClass) {
27029     // Handle references to XMM physical registers that got mapped into the
27030     // wrong class.  This can happen with constraints like {xmm0} where the
27031     // target independent register mapper will just pick the first match it can
27032     // find, ignoring the required type.
27033
27034     if (VT == MVT::f32 || VT == MVT::i32)
27035       Res.second = &X86::FR32RegClass;
27036     else if (VT == MVT::f64 || VT == MVT::i64)
27037       Res.second = &X86::FR64RegClass;
27038     else if (X86::VR128RegClass.hasType(VT))
27039       Res.second = &X86::VR128RegClass;
27040     else if (X86::VR256RegClass.hasType(VT))
27041       Res.second = &X86::VR256RegClass;
27042     else if (X86::VR512RegClass.hasType(VT))
27043       Res.second = &X86::VR512RegClass;
27044     else {
27045       // Type mismatch and not a clobber: Return an error;
27046       Res.first = 0;
27047       Res.second = nullptr;
27048     }
27049   }
27050
27051   return Res;
27052 }
27053
27054 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
27055                                             const AddrMode &AM, Type *Ty,
27056                                             unsigned AS) const {
27057   // Scaling factors are not free at all.
27058   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
27059   // will take 2 allocations in the out of order engine instead of 1
27060   // for plain addressing mode, i.e. inst (reg1).
27061   // E.g.,
27062   // vaddps (%rsi,%drx), %ymm0, %ymm1
27063   // Requires two allocations (one for the load, one for the computation)
27064   // whereas:
27065   // vaddps (%rsi), %ymm0, %ymm1
27066   // Requires just 1 allocation, i.e., freeing allocations for other operations
27067   // and having less micro operations to execute.
27068   //
27069   // For some X86 architectures, this is even worse because for instance for
27070   // stores, the complex addressing mode forces the instruction to use the
27071   // "load" ports instead of the dedicated "store" port.
27072   // E.g., on Haswell:
27073   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
27074   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
27075   if (isLegalAddressingMode(DL, AM, Ty, AS))
27076     // Scale represents reg2 * scale, thus account for 1
27077     // as soon as we use a second register.
27078     return AM.Scale != 0;
27079   return -1;
27080 }
27081
27082 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
27083   // Integer division on x86 is expensive. However, when aggressively optimizing
27084   // for code size, we prefer to use a div instruction, as it is usually smaller
27085   // than the alternative sequence.
27086   // The exception to this is vector division. Since x86 doesn't have vector
27087   // integer division, leaving the division as-is is a loss even in terms of
27088   // size, because it will have to be scalarized, while the alternative code
27089   // sequence can be performed in vector form.
27090   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
27091                                    Attribute::MinSize);
27092   return OptSize && !VT.isVector();
27093 }