CXX_FAST_TLS calling convention: performance improvement for x86-64.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86ShuffleDecodeConstantPool.h"
22 #include "X86TargetMachine.h"
23 #include "X86TargetObjectFile.h"
24 #include "llvm/ADT/SmallBitVector.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/Analysis/EHPersonalities.h"
30 #include "llvm/CodeGen/IntrinsicLowering.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/WinEHFuncInfo.h"
38 #include "llvm/IR/CallSite.h"
39 #include "llvm/IR/CallingConv.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalAlias.h"
44 #include "llvm/IR/GlobalVariable.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/Intrinsics.h"
47 #include "llvm/MC/MCAsmInfo.h"
48 #include "llvm/MC/MCContext.h"
49 #include "llvm/MC/MCExpr.h"
50 #include "llvm/MC/MCSymbol.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Target/TargetOptions.h"
56 #include "X86IntrinsicsInfo.h"
57 #include <bitset>
58 #include <numeric>
59 #include <cctype>
60 using namespace llvm;
61
62 #define DEBUG_TYPE "x86-isel"
63
64 STATISTIC(NumTailCalls, "Number of tail calls");
65
66 static cl::opt<bool> ExperimentalVectorWideningLegalization(
67     "x86-experimental-vector-widening-legalization", cl::init(false),
68     cl::desc("Enable an experimental vector type legalization through widening "
69              "rather than promotion."),
70     cl::Hidden);
71
72 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
73                                      const X86Subtarget &STI)
74     : TargetLowering(TM), Subtarget(&STI) {
75   X86ScalarSSEf64 = Subtarget->hasSSE2();
76   X86ScalarSSEf32 = Subtarget->hasSSE1();
77   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
78
79   // Set up the TargetLowering object.
80
81   // X86 is weird. It always uses i8 for shift amounts and setcc results.
82   setBooleanContents(ZeroOrOneBooleanContent);
83   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
84   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
85
86   // For 64-bit, since we have so many registers, use the ILP scheduler.
87   // For 32-bit, use the register pressure specific scheduling.
88   // For Atom, always use ILP scheduling.
89   if (Subtarget->isAtom())
90     setSchedulingPreference(Sched::ILP);
91   else if (Subtarget->is64Bit())
92     setSchedulingPreference(Sched::ILP);
93   else
94     setSchedulingPreference(Sched::RegPressure);
95   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
96   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
97
98   // Bypass expensive divides on Atom when compiling with O2.
99   if (TM.getOptLevel() >= CodeGenOpt::Default) {
100     if (Subtarget->hasSlowDivide32())
101       addBypassSlowDiv(32, 8);
102     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
103       addBypassSlowDiv(64, 16);
104   }
105
106   if (Subtarget->isTargetKnownWindowsMSVC()) {
107     // Setup Windows compiler runtime calls.
108     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
109     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
110     setLibcallName(RTLIB::SREM_I64, "_allrem");
111     setLibcallName(RTLIB::UREM_I64, "_aullrem");
112     setLibcallName(RTLIB::MUL_I64, "_allmul");
113     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
114     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
115     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
116     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
117     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
118   }
119
120   if (Subtarget->isTargetDarwin()) {
121     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
122     setUseUnderscoreSetJmp(false);
123     setUseUnderscoreLongJmp(false);
124   } else if (Subtarget->isTargetWindowsGNU()) {
125     // MS runtime is weird: it exports _setjmp, but longjmp!
126     setUseUnderscoreSetJmp(true);
127     setUseUnderscoreLongJmp(false);
128   } else {
129     setUseUnderscoreSetJmp(true);
130     setUseUnderscoreLongJmp(true);
131   }
132
133   // Set up the register classes.
134   addRegisterClass(MVT::i8, &X86::GR8RegClass);
135   addRegisterClass(MVT::i16, &X86::GR16RegClass);
136   addRegisterClass(MVT::i32, &X86::GR32RegClass);
137   if (Subtarget->is64Bit())
138     addRegisterClass(MVT::i64, &X86::GR64RegClass);
139
140   for (MVT VT : MVT::integer_valuetypes())
141     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
142
143   // We don't accept any truncstore of integer registers.
144   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
145   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
146   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
147   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
148   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
149   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
150
151   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
152
153   // SETOEQ and SETUNE require checking two conditions.
154   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
155   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
156   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
157   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
158   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
159   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
160
161   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
162   // operation.
163   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
164   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
165   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
166
167   if (Subtarget->is64Bit()) {
168     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512())
169       // f32/f64 are legal, f80 is custom.
170       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
171     else
172       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
173     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
174   } else if (!Subtarget->useSoftFloat()) {
175     // We have an algorithm for SSE2->double, and we turn this into a
176     // 64-bit FILD followed by conditional FADD for other targets.
177     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
178     // We have an algorithm for SSE2, and we turn this into a 64-bit
179     // FILD or VCVTUSI2SS/SD for other targets.
180     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
181   }
182
183   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
184   // this operation.
185   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
186   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
187
188   if (!Subtarget->useSoftFloat()) {
189     // SSE has no i16 to fp conversion, only i32
190     if (X86ScalarSSEf32) {
191       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
192       // f32 and f64 cases are Legal, f80 case is not
193       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
194     } else {
195       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
196       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
197     }
198   } else {
199     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
200     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
201   }
202
203   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
204   // this operation.
205   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
206   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
207
208   if (!Subtarget->useSoftFloat()) {
209     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
210     // are Legal, f80 is custom lowered.
211     setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
212     setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
213
214     if (X86ScalarSSEf32) {
215       setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
216       // f32 and f64 cases are Legal, f80 case is not
217       setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
218     } else {
219       setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
220       setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
221     }
222   } else {
223     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
224     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Expand);
225     setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Expand);
226   }
227
228   // Handle FP_TO_UINT by promoting the destination to a larger signed
229   // conversion.
230   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
231   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
232   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
233
234   if (Subtarget->is64Bit()) {
235     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
236       // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
237       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
238       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Custom);
239     } else {
240       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
241       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Expand);
242     }
243   } else if (!Subtarget->useSoftFloat()) {
244     // Since AVX is a superset of SSE3, only check for SSE here.
245     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
246       // Expand FP_TO_UINT into a select.
247       // FIXME: We would like to use a Custom expander here eventually to do
248       // the optimal thing for SSE vs. the default expansion in the legalizer.
249       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
250     else
251       // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
252       // With SSE3 we can use fisttpll to convert to a signed i64; without
253       // SSE, we're stuck with a fistpll.
254       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
255
256     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
257   }
258
259   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
260   if (!X86ScalarSSEf64) {
261     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
262     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
263     if (Subtarget->is64Bit()) {
264       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
265       // Without SSE, i64->f64 goes through memory.
266       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
267     }
268   } else if (!Subtarget->is64Bit())
269     setOperationAction(ISD::BITCAST      , MVT::i64  , Custom);
270
271   // Scalar integer divide and remainder are lowered to use operations that
272   // produce two results, to match the available instructions. This exposes
273   // the two-result form to trivial CSE, which is able to combine x/y and x%y
274   // into a single instruction.
275   //
276   // Scalar integer multiply-high is also lowered to use two-result
277   // operations, to match the available instructions. However, plain multiply
278   // (low) operations are left as Legal, as there are single-result
279   // instructions for this in x86. Using the two-result multiply instructions
280   // when both high and low results are needed must be arranged by dagcombine.
281   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
282     setOperationAction(ISD::MULHS, VT, Expand);
283     setOperationAction(ISD::MULHU, VT, Expand);
284     setOperationAction(ISD::SDIV, VT, Expand);
285     setOperationAction(ISD::UDIV, VT, Expand);
286     setOperationAction(ISD::SREM, VT, Expand);
287     setOperationAction(ISD::UREM, VT, Expand);
288
289     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
290     setOperationAction(ISD::ADDC, VT, Custom);
291     setOperationAction(ISD::ADDE, VT, Custom);
292     setOperationAction(ISD::SUBC, VT, Custom);
293     setOperationAction(ISD::SUBE, VT, Custom);
294   }
295
296   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
297   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
298   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
299   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
300   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
301   setOperationAction(ISD::BR_CC            , MVT::f128,  Expand);
302   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
303   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
304   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
305   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
306   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
307   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
309   setOperationAction(ISD::SELECT_CC        , MVT::f128,  Expand);
310   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
311   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
312   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
313   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
314   if (Subtarget->is64Bit())
315     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
316   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
317   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
318   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
319   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
320
321   if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
322     // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
323     // is. We should promote the value to 64-bits to solve this.
324     // This is what the CRT headers do - `fmodf` is an inline header
325     // function casting to f64 and calling `fmod`.
326     setOperationAction(ISD::FREM           , MVT::f32  , Promote);
327   } else {
328     setOperationAction(ISD::FREM           , MVT::f32  , Expand);
329   }
330
331   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
332   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
333   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
334
335   // Promote the i8 variants and force them on up to i32 which has a shorter
336   // encoding.
337   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
338   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
339   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
340   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
341   if (Subtarget->hasBMI()) {
342     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
343     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
344     if (Subtarget->is64Bit())
345       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
346   } else {
347     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
348     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
349     if (Subtarget->is64Bit())
350       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
351   }
352
353   if (Subtarget->hasLZCNT()) {
354     // When promoting the i8 variants, force them to i32 for a shorter
355     // encoding.
356     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
357     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
358     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
359     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
360     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
361     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
362     if (Subtarget->is64Bit())
363       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
364   } else {
365     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
366     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
367     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
368     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
369     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
370     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
371     if (Subtarget->is64Bit()) {
372       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
373       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
374     }
375   }
376
377   // Special handling for half-precision floating point conversions.
378   // If we don't have F16C support, then lower half float conversions
379   // into library calls.
380   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
381     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
382     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
383   }
384
385   // There's never any support for operations beyond MVT::f32.
386   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
387   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
388   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
389   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
390
391   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
392   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
393   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
394   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
395   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
396   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
397
398   if (Subtarget->hasPOPCNT()) {
399     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
400   } else {
401     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
402     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
403     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
404     if (Subtarget->is64Bit())
405       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
406   }
407
408   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
409
410   if (!Subtarget->hasMOVBE())
411     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
412
413   // These should be promoted to a larger select which is supported.
414   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
415   // X86 wants to expand cmov itself.
416   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
417   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
418   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
419   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
420   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
421   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
422   setOperationAction(ISD::SELECT          , MVT::f128 , Custom);
423   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
424   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
425   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
426   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
427   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
428   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
429   setOperationAction(ISD::SETCC           , MVT::f128 , Custom);
430   setOperationAction(ISD::SETCCE          , MVT::i8   , Custom);
431   setOperationAction(ISD::SETCCE          , MVT::i16  , Custom);
432   setOperationAction(ISD::SETCCE          , MVT::i32  , Custom);
433   if (Subtarget->is64Bit()) {
434     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
435     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
436     setOperationAction(ISD::SETCCE        , MVT::i64  , Custom);
437   }
438   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
439   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
440   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
441   // support continuation, user-level threading, and etc.. As a result, no
442   // other SjLj exception interfaces are implemented and please don't build
443   // your own exception handling based on them.
444   // LLVM/Clang supports zero-cost DWARF exception handling.
445   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
446   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
447
448   // Darwin ABI issue.
449   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
450   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
451   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
452   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
453   if (Subtarget->is64Bit())
454     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
455   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
456   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
457   if (Subtarget->is64Bit()) {
458     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
459     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
460     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
461     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
462     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
463   }
464   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
465   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
466   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
467   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
468   if (Subtarget->is64Bit()) {
469     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
470     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
471     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
472   }
473
474   if (Subtarget->hasSSE1())
475     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
476
477   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
478
479   // Expand certain atomics
480   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
481     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
482     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
483     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
484   }
485
486   if (Subtarget->hasCmpxchg16b()) {
487     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
488   }
489
490   // FIXME - use subtarget debug flags
491   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
492       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
493     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
494   }
495
496   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
497   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
498
499   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
500   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
501
502   setOperationAction(ISD::TRAP, MVT::Other, Legal);
503   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
504
505   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
506   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
507   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
508   if (Subtarget->is64Bit()) {
509     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
510     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
511   } else {
512     // TargetInfo::CharPtrBuiltinVaList
513     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
514     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
515   }
516
517   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
518   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
519
520   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
521
522   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
523   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
524   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
525
526   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
527     // f32 and f64 use SSE.
528     // Set up the FP register classes.
529     addRegisterClass(MVT::f32, &X86::FR32RegClass);
530     addRegisterClass(MVT::f64, &X86::FR64RegClass);
531
532     // Use ANDPD to simulate FABS.
533     setOperationAction(ISD::FABS , MVT::f64, Custom);
534     setOperationAction(ISD::FABS , MVT::f32, Custom);
535
536     // Use XORP to simulate FNEG.
537     setOperationAction(ISD::FNEG , MVT::f64, Custom);
538     setOperationAction(ISD::FNEG , MVT::f32, Custom);
539
540     // Use ANDPD and ORPD to simulate FCOPYSIGN.
541     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
542     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
543
544     // Lower this to FGETSIGNx86 plus an AND.
545     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
546     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
547
548     // We don't support sin/cos/fmod
549     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
550     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
551     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
552     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
553     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
554     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
555
556     // Expand FP immediates into loads from the stack, except for the special
557     // cases we handle.
558     addLegalFPImmediate(APFloat(+0.0)); // xorpd
559     addLegalFPImmediate(APFloat(+0.0f)); // xorps
560   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
561     // Use SSE for f32, x87 for f64.
562     // Set up the FP register classes.
563     addRegisterClass(MVT::f32, &X86::FR32RegClass);
564     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
565
566     // Use ANDPS to simulate FABS.
567     setOperationAction(ISD::FABS , MVT::f32, Custom);
568
569     // Use XORP to simulate FNEG.
570     setOperationAction(ISD::FNEG , MVT::f32, Custom);
571
572     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
573
574     // Use ANDPS and ORPS to simulate FCOPYSIGN.
575     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
576     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
577
578     // We don't support sin/cos/fmod
579     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
580     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
581     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
582
583     // Special cases we handle for FP constants.
584     addLegalFPImmediate(APFloat(+0.0f)); // xorps
585     addLegalFPImmediate(APFloat(+0.0)); // FLD0
586     addLegalFPImmediate(APFloat(+1.0)); // FLD1
587     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
588     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
589
590     if (!TM.Options.UnsafeFPMath) {
591       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
592       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
593       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
594     }
595   } else if (!Subtarget->useSoftFloat()) {
596     // f32 and f64 in x87.
597     // Set up the FP register classes.
598     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
599     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
600
601     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
602     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
603     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
604     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
605
606     if (!TM.Options.UnsafeFPMath) {
607       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
608       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
609       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
610       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
611       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
612       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
613     }
614     addLegalFPImmediate(APFloat(+0.0)); // FLD0
615     addLegalFPImmediate(APFloat(+1.0)); // FLD1
616     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
617     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
618     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
619     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
620     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
621     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
622   }
623
624   // We don't support FMA.
625   setOperationAction(ISD::FMA, MVT::f64, Expand);
626   setOperationAction(ISD::FMA, MVT::f32, Expand);
627
628   // Long double always uses X87, except f128 in MMX.
629   if (!Subtarget->useSoftFloat()) {
630     if (Subtarget->is64Bit() && Subtarget->hasMMX()) {
631       addRegisterClass(MVT::f128, &X86::FR128RegClass);
632       ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
633       setOperationAction(ISD::FABS , MVT::f128, Custom);
634       setOperationAction(ISD::FNEG , MVT::f128, Custom);
635       setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
636     }
637
638     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
639     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
640     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
641     {
642       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
643       addLegalFPImmediate(TmpFlt);  // FLD0
644       TmpFlt.changeSign();
645       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
646
647       bool ignored;
648       APFloat TmpFlt2(+1.0);
649       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
650                       &ignored);
651       addLegalFPImmediate(TmpFlt2);  // FLD1
652       TmpFlt2.changeSign();
653       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
654     }
655
656     if (!TM.Options.UnsafeFPMath) {
657       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
658       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
659       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
660     }
661
662     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
663     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
664     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
665     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
666     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
667     setOperationAction(ISD::FMA, MVT::f80, Expand);
668   }
669
670   // Always use a library call for pow.
671   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
672   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
673   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
674
675   setOperationAction(ISD::FLOG, MVT::f80, Expand);
676   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
677   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
678   setOperationAction(ISD::FEXP, MVT::f80, Expand);
679   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
680   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
681   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
682
683   // First set operation action for all vector types to either promote
684   // (for widening) or expand (for scalarization). Then we will selectively
685   // turn on ones that can be effectively codegen'd.
686   for (MVT VT : MVT::vector_valuetypes()) {
687     setOperationAction(ISD::ADD , VT, Expand);
688     setOperationAction(ISD::SUB , VT, Expand);
689     setOperationAction(ISD::FADD, VT, Expand);
690     setOperationAction(ISD::FNEG, VT, Expand);
691     setOperationAction(ISD::FSUB, VT, Expand);
692     setOperationAction(ISD::MUL , VT, Expand);
693     setOperationAction(ISD::FMUL, VT, Expand);
694     setOperationAction(ISD::SDIV, VT, Expand);
695     setOperationAction(ISD::UDIV, VT, Expand);
696     setOperationAction(ISD::FDIV, VT, Expand);
697     setOperationAction(ISD::SREM, VT, Expand);
698     setOperationAction(ISD::UREM, VT, Expand);
699     setOperationAction(ISD::LOAD, VT, Expand);
700     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
701     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
702     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
703     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
704     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
705     setOperationAction(ISD::FABS, VT, Expand);
706     setOperationAction(ISD::FSIN, VT, Expand);
707     setOperationAction(ISD::FSINCOS, VT, Expand);
708     setOperationAction(ISD::FCOS, VT, Expand);
709     setOperationAction(ISD::FSINCOS, VT, Expand);
710     setOperationAction(ISD::FREM, VT, Expand);
711     setOperationAction(ISD::FMA,  VT, Expand);
712     setOperationAction(ISD::FPOWI, VT, Expand);
713     setOperationAction(ISD::FSQRT, VT, Expand);
714     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
715     setOperationAction(ISD::FFLOOR, VT, Expand);
716     setOperationAction(ISD::FCEIL, VT, Expand);
717     setOperationAction(ISD::FTRUNC, VT, Expand);
718     setOperationAction(ISD::FRINT, VT, Expand);
719     setOperationAction(ISD::FNEARBYINT, VT, Expand);
720     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
721     setOperationAction(ISD::MULHS, VT, Expand);
722     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
723     setOperationAction(ISD::MULHU, VT, Expand);
724     setOperationAction(ISD::SDIVREM, VT, Expand);
725     setOperationAction(ISD::UDIVREM, VT, Expand);
726     setOperationAction(ISD::FPOW, VT, Expand);
727     setOperationAction(ISD::CTPOP, VT, Expand);
728     setOperationAction(ISD::CTTZ, VT, Expand);
729     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
730     setOperationAction(ISD::CTLZ, VT, Expand);
731     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
732     setOperationAction(ISD::SHL, VT, Expand);
733     setOperationAction(ISD::SRA, VT, Expand);
734     setOperationAction(ISD::SRL, VT, Expand);
735     setOperationAction(ISD::ROTL, VT, Expand);
736     setOperationAction(ISD::ROTR, VT, Expand);
737     setOperationAction(ISD::BSWAP, VT, Expand);
738     setOperationAction(ISD::SETCC, VT, Expand);
739     setOperationAction(ISD::FLOG, VT, Expand);
740     setOperationAction(ISD::FLOG2, VT, Expand);
741     setOperationAction(ISD::FLOG10, VT, Expand);
742     setOperationAction(ISD::FEXP, VT, Expand);
743     setOperationAction(ISD::FEXP2, VT, Expand);
744     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
745     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
746     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
747     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
748     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
749     setOperationAction(ISD::TRUNCATE, VT, Expand);
750     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
751     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
752     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
753     setOperationAction(ISD::VSELECT, VT, Expand);
754     setOperationAction(ISD::SELECT_CC, VT, Expand);
755     for (MVT InnerVT : MVT::vector_valuetypes()) {
756       setTruncStoreAction(InnerVT, VT, Expand);
757
758       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
759       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
760
761       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
762       // types, we have to deal with them whether we ask for Expansion or not.
763       // Setting Expand causes its own optimisation problems though, so leave
764       // them legal.
765       if (VT.getVectorElementType() == MVT::i1)
766         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
767
768       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
769       // split/scalarized right now.
770       if (VT.getVectorElementType() == MVT::f16)
771         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
772     }
773   }
774
775   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
776   // with -msoft-float, disable use of MMX as well.
777   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
778     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
779     // No operations on x86mmx supported, everything uses intrinsics.
780   }
781
782   // MMX-sized vectors (other than x86mmx) are expected to be expanded
783   // into smaller operations.
784   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
785     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
786     setOperationAction(ISD::AND,                MMXTy,      Expand);
787     setOperationAction(ISD::OR,                 MMXTy,      Expand);
788     setOperationAction(ISD::XOR,                MMXTy,      Expand);
789     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
790     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
791     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
792   }
793   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
794
795   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
796     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
797
798     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
799     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
800     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
801     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
802     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
803     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
804     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
805     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
806     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
807     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
808     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
809     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
810     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
811     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
812   }
813
814   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
815     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
816
817     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
818     // registers cannot be used even for integer operations.
819     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
820     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
821     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
822     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
823
824     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
825     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
826     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
827     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
828     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
829     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
830     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
831     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
832     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
833     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
834     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
835     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
836     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
837     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
838     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
839     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
840     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
841     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
842     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
843     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
844     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
845     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
846     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
847
848     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
849     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
850     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
851     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
852
853     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
854     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
855     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
856     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
857
858     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
859     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
860     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
861     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
862     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
863
864     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
865     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
866     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
867     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
868
869     setOperationAction(ISD::CTTZ,               MVT::v16i8, Custom);
870     setOperationAction(ISD::CTTZ,               MVT::v8i16, Custom);
871     setOperationAction(ISD::CTTZ,               MVT::v4i32, Custom);
872     // ISD::CTTZ v2i64 - scalarization is faster.
873     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v16i8, Custom);
874     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v8i16, Custom);
875     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v4i32, Custom);
876     // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
877
878     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
879     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
880       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
881       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
882       setOperationAction(ISD::VSELECT,            VT, Custom);
883       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
884     }
885
886     // We support custom legalizing of sext and anyext loads for specific
887     // memory vector types which we can load as a scalar (or sequence of
888     // scalars) and extend in-register to a legal 128-bit vector type. For sext
889     // loads these must work with a single scalar load.
890     for (MVT VT : MVT::integer_vector_valuetypes()) {
891       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
892       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
893       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
894       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
895       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
896       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
897       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
898       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
899       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
900     }
901
902     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
903     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
904     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
905     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
906     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
907     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
908     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
909     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
910
911     if (Subtarget->is64Bit()) {
912       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
913       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
914     }
915
916     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
917     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
918       setOperationAction(ISD::AND,    VT, Promote);
919       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
920       setOperationAction(ISD::OR,     VT, Promote);
921       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
922       setOperationAction(ISD::XOR,    VT, Promote);
923       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
924       setOperationAction(ISD::LOAD,   VT, Promote);
925       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
926       setOperationAction(ISD::SELECT, VT, Promote);
927       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
928     }
929
930     // Custom lower v2i64 and v2f64 selects.
931     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
932     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
933     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
934     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
935
936     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
937     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
938
939     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
940
941     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
942     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
943     // As there is no 64-bit GPR available, we need build a special custom
944     // sequence to convert from v2i32 to v2f32.
945     if (!Subtarget->is64Bit())
946       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
947
948     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
949     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
950
951     for (MVT VT : MVT::fp_vector_valuetypes())
952       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
953
954     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
955     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
956     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
957   }
958
959   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
960     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
961       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
962       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
963       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
964       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
965       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
966     }
967
968     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
969     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
970     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
971     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
972     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
973     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
974     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
975     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
976
977     // FIXME: Do we need to handle scalar-to-vector here?
978     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
979
980     // We directly match byte blends in the backend as they match the VSELECT
981     // condition form.
982     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
983
984     // SSE41 brings specific instructions for doing vector sign extend even in
985     // cases where we don't have SRA.
986     for (MVT VT : MVT::integer_vector_valuetypes()) {
987       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
988       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
989       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
990     }
991
992     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
993     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
994     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
995     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
996     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
997     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
998     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
999
1000     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
1001     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
1002     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
1003     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1004     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1005     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1006
1007     // i8 and i16 vectors are custom because the source register and source
1008     // source memory operand types are not the same width.  f32 vectors are
1009     // custom since the immediate controlling the insert encodes additional
1010     // information.
1011     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1012     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1013     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1014     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1015
1016     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1017     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1018     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1019     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1020
1021     // FIXME: these should be Legal, but that's only for the case where
1022     // the index is constant.  For now custom expand to deal with that.
1023     if (Subtarget->is64Bit()) {
1024       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1025       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1026     }
1027   }
1028
1029   if (Subtarget->hasSSE2()) {
1030     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1031     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1032     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1033
1034     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1035     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1036
1037     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1038     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1039
1040     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1041     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1042
1043     // In the customized shift lowering, the legal cases in AVX2 will be
1044     // recognized.
1045     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1046     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1047
1048     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1049     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1050
1051     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1052     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1053   }
1054
1055   if (Subtarget->hasXOP()) {
1056     setOperationAction(ISD::ROTL,              MVT::v16i8, Custom);
1057     setOperationAction(ISD::ROTL,              MVT::v8i16, Custom);
1058     setOperationAction(ISD::ROTL,              MVT::v4i32, Custom);
1059     setOperationAction(ISD::ROTL,              MVT::v2i64, Custom);
1060     setOperationAction(ISD::ROTL,              MVT::v32i8, Custom);
1061     setOperationAction(ISD::ROTL,              MVT::v16i16, Custom);
1062     setOperationAction(ISD::ROTL,              MVT::v8i32, Custom);
1063     setOperationAction(ISD::ROTL,              MVT::v4i64, Custom);
1064   }
1065
1066   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1067     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1068     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1069     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1070     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1071     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1072     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1073
1074     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1075     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1076     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1077
1078     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1079     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1080     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1081     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1082     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1083     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1084     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1085     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1086     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1087     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1088     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1089     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1090
1091     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1092     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1093     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1094     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1095     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1096     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1097     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1098     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1099     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1100     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1101     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1102     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1103
1104     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1105     // even though v8i16 is a legal type.
1106     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1107     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1108     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1109
1110     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1111     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1112     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1113
1114     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1115     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1116
1117     for (MVT VT : MVT::fp_vector_valuetypes())
1118       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1119
1120     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1121     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1122
1123     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1124     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1125
1126     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1127     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1128
1129     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1130     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1131     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1132     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1133
1134     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1135     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1136     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1137
1138     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1139     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1140     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1141     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1142     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1143     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1144     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1145     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1146     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1147     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1148     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1149     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1150
1151     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1152     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1153     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1154     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1155
1156     setOperationAction(ISD::CTTZ,              MVT::v32i8, Custom);
1157     setOperationAction(ISD::CTTZ,              MVT::v16i16, Custom);
1158     setOperationAction(ISD::CTTZ,              MVT::v8i32, Custom);
1159     setOperationAction(ISD::CTTZ,              MVT::v4i64, Custom);
1160     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v32i8, Custom);
1161     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v16i16, Custom);
1162     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v8i32, Custom);
1163     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v4i64, Custom);
1164
1165     if (Subtarget->hasAnyFMA()) {
1166       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1167       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1168       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1169       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1170       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1171       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1172     }
1173
1174     if (Subtarget->hasInt256()) {
1175       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1176       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1177       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1178       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1179
1180       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1181       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1182       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1183       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1184
1185       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1186       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1187       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1188       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1189
1190       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1191       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1192       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1193       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1194
1195       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1196       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1197       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1198       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1199       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1200       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1201       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1202       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1203       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1204       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1205       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1206       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1207
1208       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1209       // when we have a 256bit-wide blend with immediate.
1210       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1211
1212       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1213       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1214       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1215       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1216       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1217       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1218       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1219
1220       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1221       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1222       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1223       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1224       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1225       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1226     } else {
1227       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1228       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1229       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1230       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1231
1232       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1233       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1234       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1235       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1236
1237       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1238       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1239       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1240       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1241
1242       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1243       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1244       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1245       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1246       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1247       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1248       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1249       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1250       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1251       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1252       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1253       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1254     }
1255
1256     // In the customized shift lowering, the legal cases in AVX2 will be
1257     // recognized.
1258     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1259     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1260
1261     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1262     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1263
1264     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1265     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1266
1267     // Custom lower several nodes for 256-bit types.
1268     for (MVT VT : MVT::vector_valuetypes()) {
1269       if (VT.getScalarSizeInBits() >= 32) {
1270         setOperationAction(ISD::MLOAD,  VT, Legal);
1271         setOperationAction(ISD::MSTORE, VT, Legal);
1272       }
1273       // Extract subvector is special because the value type
1274       // (result) is 128-bit but the source is 256-bit wide.
1275       if (VT.is128BitVector()) {
1276         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1277       }
1278       // Do not attempt to custom lower other non-256-bit vectors
1279       if (!VT.is256BitVector())
1280         continue;
1281
1282       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1283       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1284       setOperationAction(ISD::VSELECT,            VT, Custom);
1285       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1286       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1287       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1288       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1289       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1290     }
1291
1292     if (Subtarget->hasInt256())
1293       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1294
1295     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1296     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1297       setOperationAction(ISD::AND,    VT, Promote);
1298       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1299       setOperationAction(ISD::OR,     VT, Promote);
1300       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1301       setOperationAction(ISD::XOR,    VT, Promote);
1302       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1303       setOperationAction(ISD::LOAD,   VT, Promote);
1304       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1305       setOperationAction(ISD::SELECT, VT, Promote);
1306       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1307     }
1308   }
1309
1310   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1311     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1312     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1313     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1314     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1315
1316     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1317     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1318     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1319
1320     for (MVT VT : MVT::fp_vector_valuetypes())
1321       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1322
1323     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1324     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1325     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1326     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1327     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1328     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1329     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1330     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1331     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1332     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1333     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1334     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1335
1336     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1337     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1338     setOperationAction(ISD::SELECT_CC,          MVT::i1,    Expand);
1339     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1340     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1341     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1342     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1343     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1344     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1345     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1346     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1347     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1348     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1349     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1350
1351     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1352     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1353     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1354     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1355     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1356     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1357     setOperationAction(ISD::FABS,               MVT::v16f32, Custom);
1358
1359     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1360     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1361     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1362     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1363     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1364     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1365     setOperationAction(ISD::FABS,               MVT::v8f64, Custom);
1366     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1367     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1368
1369     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1370     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1371     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1372     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1373     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1374     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1375     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1376     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1377     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1378     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1379     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1380     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1381     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1382     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1383     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1384     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1385
1386     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1387     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1388     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1389     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1390     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1391     if (Subtarget->hasVLX()){
1392       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1393       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1394       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1395       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1396       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1397
1398       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1399       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1400       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1401       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1402       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1403     } else {
1404       setOperationAction(ISD::MLOAD,    MVT::v8i32, Custom);
1405       setOperationAction(ISD::MLOAD,    MVT::v8f32, Custom);
1406       setOperationAction(ISD::MSTORE,   MVT::v8i32, Custom);
1407       setOperationAction(ISD::MSTORE,   MVT::v8f32, Custom);
1408     }
1409     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1410     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1411     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1412     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i1,  Custom);
1413     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v16i1, Custom);
1414     if (Subtarget->hasDQI()) {
1415       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1416       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1417
1418       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1419       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1420       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1421       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1422       if (Subtarget->hasVLX()) {
1423         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1424         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1425         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1426         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1427         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1428         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1429         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1430         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1431       }
1432     }
1433     if (Subtarget->hasVLX()) {
1434       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1435       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1436       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1437       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1438       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1439       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1440       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1441       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1442     }
1443     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1444     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1445     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1446     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1447     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1448     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1449     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1450     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1451     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1452     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1453     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1454     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1455     if (Subtarget->hasDQI()) {
1456       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1457       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1458     }
1459     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1460     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1461     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1462     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1463     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1464     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1465     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1466     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1467     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1468     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1469
1470     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1471     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1472     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1473     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1474     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1,   Custom);
1475
1476     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1477     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1478
1479     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1480
1481     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1482     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1483     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v16i1, Custom);
1484     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1485     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1486     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1487     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1488     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1489     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1490     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1491     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1492     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1493
1494     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1495     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1496     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1497     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1498     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1499     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1500     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1501     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1502
1503     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1504     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1505
1506     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1507     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1508
1509     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1510
1511     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1512     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1513
1514     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1515     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1516
1517     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1518     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1519
1520     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1521     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1522     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1523     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1524     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1525     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1526
1527     if (Subtarget->hasCDI()) {
1528       setOperationAction(ISD::CTLZ,             MVT::v8i64,  Legal);
1529       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1530       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64,  Expand);
1531       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Expand);
1532
1533       setOperationAction(ISD::CTLZ,             MVT::v8i16,  Custom);
1534       setOperationAction(ISD::CTLZ,             MVT::v16i8,  Custom);
1535       setOperationAction(ISD::CTLZ,             MVT::v16i16, Custom);
1536       setOperationAction(ISD::CTLZ,             MVT::v32i8,  Custom);
1537       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i16,  Expand);
1538       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i8,  Expand);
1539       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i16, Expand);
1540       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v32i8,  Expand);
1541
1542       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i64,  Custom);
1543       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v16i32, Custom);
1544
1545       if (Subtarget->hasVLX()) {
1546         setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1547         setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1548         setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1549         setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1550         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Expand);
1551         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Expand);
1552         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Expand);
1553         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Expand);
1554
1555         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1556         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1557         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1558         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1559       } else {
1560         setOperationAction(ISD::CTLZ,             MVT::v4i64, Custom);
1561         setOperationAction(ISD::CTLZ,             MVT::v8i32, Custom);
1562         setOperationAction(ISD::CTLZ,             MVT::v2i64, Custom);
1563         setOperationAction(ISD::CTLZ,             MVT::v4i32, Custom);
1564         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Expand);
1565         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Expand);
1566         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Expand);
1567         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Expand);
1568       }
1569     } // Subtarget->hasCDI()
1570
1571     if (Subtarget->hasDQI()) {
1572       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1573       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1574       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1575     }
1576     // Custom lower several nodes.
1577     for (MVT VT : MVT::vector_valuetypes()) {
1578       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1579       if (EltSize == 1) {
1580         setOperationAction(ISD::AND, VT, Legal);
1581         setOperationAction(ISD::OR,  VT, Legal);
1582         setOperationAction(ISD::XOR,  VT, Legal);
1583       }
1584       if ((VT.is128BitVector() || VT.is256BitVector()) && EltSize >= 32) {
1585         setOperationAction(ISD::MGATHER,  VT, Custom);
1586         setOperationAction(ISD::MSCATTER, VT, Custom);
1587       }
1588       // Extract subvector is special because the value type
1589       // (result) is 256/128-bit but the source is 512-bit wide.
1590       if (VT.is128BitVector() || VT.is256BitVector()) {
1591         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1592       }
1593       if (VT.getVectorElementType() == MVT::i1)
1594         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1595
1596       // Do not attempt to custom lower other non-512-bit vectors
1597       if (!VT.is512BitVector())
1598         continue;
1599
1600       if (EltSize >= 32) {
1601         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1602         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1603         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1604         setOperationAction(ISD::VSELECT,             VT, Legal);
1605         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1606         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1607         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1608         setOperationAction(ISD::MLOAD,               VT, Legal);
1609         setOperationAction(ISD::MSTORE,              VT, Legal);
1610         setOperationAction(ISD::MGATHER,  VT, Legal);
1611         setOperationAction(ISD::MSCATTER, VT, Custom);
1612       }
1613     }
1614     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1615       setOperationAction(ISD::SELECT, VT, Promote);
1616       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1617     }
1618   }// has  AVX-512
1619
1620   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1621     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1622     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1623
1624     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1625     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1626
1627     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1628     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1629     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1630     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1631     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1632     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1633     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1634     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1635     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1636     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1637     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1638     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1639     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1640     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i16, Custom);
1641     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i8, Custom);
1642     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1643     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1644     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i16, Custom);
1645     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i8, Custom);
1646     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1647     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1648     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1649     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1650     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1651     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1652     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1653     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1654     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1655     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i8, Custom);
1656     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1657     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1658     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1659     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1660     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i16, Custom);
1661     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i8, Custom);
1662     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1663     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1664     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1665     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1666     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1667     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i1, Custom);
1668     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i1, Custom);
1669
1670     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1671     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1672     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1673     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1674     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1675     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1676     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1677     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1678
1679     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1680     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1681     if (Subtarget->hasVLX())
1682       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1683
1684     if (Subtarget->hasCDI()) {
1685       setOperationAction(ISD::CTLZ,            MVT::v32i16, Custom);
1686       setOperationAction(ISD::CTLZ,            MVT::v64i8,  Custom);
1687       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Expand);
1688       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8,  Expand);
1689     }
1690
1691     for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1692       setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1693       setOperationAction(ISD::VSELECT,             VT, Legal);
1694       setOperationAction(ISD::SRL,                 VT, Custom);
1695       setOperationAction(ISD::SHL,                 VT, Custom);
1696       setOperationAction(ISD::SRA,                 VT, Custom);
1697
1698       setOperationAction(ISD::AND,    VT, Promote);
1699       AddPromotedToType (ISD::AND,    VT, MVT::v8i64);
1700       setOperationAction(ISD::OR,     VT, Promote);
1701       AddPromotedToType (ISD::OR,     VT, MVT::v8i64);
1702       setOperationAction(ISD::XOR,    VT, Promote);
1703       AddPromotedToType (ISD::XOR,    VT, MVT::v8i64);
1704     }
1705   }
1706
1707   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1708     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1709     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1710
1711     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1712     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1713     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1714     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1715     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1716     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1717     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1718     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1719     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1720     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1721     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i1, Custom);
1722     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i1, Custom);
1723
1724     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1725     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1726     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1727     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1728     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1729     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1730     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1731     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1732
1733     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1734     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1735     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1736     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1737     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1738     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1739     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1740     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1741   }
1742
1743   // We want to custom lower some of our intrinsics.
1744   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1745   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1746   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1747   if (!Subtarget->is64Bit()) {
1748     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1749     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1750   }
1751
1752   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1753   // handle type legalization for these operations here.
1754   //
1755   // FIXME: We really should do custom legalization for addition and
1756   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1757   // than generic legalization for 64-bit multiplication-with-overflow, though.
1758   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1759     if (VT == MVT::i64 && !Subtarget->is64Bit())
1760       continue;
1761     // Add/Sub/Mul with overflow operations are custom lowered.
1762     setOperationAction(ISD::SADDO, VT, Custom);
1763     setOperationAction(ISD::UADDO, VT, Custom);
1764     setOperationAction(ISD::SSUBO, VT, Custom);
1765     setOperationAction(ISD::USUBO, VT, Custom);
1766     setOperationAction(ISD::SMULO, VT, Custom);
1767     setOperationAction(ISD::UMULO, VT, Custom);
1768   }
1769
1770   if (!Subtarget->is64Bit()) {
1771     // These libcalls are not available in 32-bit.
1772     setLibcallName(RTLIB::SHL_I128, nullptr);
1773     setLibcallName(RTLIB::SRL_I128, nullptr);
1774     setLibcallName(RTLIB::SRA_I128, nullptr);
1775   }
1776
1777   // Combine sin / cos into one node or libcall if possible.
1778   if (Subtarget->hasSinCos()) {
1779     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1780     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1781     if (Subtarget->isTargetDarwin()) {
1782       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1783       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1784       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1785       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1786     }
1787   }
1788
1789   if (Subtarget->isTargetWin64()) {
1790     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1791     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1792     setOperationAction(ISD::SREM, MVT::i128, Custom);
1793     setOperationAction(ISD::UREM, MVT::i128, Custom);
1794     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1795     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1796   }
1797
1798   // We have target-specific dag combine patterns for the following nodes:
1799   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1800   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1801   setTargetDAGCombine(ISD::BITCAST);
1802   setTargetDAGCombine(ISD::VSELECT);
1803   setTargetDAGCombine(ISD::SELECT);
1804   setTargetDAGCombine(ISD::SHL);
1805   setTargetDAGCombine(ISD::SRA);
1806   setTargetDAGCombine(ISD::SRL);
1807   setTargetDAGCombine(ISD::OR);
1808   setTargetDAGCombine(ISD::AND);
1809   setTargetDAGCombine(ISD::ADD);
1810   setTargetDAGCombine(ISD::FADD);
1811   setTargetDAGCombine(ISD::FSUB);
1812   setTargetDAGCombine(ISD::FNEG);
1813   setTargetDAGCombine(ISD::FMA);
1814   setTargetDAGCombine(ISD::FMINNUM);
1815   setTargetDAGCombine(ISD::FMAXNUM);
1816   setTargetDAGCombine(ISD::SUB);
1817   setTargetDAGCombine(ISD::LOAD);
1818   setTargetDAGCombine(ISD::MLOAD);
1819   setTargetDAGCombine(ISD::STORE);
1820   setTargetDAGCombine(ISD::MSTORE);
1821   setTargetDAGCombine(ISD::TRUNCATE);
1822   setTargetDAGCombine(ISD::ZERO_EXTEND);
1823   setTargetDAGCombine(ISD::ANY_EXTEND);
1824   setTargetDAGCombine(ISD::SIGN_EXTEND);
1825   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1826   setTargetDAGCombine(ISD::SINT_TO_FP);
1827   setTargetDAGCombine(ISD::UINT_TO_FP);
1828   setTargetDAGCombine(ISD::SETCC);
1829   setTargetDAGCombine(ISD::BUILD_VECTOR);
1830   setTargetDAGCombine(ISD::MUL);
1831   setTargetDAGCombine(ISD::XOR);
1832   setTargetDAGCombine(ISD::MSCATTER);
1833   setTargetDAGCombine(ISD::MGATHER);
1834
1835   computeRegisterProperties(Subtarget->getRegisterInfo());
1836
1837   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1838   MaxStoresPerMemsetOptSize = 8;
1839   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1840   MaxStoresPerMemcpyOptSize = 4;
1841   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1842   MaxStoresPerMemmoveOptSize = 4;
1843   setPrefLoopAlignment(4); // 2^4 bytes.
1844
1845   // A predictable cmov does not hurt on an in-order CPU.
1846   // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1847   PredictableSelectIsExpensive = !Subtarget->isAtom();
1848   EnableExtLdPromotion = true;
1849   setPrefFunctionAlignment(4); // 2^4 bytes.
1850
1851   verifyIntrinsicTables();
1852 }
1853
1854 // This has so far only been implemented for 64-bit MachO.
1855 bool X86TargetLowering::useLoadStackGuardNode() const {
1856   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1857 }
1858
1859 TargetLoweringBase::LegalizeTypeAction
1860 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1861   if (ExperimentalVectorWideningLegalization &&
1862       VT.getVectorNumElements() != 1 &&
1863       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1864     return TypeWidenVector;
1865
1866   return TargetLoweringBase::getPreferredVectorAction(VT);
1867 }
1868
1869 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1870                                           EVT VT) const {
1871   if (!VT.isVector())
1872     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1873
1874   if (VT.isSimple()) {
1875     MVT VVT = VT.getSimpleVT();
1876     const unsigned NumElts = VVT.getVectorNumElements();
1877     const MVT EltVT = VVT.getVectorElementType();
1878     if (VVT.is512BitVector()) {
1879       if (Subtarget->hasAVX512())
1880         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1881             EltVT == MVT::f32 || EltVT == MVT::f64)
1882           switch(NumElts) {
1883           case  8: return MVT::v8i1;
1884           case 16: return MVT::v16i1;
1885         }
1886       if (Subtarget->hasBWI())
1887         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1888           switch(NumElts) {
1889           case 32: return MVT::v32i1;
1890           case 64: return MVT::v64i1;
1891         }
1892     }
1893
1894     if (VVT.is256BitVector() || VVT.is128BitVector()) {
1895       if (Subtarget->hasVLX())
1896         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1897             EltVT == MVT::f32 || EltVT == MVT::f64)
1898           switch(NumElts) {
1899           case 2: return MVT::v2i1;
1900           case 4: return MVT::v4i1;
1901           case 8: return MVT::v8i1;
1902         }
1903       if (Subtarget->hasBWI() && Subtarget->hasVLX())
1904         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1905           switch(NumElts) {
1906           case  8: return MVT::v8i1;
1907           case 16: return MVT::v16i1;
1908           case 32: return MVT::v32i1;
1909         }
1910     }
1911   }
1912
1913   return VT.changeVectorElementTypeToInteger();
1914 }
1915
1916 /// Helper for getByValTypeAlignment to determine
1917 /// the desired ByVal argument alignment.
1918 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1919   if (MaxAlign == 16)
1920     return;
1921   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1922     if (VTy->getBitWidth() == 128)
1923       MaxAlign = 16;
1924   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1925     unsigned EltAlign = 0;
1926     getMaxByValAlign(ATy->getElementType(), EltAlign);
1927     if (EltAlign > MaxAlign)
1928       MaxAlign = EltAlign;
1929   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1930     for (auto *EltTy : STy->elements()) {
1931       unsigned EltAlign = 0;
1932       getMaxByValAlign(EltTy, EltAlign);
1933       if (EltAlign > MaxAlign)
1934         MaxAlign = EltAlign;
1935       if (MaxAlign == 16)
1936         break;
1937     }
1938   }
1939 }
1940
1941 /// Return the desired alignment for ByVal aggregate
1942 /// function arguments in the caller parameter area. For X86, aggregates
1943 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1944 /// are at 4-byte boundaries.
1945 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1946                                                   const DataLayout &DL) const {
1947   if (Subtarget->is64Bit()) {
1948     // Max of 8 and alignment of type.
1949     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1950     if (TyAlign > 8)
1951       return TyAlign;
1952     return 8;
1953   }
1954
1955   unsigned Align = 4;
1956   if (Subtarget->hasSSE1())
1957     getMaxByValAlign(Ty, Align);
1958   return Align;
1959 }
1960
1961 /// Returns the target specific optimal type for load
1962 /// and store operations as a result of memset, memcpy, and memmove
1963 /// lowering. If DstAlign is zero that means it's safe to destination
1964 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1965 /// means there isn't a need to check it against alignment requirement,
1966 /// probably because the source does not need to be loaded. If 'IsMemset' is
1967 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1968 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1969 /// source is constant so it does not need to be loaded.
1970 /// It returns EVT::Other if the type should be determined using generic
1971 /// target-independent logic.
1972 EVT
1973 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1974                                        unsigned DstAlign, unsigned SrcAlign,
1975                                        bool IsMemset, bool ZeroMemset,
1976                                        bool MemcpyStrSrc,
1977                                        MachineFunction &MF) const {
1978   const Function *F = MF.getFunction();
1979   if ((!IsMemset || ZeroMemset) &&
1980       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1981     if (Size >= 16 &&
1982         (!Subtarget->isUnalignedMem16Slow() ||
1983          ((DstAlign == 0 || DstAlign >= 16) &&
1984           (SrcAlign == 0 || SrcAlign >= 16)))) {
1985       if (Size >= 32) {
1986         // FIXME: Check if unaligned 32-byte accesses are slow.
1987         if (Subtarget->hasInt256())
1988           return MVT::v8i32;
1989         if (Subtarget->hasFp256())
1990           return MVT::v8f32;
1991       }
1992       if (Subtarget->hasSSE2())
1993         return MVT::v4i32;
1994       if (Subtarget->hasSSE1())
1995         return MVT::v4f32;
1996     } else if (!MemcpyStrSrc && Size >= 8 &&
1997                !Subtarget->is64Bit() &&
1998                Subtarget->hasSSE2()) {
1999       // Do not use f64 to lower memcpy if source is string constant. It's
2000       // better to use i32 to avoid the loads.
2001       return MVT::f64;
2002     }
2003   }
2004   // This is a compromise. If we reach here, unaligned accesses may be slow on
2005   // this target. However, creating smaller, aligned accesses could be even
2006   // slower and would certainly be a lot more code.
2007   if (Subtarget->is64Bit() && Size >= 8)
2008     return MVT::i64;
2009   return MVT::i32;
2010 }
2011
2012 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2013   if (VT == MVT::f32)
2014     return X86ScalarSSEf32;
2015   else if (VT == MVT::f64)
2016     return X86ScalarSSEf64;
2017   return true;
2018 }
2019
2020 bool
2021 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
2022                                                   unsigned,
2023                                                   unsigned,
2024                                                   bool *Fast) const {
2025   if (Fast) {
2026     switch (VT.getSizeInBits()) {
2027     default:
2028       // 8-byte and under are always assumed to be fast.
2029       *Fast = true;
2030       break;
2031     case 128:
2032       *Fast = !Subtarget->isUnalignedMem16Slow();
2033       break;
2034     case 256:
2035       *Fast = !Subtarget->isUnalignedMem32Slow();
2036       break;
2037     // TODO: What about AVX-512 (512-bit) accesses?
2038     }
2039   }
2040   // Misaligned accesses of any size are always allowed.
2041   return true;
2042 }
2043
2044 /// Return the entry encoding for a jump table in the
2045 /// current function.  The returned value is a member of the
2046 /// MachineJumpTableInfo::JTEntryKind enum.
2047 unsigned X86TargetLowering::getJumpTableEncoding() const {
2048   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2049   // symbol.
2050   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2051       Subtarget->isPICStyleGOT())
2052     return MachineJumpTableInfo::EK_Custom32;
2053
2054   // Otherwise, use the normal jump table encoding heuristics.
2055   return TargetLowering::getJumpTableEncoding();
2056 }
2057
2058 bool X86TargetLowering::useSoftFloat() const {
2059   return Subtarget->useSoftFloat();
2060 }
2061
2062 const MCExpr *
2063 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2064                                              const MachineBasicBlock *MBB,
2065                                              unsigned uid,MCContext &Ctx) const{
2066   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2067          Subtarget->isPICStyleGOT());
2068   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2069   // entries.
2070   return MCSymbolRefExpr::create(MBB->getSymbol(),
2071                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2072 }
2073
2074 /// Returns relocation base for the given PIC jumptable.
2075 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2076                                                     SelectionDAG &DAG) const {
2077   if (!Subtarget->is64Bit())
2078     // This doesn't have SDLoc associated with it, but is not really the
2079     // same as a Register.
2080     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2081                        getPointerTy(DAG.getDataLayout()));
2082   return Table;
2083 }
2084
2085 /// This returns the relocation base for the given PIC jumptable,
2086 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2087 const MCExpr *X86TargetLowering::
2088 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2089                              MCContext &Ctx) const {
2090   // X86-64 uses RIP relative addressing based on the jump table label.
2091   if (Subtarget->isPICStyleRIPRel())
2092     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2093
2094   // Otherwise, the reference is relative to the PIC base.
2095   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2096 }
2097
2098 std::pair<const TargetRegisterClass *, uint8_t>
2099 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2100                                            MVT VT) const {
2101   const TargetRegisterClass *RRC = nullptr;
2102   uint8_t Cost = 1;
2103   switch (VT.SimpleTy) {
2104   default:
2105     return TargetLowering::findRepresentativeClass(TRI, VT);
2106   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2107     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2108     break;
2109   case MVT::x86mmx:
2110     RRC = &X86::VR64RegClass;
2111     break;
2112   case MVT::f32: case MVT::f64:
2113   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2114   case MVT::v4f32: case MVT::v2f64:
2115   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2116   case MVT::v4f64:
2117     RRC = &X86::VR128RegClass;
2118     break;
2119   }
2120   return std::make_pair(RRC, Cost);
2121 }
2122
2123 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2124                                                unsigned &Offset) const {
2125   if (!Subtarget->isTargetLinux())
2126     return false;
2127
2128   if (Subtarget->is64Bit()) {
2129     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2130     Offset = 0x28;
2131     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2132       AddressSpace = 256;
2133     else
2134       AddressSpace = 257;
2135   } else {
2136     // %gs:0x14 on i386
2137     Offset = 0x14;
2138     AddressSpace = 256;
2139   }
2140   return true;
2141 }
2142
2143 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2144   if (!Subtarget->isTargetAndroid())
2145     return TargetLowering::getSafeStackPointerLocation(IRB);
2146
2147   // Android provides a fixed TLS slot for the SafeStack pointer. See the
2148   // definition of TLS_SLOT_SAFESTACK in
2149   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2150   unsigned AddressSpace, Offset;
2151   if (Subtarget->is64Bit()) {
2152     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2153     Offset = 0x48;
2154     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2155       AddressSpace = 256;
2156     else
2157       AddressSpace = 257;
2158   } else {
2159     // %gs:0x24 on i386
2160     Offset = 0x24;
2161     AddressSpace = 256;
2162   }
2163
2164   return ConstantExpr::getIntToPtr(
2165       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2166       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2167 }
2168
2169 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2170                                             unsigned DestAS) const {
2171   assert(SrcAS != DestAS && "Expected different address spaces!");
2172
2173   return SrcAS < 256 && DestAS < 256;
2174 }
2175
2176 //===----------------------------------------------------------------------===//
2177 //               Return Value Calling Convention Implementation
2178 //===----------------------------------------------------------------------===//
2179
2180 #include "X86GenCallingConv.inc"
2181
2182 bool X86TargetLowering::CanLowerReturn(
2183     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2184     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2185   SmallVector<CCValAssign, 16> RVLocs;
2186   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2187   return CCInfo.CheckReturn(Outs, RetCC_X86);
2188 }
2189
2190 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2191   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2192   return ScratchRegs;
2193 }
2194
2195 SDValue
2196 X86TargetLowering::LowerReturn(SDValue Chain,
2197                                CallingConv::ID CallConv, bool isVarArg,
2198                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2199                                const SmallVectorImpl<SDValue> &OutVals,
2200                                SDLoc dl, SelectionDAG &DAG) const {
2201   MachineFunction &MF = DAG.getMachineFunction();
2202   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2203
2204   if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2205     report_fatal_error("X86 interrupts may not return any value");
2206
2207   SmallVector<CCValAssign, 16> RVLocs;
2208   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2209   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2210
2211   SDValue Flag;
2212   SmallVector<SDValue, 6> RetOps;
2213   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2214   // Operand #1 = Bytes To Pop
2215   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2216                    MVT::i16));
2217
2218   // Copy the result values into the output registers.
2219   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2220     CCValAssign &VA = RVLocs[i];
2221     assert(VA.isRegLoc() && "Can only return in registers!");
2222     SDValue ValToCopy = OutVals[i];
2223     EVT ValVT = ValToCopy.getValueType();
2224
2225     // Promote values to the appropriate types.
2226     if (VA.getLocInfo() == CCValAssign::SExt)
2227       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2228     else if (VA.getLocInfo() == CCValAssign::ZExt)
2229       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2230     else if (VA.getLocInfo() == CCValAssign::AExt) {
2231       if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2232         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2233       else
2234         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2235     }
2236     else if (VA.getLocInfo() == CCValAssign::BCvt)
2237       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2238
2239     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2240            "Unexpected FP-extend for return value.");
2241
2242     // If this is x86-64, and we disabled SSE, we can't return FP values,
2243     // or SSE or MMX vectors.
2244     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2245          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2246           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2247       report_fatal_error("SSE register return with SSE disabled");
2248     }
2249     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2250     // llvm-gcc has never done it right and no one has noticed, so this
2251     // should be OK for now.
2252     if (ValVT == MVT::f64 &&
2253         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2254       report_fatal_error("SSE2 register return with SSE2 disabled");
2255
2256     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2257     // the RET instruction and handled by the FP Stackifier.
2258     if (VA.getLocReg() == X86::FP0 ||
2259         VA.getLocReg() == X86::FP1) {
2260       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2261       // change the value to the FP stack register class.
2262       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2263         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2264       RetOps.push_back(ValToCopy);
2265       // Don't emit a copytoreg.
2266       continue;
2267     }
2268
2269     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2270     // which is returned in RAX / RDX.
2271     if (Subtarget->is64Bit()) {
2272       if (ValVT == MVT::x86mmx) {
2273         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2274           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2275           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2276                                   ValToCopy);
2277           // If we don't have SSE2 available, convert to v4f32 so the generated
2278           // register is legal.
2279           if (!Subtarget->hasSSE2())
2280             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2281         }
2282       }
2283     }
2284
2285     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2286     Flag = Chain.getValue(1);
2287     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2288   }
2289
2290   // All x86 ABIs require that for returning structs by value we copy
2291   // the sret argument into %rax/%eax (depending on ABI) for the return.
2292   // We saved the argument into a virtual register in the entry block,
2293   // so now we copy the value out and into %rax/%eax.
2294   //
2295   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2296   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2297   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2298   // either case FuncInfo->setSRetReturnReg() will have been called.
2299   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2300     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2301                                      getPointerTy(MF.getDataLayout()));
2302
2303     unsigned RetValReg
2304         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2305           X86::RAX : X86::EAX;
2306     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2307     Flag = Chain.getValue(1);
2308
2309     // RAX/EAX now acts like a return value.
2310     RetOps.push_back(
2311         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2312   }
2313
2314   const X86RegisterInfo *TRI = Subtarget->getRegisterInfo();
2315   const MCPhysReg *I =
2316       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2317   if (I) {
2318     for (; *I; ++I) {
2319       if (X86::GR64RegClass.contains(*I))
2320         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2321       else
2322         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2323     }
2324   }
2325
2326   RetOps[0] = Chain;  // Update chain.
2327
2328   // Add the flag if we have it.
2329   if (Flag.getNode())
2330     RetOps.push_back(Flag);
2331
2332   X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2333   if (CallConv == CallingConv::X86_INTR)
2334     opcode = X86ISD::IRET;
2335   return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2336 }
2337
2338 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2339   if (N->getNumValues() != 1)
2340     return false;
2341   if (!N->hasNUsesOfValue(1, 0))
2342     return false;
2343
2344   SDValue TCChain = Chain;
2345   SDNode *Copy = *N->use_begin();
2346   if (Copy->getOpcode() == ISD::CopyToReg) {
2347     // If the copy has a glue operand, we conservatively assume it isn't safe to
2348     // perform a tail call.
2349     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2350       return false;
2351     TCChain = Copy->getOperand(0);
2352   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2353     return false;
2354
2355   bool HasRet = false;
2356   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2357        UI != UE; ++UI) {
2358     if (UI->getOpcode() != X86ISD::RET_FLAG)
2359       return false;
2360     // If we are returning more than one value, we can definitely
2361     // not make a tail call see PR19530
2362     if (UI->getNumOperands() > 4)
2363       return false;
2364     if (UI->getNumOperands() == 4 &&
2365         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2366       return false;
2367     HasRet = true;
2368   }
2369
2370   if (!HasRet)
2371     return false;
2372
2373   Chain = TCChain;
2374   return true;
2375 }
2376
2377 EVT
2378 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2379                                             ISD::NodeType ExtendKind) const {
2380   MVT ReturnMVT;
2381   // TODO: Is this also valid on 32-bit?
2382   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2383     ReturnMVT = MVT::i8;
2384   else
2385     ReturnMVT = MVT::i32;
2386
2387   EVT MinVT = getRegisterType(Context, ReturnMVT);
2388   return VT.bitsLT(MinVT) ? MinVT : VT;
2389 }
2390
2391 /// Lower the result values of a call into the
2392 /// appropriate copies out of appropriate physical registers.
2393 ///
2394 SDValue
2395 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2396                                    CallingConv::ID CallConv, bool isVarArg,
2397                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2398                                    SDLoc dl, SelectionDAG &DAG,
2399                                    SmallVectorImpl<SDValue> &InVals) const {
2400
2401   // Assign locations to each value returned by this call.
2402   SmallVector<CCValAssign, 16> RVLocs;
2403   bool Is64Bit = Subtarget->is64Bit();
2404   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2405                  *DAG.getContext());
2406   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2407
2408   // Copy all of the result registers out of their specified physreg.
2409   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2410     CCValAssign &VA = RVLocs[i];
2411     EVT CopyVT = VA.getLocVT();
2412
2413     // If this is x86-64, and we disabled SSE, we can't return FP values
2414     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2415         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2416       report_fatal_error("SSE register return with SSE disabled");
2417     }
2418
2419     // If we prefer to use the value in xmm registers, copy it out as f80 and
2420     // use a truncate to move it from fp stack reg to xmm reg.
2421     bool RoundAfterCopy = false;
2422     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2423         isScalarFPTypeInSSEReg(VA.getValVT())) {
2424       CopyVT = MVT::f80;
2425       RoundAfterCopy = (CopyVT != VA.getLocVT());
2426     }
2427
2428     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2429                                CopyVT, InFlag).getValue(1);
2430     SDValue Val = Chain.getValue(0);
2431
2432     if (RoundAfterCopy)
2433       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2434                         // This truncation won't change the value.
2435                         DAG.getIntPtrConstant(1, dl));
2436
2437     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2438       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2439
2440     InFlag = Chain.getValue(2);
2441     InVals.push_back(Val);
2442   }
2443
2444   return Chain;
2445 }
2446
2447 //===----------------------------------------------------------------------===//
2448 //                C & StdCall & Fast Calling Convention implementation
2449 //===----------------------------------------------------------------------===//
2450 //  StdCall calling convention seems to be standard for many Windows' API
2451 //  routines and around. It differs from C calling convention just a little:
2452 //  callee should clean up the stack, not caller. Symbols should be also
2453 //  decorated in some fancy way :) It doesn't support any vector arguments.
2454 //  For info on fast calling convention see Fast Calling Convention (tail call)
2455 //  implementation LowerX86_32FastCCCallTo.
2456
2457 /// CallIsStructReturn - Determines whether a call uses struct return
2458 /// semantics.
2459 enum StructReturnType {
2460   NotStructReturn,
2461   RegStructReturn,
2462   StackStructReturn
2463 };
2464 static StructReturnType
2465 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsMCU) {
2466   if (Outs.empty())
2467     return NotStructReturn;
2468
2469   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2470   if (!Flags.isSRet())
2471     return NotStructReturn;
2472   if (Flags.isInReg() || IsMCU)
2473     return RegStructReturn;
2474   return StackStructReturn;
2475 }
2476
2477 /// Determines whether a function uses struct return semantics.
2478 static StructReturnType
2479 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsMCU) {
2480   if (Ins.empty())
2481     return NotStructReturn;
2482
2483   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2484   if (!Flags.isSRet())
2485     return NotStructReturn;
2486   if (Flags.isInReg() || IsMCU)
2487     return RegStructReturn;
2488   return StackStructReturn;
2489 }
2490
2491 /// Make a copy of an aggregate at address specified by "Src" to address
2492 /// "Dst" with size and alignment information specified by the specific
2493 /// parameter attribute. The copy will be passed as a byval function parameter.
2494 static SDValue
2495 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2496                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2497                           SDLoc dl) {
2498   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2499
2500   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2501                        /*isVolatile*/false, /*AlwaysInline=*/true,
2502                        /*isTailCall*/false,
2503                        MachinePointerInfo(), MachinePointerInfo());
2504 }
2505
2506 /// Return true if the calling convention is one that we can guarantee TCO for.
2507 static bool canGuaranteeTCO(CallingConv::ID CC) {
2508   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2509           CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2510 }
2511
2512 /// Return true if we might ever do TCO for calls with this calling convention.
2513 static bool mayTailCallThisCC(CallingConv::ID CC) {
2514   switch (CC) {
2515   // C calling conventions:
2516   case CallingConv::C:
2517   case CallingConv::X86_64_Win64:
2518   case CallingConv::X86_64_SysV:
2519   // Callee pop conventions:
2520   case CallingConv::X86_ThisCall:
2521   case CallingConv::X86_StdCall:
2522   case CallingConv::X86_VectorCall:
2523   case CallingConv::X86_FastCall:
2524     return true;
2525   default:
2526     return canGuaranteeTCO(CC);
2527   }
2528 }
2529
2530 /// Return true if the function is being made into a tailcall target by
2531 /// changing its ABI.
2532 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2533   return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2534 }
2535
2536 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2537   auto Attr =
2538       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2539   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2540     return false;
2541
2542   CallSite CS(CI);
2543   CallingConv::ID CalleeCC = CS.getCallingConv();
2544   if (!mayTailCallThisCC(CalleeCC))
2545     return false;
2546
2547   return true;
2548 }
2549
2550 SDValue
2551 X86TargetLowering::LowerMemArgument(SDValue Chain,
2552                                     CallingConv::ID CallConv,
2553                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2554                                     SDLoc dl, SelectionDAG &DAG,
2555                                     const CCValAssign &VA,
2556                                     MachineFrameInfo *MFI,
2557                                     unsigned i) const {
2558   // Create the nodes corresponding to a load from this parameter slot.
2559   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2560   bool AlwaysUseMutable = shouldGuaranteeTCO(
2561       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2562   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2563   EVT ValVT;
2564
2565   // If value is passed by pointer we have address passed instead of the value
2566   // itself.
2567   bool ExtendedInMem = VA.isExtInLoc() &&
2568     VA.getValVT().getScalarType() == MVT::i1;
2569
2570   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2571     ValVT = VA.getLocVT();
2572   else
2573     ValVT = VA.getValVT();
2574
2575   // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2576   // taken by a return address.
2577   int Offset = 0;
2578   if (CallConv == CallingConv::X86_INTR) {
2579     const X86Subtarget& Subtarget =
2580         static_cast<const X86Subtarget&>(DAG.getSubtarget());
2581     // X86 interrupts may take one or two arguments.
2582     // On the stack there will be no return address as in regular call.
2583     // Offset of last argument need to be set to -4/-8 bytes.
2584     // Where offset of the first argument out of two, should be set to 0 bytes.
2585     Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2586   }
2587
2588   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2589   // changed with more analysis.
2590   // In case of tail call optimization mark all arguments mutable. Since they
2591   // could be overwritten by lowering of arguments in case of a tail call.
2592   if (Flags.isByVal()) {
2593     unsigned Bytes = Flags.getByValSize();
2594     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2595     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2596     // Adjust SP offset of interrupt parameter.
2597     if (CallConv == CallingConv::X86_INTR) {
2598       MFI->setObjectOffset(FI, Offset);
2599     }
2600     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2601   } else {
2602     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2603                                     VA.getLocMemOffset(), isImmutable);
2604     // Adjust SP offset of interrupt parameter.
2605     if (CallConv == CallingConv::X86_INTR) {
2606       MFI->setObjectOffset(FI, Offset);
2607     }
2608
2609     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2610     SDValue Val = DAG.getLoad(
2611         ValVT, dl, Chain, FIN,
2612         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2613         false, false, 0);
2614     return ExtendedInMem ?
2615       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2616   }
2617 }
2618
2619 // FIXME: Get this from tablegen.
2620 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2621                                                 const X86Subtarget *Subtarget) {
2622   assert(Subtarget->is64Bit());
2623
2624   if (Subtarget->isCallingConvWin64(CallConv)) {
2625     static const MCPhysReg GPR64ArgRegsWin64[] = {
2626       X86::RCX, X86::RDX, X86::R8,  X86::R9
2627     };
2628     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2629   }
2630
2631   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2632     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2633   };
2634   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2635 }
2636
2637 // FIXME: Get this from tablegen.
2638 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2639                                                 CallingConv::ID CallConv,
2640                                                 const X86Subtarget *Subtarget) {
2641   assert(Subtarget->is64Bit());
2642   if (Subtarget->isCallingConvWin64(CallConv)) {
2643     // The XMM registers which might contain var arg parameters are shadowed
2644     // in their paired GPR.  So we only need to save the GPR to their home
2645     // slots.
2646     // TODO: __vectorcall will change this.
2647     return None;
2648   }
2649
2650   const Function *Fn = MF.getFunction();
2651   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2652   bool isSoftFloat = Subtarget->useSoftFloat();
2653   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2654          "SSE register cannot be used when SSE is disabled!");
2655   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2656     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2657     // registers.
2658     return None;
2659
2660   static const MCPhysReg XMMArgRegs64Bit[] = {
2661     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2662     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2663   };
2664   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2665 }
2666
2667 SDValue X86TargetLowering::LowerFormalArguments(
2668     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2669     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2670     SmallVectorImpl<SDValue> &InVals) const {
2671   MachineFunction &MF = DAG.getMachineFunction();
2672   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2673   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2674
2675   const Function* Fn = MF.getFunction();
2676   if (Fn->hasExternalLinkage() &&
2677       Subtarget->isTargetCygMing() &&
2678       Fn->getName() == "main")
2679     FuncInfo->setForceFramePointer(true);
2680
2681   MachineFrameInfo *MFI = MF.getFrameInfo();
2682   bool Is64Bit = Subtarget->is64Bit();
2683   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2684
2685   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2686          "Var args not supported with calling convention fastcc, ghc or hipe");
2687
2688   if (CallConv == CallingConv::X86_INTR) {
2689     bool isLegal = Ins.size() == 1 ||
2690                    (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
2691                                         (!Is64Bit && Ins[1].VT == MVT::i32)));
2692     if (!isLegal)
2693       report_fatal_error("X86 interrupts may take one or two arguments");
2694   }
2695
2696   // Assign locations to all of the incoming arguments.
2697   SmallVector<CCValAssign, 16> ArgLocs;
2698   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2699
2700   // Allocate shadow area for Win64
2701   if (IsWin64)
2702     CCInfo.AllocateStack(32, 8);
2703
2704   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2705
2706   unsigned LastVal = ~0U;
2707   SDValue ArgValue;
2708   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2709     CCValAssign &VA = ArgLocs[i];
2710     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2711     // places.
2712     assert(VA.getValNo() != LastVal &&
2713            "Don't support value assigned to multiple locs yet");
2714     (void)LastVal;
2715     LastVal = VA.getValNo();
2716
2717     if (VA.isRegLoc()) {
2718       EVT RegVT = VA.getLocVT();
2719       const TargetRegisterClass *RC;
2720       if (RegVT == MVT::i32)
2721         RC = &X86::GR32RegClass;
2722       else if (Is64Bit && RegVT == MVT::i64)
2723         RC = &X86::GR64RegClass;
2724       else if (RegVT == MVT::f32)
2725         RC = &X86::FR32RegClass;
2726       else if (RegVT == MVT::f64)
2727         RC = &X86::FR64RegClass;
2728       else if (RegVT == MVT::f128)
2729         RC = &X86::FR128RegClass;
2730       else if (RegVT.is512BitVector())
2731         RC = &X86::VR512RegClass;
2732       else if (RegVT.is256BitVector())
2733         RC = &X86::VR256RegClass;
2734       else if (RegVT.is128BitVector())
2735         RC = &X86::VR128RegClass;
2736       else if (RegVT == MVT::x86mmx)
2737         RC = &X86::VR64RegClass;
2738       else if (RegVT == MVT::i1)
2739         RC = &X86::VK1RegClass;
2740       else if (RegVT == MVT::v8i1)
2741         RC = &X86::VK8RegClass;
2742       else if (RegVT == MVT::v16i1)
2743         RC = &X86::VK16RegClass;
2744       else if (RegVT == MVT::v32i1)
2745         RC = &X86::VK32RegClass;
2746       else if (RegVT == MVT::v64i1)
2747         RC = &X86::VK64RegClass;
2748       else
2749         llvm_unreachable("Unknown argument type!");
2750
2751       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2752       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2753
2754       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2755       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2756       // right size.
2757       if (VA.getLocInfo() == CCValAssign::SExt)
2758         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2759                                DAG.getValueType(VA.getValVT()));
2760       else if (VA.getLocInfo() == CCValAssign::ZExt)
2761         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2762                                DAG.getValueType(VA.getValVT()));
2763       else if (VA.getLocInfo() == CCValAssign::BCvt)
2764         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2765
2766       if (VA.isExtInLoc()) {
2767         // Handle MMX values passed in XMM regs.
2768         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2769           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2770         else
2771           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2772       }
2773     } else {
2774       assert(VA.isMemLoc());
2775       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2776     }
2777
2778     // If value is passed via pointer - do a load.
2779     if (VA.getLocInfo() == CCValAssign::Indirect)
2780       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2781                              MachinePointerInfo(), false, false, false, 0);
2782
2783     InVals.push_back(ArgValue);
2784   }
2785
2786   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2787     // All x86 ABIs require that for returning structs by value we copy the
2788     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2789     // the argument into a virtual register so that we can access it from the
2790     // return points.
2791     if (Ins[i].Flags.isSRet()) {
2792       unsigned Reg = FuncInfo->getSRetReturnReg();
2793       if (!Reg) {
2794         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2795         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2796         FuncInfo->setSRetReturnReg(Reg);
2797       }
2798       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2799       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2800       break;
2801     }
2802   }
2803
2804   unsigned StackSize = CCInfo.getNextStackOffset();
2805   // Align stack specially for tail calls.
2806   if (shouldGuaranteeTCO(CallConv,
2807                          MF.getTarget().Options.GuaranteedTailCallOpt))
2808     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2809
2810   // If the function takes variable number of arguments, make a frame index for
2811   // the start of the first vararg value... for expansion of llvm.va_start. We
2812   // can skip this if there are no va_start calls.
2813   if (MFI->hasVAStart() &&
2814       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2815                    CallConv != CallingConv::X86_ThisCall))) {
2816     FuncInfo->setVarArgsFrameIndex(
2817         MFI->CreateFixedObject(1, StackSize, true));
2818   }
2819
2820   // Figure out if XMM registers are in use.
2821   assert(!(Subtarget->useSoftFloat() &&
2822            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2823          "SSE register cannot be used when SSE is disabled!");
2824
2825   // 64-bit calling conventions support varargs and register parameters, so we
2826   // have to do extra work to spill them in the prologue.
2827   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2828     // Find the first unallocated argument registers.
2829     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2830     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2831     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2832     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2833     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2834            "SSE register cannot be used when SSE is disabled!");
2835
2836     // Gather all the live in physical registers.
2837     SmallVector<SDValue, 6> LiveGPRs;
2838     SmallVector<SDValue, 8> LiveXMMRegs;
2839     SDValue ALVal;
2840     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2841       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2842       LiveGPRs.push_back(
2843           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2844     }
2845     if (!ArgXMMs.empty()) {
2846       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2847       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2848       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2849         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2850         LiveXMMRegs.push_back(
2851             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2852       }
2853     }
2854
2855     if (IsWin64) {
2856       // Get to the caller-allocated home save location.  Add 8 to account
2857       // for the return address.
2858       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2859       FuncInfo->setRegSaveFrameIndex(
2860           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2861       // Fixup to set vararg frame on shadow area (4 x i64).
2862       if (NumIntRegs < 4)
2863         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2864     } else {
2865       // For X86-64, if there are vararg parameters that are passed via
2866       // registers, then we must store them to their spots on the stack so
2867       // they may be loaded by deferencing the result of va_next.
2868       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2869       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2870       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2871           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2872     }
2873
2874     // Store the integer parameter registers.
2875     SmallVector<SDValue, 8> MemOps;
2876     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2877                                       getPointerTy(DAG.getDataLayout()));
2878     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2879     for (SDValue Val : LiveGPRs) {
2880       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2881                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2882       SDValue Store =
2883           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2884                        MachinePointerInfo::getFixedStack(
2885                            DAG.getMachineFunction(),
2886                            FuncInfo->getRegSaveFrameIndex(), Offset),
2887                        false, false, 0);
2888       MemOps.push_back(Store);
2889       Offset += 8;
2890     }
2891
2892     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2893       // Now store the XMM (fp + vector) parameter registers.
2894       SmallVector<SDValue, 12> SaveXMMOps;
2895       SaveXMMOps.push_back(Chain);
2896       SaveXMMOps.push_back(ALVal);
2897       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2898                              FuncInfo->getRegSaveFrameIndex(), dl));
2899       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2900                              FuncInfo->getVarArgsFPOffset(), dl));
2901       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2902                         LiveXMMRegs.end());
2903       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2904                                    MVT::Other, SaveXMMOps));
2905     }
2906
2907     if (!MemOps.empty())
2908       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2909   }
2910
2911   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2912     // Find the largest legal vector type.
2913     MVT VecVT = MVT::Other;
2914     // FIXME: Only some x86_32 calling conventions support AVX512.
2915     if (Subtarget->hasAVX512() &&
2916         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2917                      CallConv == CallingConv::Intel_OCL_BI)))
2918       VecVT = MVT::v16f32;
2919     else if (Subtarget->hasAVX())
2920       VecVT = MVT::v8f32;
2921     else if (Subtarget->hasSSE2())
2922       VecVT = MVT::v4f32;
2923
2924     // We forward some GPRs and some vector types.
2925     SmallVector<MVT, 2> RegParmTypes;
2926     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2927     RegParmTypes.push_back(IntVT);
2928     if (VecVT != MVT::Other)
2929       RegParmTypes.push_back(VecVT);
2930
2931     // Compute the set of forwarded registers. The rest are scratch.
2932     SmallVectorImpl<ForwardedRegister> &Forwards =
2933         FuncInfo->getForwardedMustTailRegParms();
2934     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2935
2936     // Conservatively forward AL on x86_64, since it might be used for varargs.
2937     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2938       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2939       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2940     }
2941
2942     // Copy all forwards from physical to virtual registers.
2943     for (ForwardedRegister &F : Forwards) {
2944       // FIXME: Can we use a less constrained schedule?
2945       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2946       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2947       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2948     }
2949   }
2950
2951   // Some CCs need callee pop.
2952   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2953                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2954     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2955   } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
2956     // X86 interrupts must pop the error code if present
2957     FuncInfo->setBytesToPopOnReturn(Is64Bit ? 8 : 4);
2958   } else {
2959     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2960     // If this is an sret function, the return should pop the hidden pointer.
2961     if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2962         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2963         argsAreStructReturn(Ins, Subtarget->isTargetMCU()) == StackStructReturn)
2964       FuncInfo->setBytesToPopOnReturn(4);
2965   }
2966
2967   if (!Is64Bit) {
2968     // RegSaveFrameIndex is X86-64 only.
2969     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2970     if (CallConv == CallingConv::X86_FastCall ||
2971         CallConv == CallingConv::X86_ThisCall)
2972       // fastcc functions can't have varargs.
2973       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2974   }
2975
2976   FuncInfo->setArgumentStackSize(StackSize);
2977
2978   if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
2979     EHPersonality Personality = classifyEHPersonality(Fn->getPersonalityFn());
2980     if (Personality == EHPersonality::CoreCLR) {
2981       assert(Is64Bit);
2982       // TODO: Add a mechanism to frame lowering that will allow us to indicate
2983       // that we'd prefer this slot be allocated towards the bottom of the frame
2984       // (i.e. near the stack pointer after allocating the frame).  Every
2985       // funclet needs a copy of this slot in its (mostly empty) frame, and the
2986       // offset from the bottom of this and each funclet's frame must be the
2987       // same, so the size of funclets' (mostly empty) frames is dictated by
2988       // how far this slot is from the bottom (since they allocate just enough
2989       // space to accomodate holding this slot at the correct offset).
2990       int PSPSymFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2991       EHInfo->PSPSymFrameIdx = PSPSymFI;
2992     }
2993   }
2994
2995   return Chain;
2996 }
2997
2998 SDValue
2999 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
3000                                     SDValue StackPtr, SDValue Arg,
3001                                     SDLoc dl, SelectionDAG &DAG,
3002                                     const CCValAssign &VA,
3003                                     ISD::ArgFlagsTy Flags) const {
3004   unsigned LocMemOffset = VA.getLocMemOffset();
3005   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
3006   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3007                        StackPtr, PtrOff);
3008   if (Flags.isByVal())
3009     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
3010
3011   return DAG.getStore(
3012       Chain, dl, Arg, PtrOff,
3013       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
3014       false, false, 0);
3015 }
3016
3017 /// Emit a load of return address if tail call
3018 /// optimization is performed and it is required.
3019 SDValue
3020 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
3021                                            SDValue &OutRetAddr, SDValue Chain,
3022                                            bool IsTailCall, bool Is64Bit,
3023                                            int FPDiff, SDLoc dl) const {
3024   // Adjust the Return address stack slot.
3025   EVT VT = getPointerTy(DAG.getDataLayout());
3026   OutRetAddr = getReturnAddressFrameIndex(DAG);
3027
3028   // Load the "old" Return address.
3029   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
3030                            false, false, false, 0);
3031   return SDValue(OutRetAddr.getNode(), 1);
3032 }
3033
3034 /// Emit a store of the return address if tail call
3035 /// optimization is performed and it is required (FPDiff!=0).
3036 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
3037                                         SDValue Chain, SDValue RetAddrFrIdx,
3038                                         EVT PtrVT, unsigned SlotSize,
3039                                         int FPDiff, SDLoc dl) {
3040   // Store the return address to the appropriate stack slot.
3041   if (!FPDiff) return Chain;
3042   // Calculate the new stack slot for the return address.
3043   int NewReturnAddrFI =
3044     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3045                                          false);
3046   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3047   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3048                        MachinePointerInfo::getFixedStack(
3049                            DAG.getMachineFunction(), NewReturnAddrFI),
3050                        false, false, 0);
3051   return Chain;
3052 }
3053
3054 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3055 /// operation of specified width.
3056 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
3057                        SDValue V2) {
3058   unsigned NumElems = VT.getVectorNumElements();
3059   SmallVector<int, 8> Mask;
3060   Mask.push_back(NumElems);
3061   for (unsigned i = 1; i != NumElems; ++i)
3062     Mask.push_back(i);
3063   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3064 }
3065
3066 SDValue
3067 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3068                              SmallVectorImpl<SDValue> &InVals) const {
3069   SelectionDAG &DAG                     = CLI.DAG;
3070   SDLoc &dl                             = CLI.DL;
3071   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3072   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3073   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3074   SDValue Chain                         = CLI.Chain;
3075   SDValue Callee                        = CLI.Callee;
3076   CallingConv::ID CallConv              = CLI.CallConv;
3077   bool &isTailCall                      = CLI.IsTailCall;
3078   bool isVarArg                         = CLI.IsVarArg;
3079
3080   MachineFunction &MF = DAG.getMachineFunction();
3081   bool Is64Bit        = Subtarget->is64Bit();
3082   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
3083   StructReturnType SR = callIsStructReturn(Outs, Subtarget->isTargetMCU());
3084   bool IsSibcall      = false;
3085   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3086   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
3087
3088   if (CallConv == CallingConv::X86_INTR)
3089     report_fatal_error("X86 interrupts may not be called directly");
3090
3091   if (Attr.getValueAsString() == "true")
3092     isTailCall = false;
3093
3094   if (Subtarget->isPICStyleGOT() &&
3095       !MF.getTarget().Options.GuaranteedTailCallOpt) {
3096     // If we are using a GOT, disable tail calls to external symbols with
3097     // default visibility. Tail calling such a symbol requires using a GOT
3098     // relocation, which forces early binding of the symbol. This breaks code
3099     // that require lazy function symbol resolution. Using musttail or
3100     // GuaranteedTailCallOpt will override this.
3101     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3102     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3103                G->getGlobal()->hasDefaultVisibility()))
3104       isTailCall = false;
3105   }
3106
3107   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3108   if (IsMustTail) {
3109     // Force this to be a tail call.  The verifier rules are enough to ensure
3110     // that we can lower this successfully without moving the return address
3111     // around.
3112     isTailCall = true;
3113   } else if (isTailCall) {
3114     // Check if it's really possible to do a tail call.
3115     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3116                     isVarArg, SR != NotStructReturn,
3117                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3118                     Outs, OutVals, Ins, DAG);
3119
3120     // Sibcalls are automatically detected tailcalls which do not require
3121     // ABI changes.
3122     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3123       IsSibcall = true;
3124
3125     if (isTailCall)
3126       ++NumTailCalls;
3127   }
3128
3129   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3130          "Var args not supported with calling convention fastcc, ghc or hipe");
3131
3132   // Analyze operands of the call, assigning locations to each operand.
3133   SmallVector<CCValAssign, 16> ArgLocs;
3134   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3135
3136   // Allocate shadow area for Win64
3137   if (IsWin64)
3138     CCInfo.AllocateStack(32, 8);
3139
3140   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3141
3142   // Get a count of how many bytes are to be pushed on the stack.
3143   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3144   if (IsSibcall)
3145     // This is a sibcall. The memory operands are available in caller's
3146     // own caller's stack.
3147     NumBytes = 0;
3148   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3149            canGuaranteeTCO(CallConv))
3150     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3151
3152   int FPDiff = 0;
3153   if (isTailCall && !IsSibcall && !IsMustTail) {
3154     // Lower arguments at fp - stackoffset + fpdiff.
3155     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3156
3157     FPDiff = NumBytesCallerPushed - NumBytes;
3158
3159     // Set the delta of movement of the returnaddr stackslot.
3160     // But only set if delta is greater than previous delta.
3161     if (FPDiff < X86Info->getTCReturnAddrDelta())
3162       X86Info->setTCReturnAddrDelta(FPDiff);
3163   }
3164
3165   unsigned NumBytesToPush = NumBytes;
3166   unsigned NumBytesToPop = NumBytes;
3167
3168   // If we have an inalloca argument, all stack space has already been allocated
3169   // for us and be right at the top of the stack.  We don't support multiple
3170   // arguments passed in memory when using inalloca.
3171   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3172     NumBytesToPush = 0;
3173     if (!ArgLocs.back().isMemLoc())
3174       report_fatal_error("cannot use inalloca attribute on a register "
3175                          "parameter");
3176     if (ArgLocs.back().getLocMemOffset() != 0)
3177       report_fatal_error("any parameter with the inalloca attribute must be "
3178                          "the only memory argument");
3179   }
3180
3181   if (!IsSibcall)
3182     Chain = DAG.getCALLSEQ_START(
3183         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3184
3185   SDValue RetAddrFrIdx;
3186   // Load return address for tail calls.
3187   if (isTailCall && FPDiff)
3188     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3189                                     Is64Bit, FPDiff, dl);
3190
3191   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3192   SmallVector<SDValue, 8> MemOpChains;
3193   SDValue StackPtr;
3194
3195   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3196   // of tail call optimization arguments are handle later.
3197   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3198   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3199     // Skip inalloca arguments, they have already been written.
3200     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3201     if (Flags.isInAlloca())
3202       continue;
3203
3204     CCValAssign &VA = ArgLocs[i];
3205     EVT RegVT = VA.getLocVT();
3206     SDValue Arg = OutVals[i];
3207     bool isByVal = Flags.isByVal();
3208
3209     // Promote the value if needed.
3210     switch (VA.getLocInfo()) {
3211     default: llvm_unreachable("Unknown loc info!");
3212     case CCValAssign::Full: break;
3213     case CCValAssign::SExt:
3214       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3215       break;
3216     case CCValAssign::ZExt:
3217       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3218       break;
3219     case CCValAssign::AExt:
3220       if (Arg.getValueType().isVector() &&
3221           Arg.getValueType().getVectorElementType() == MVT::i1)
3222         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3223       else if (RegVT.is128BitVector()) {
3224         // Special case: passing MMX values in XMM registers.
3225         Arg = DAG.getBitcast(MVT::i64, Arg);
3226         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3227         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3228       } else
3229         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3230       break;
3231     case CCValAssign::BCvt:
3232       Arg = DAG.getBitcast(RegVT, Arg);
3233       break;
3234     case CCValAssign::Indirect: {
3235       // Store the argument.
3236       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3237       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3238       Chain = DAG.getStore(
3239           Chain, dl, Arg, SpillSlot,
3240           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3241           false, false, 0);
3242       Arg = SpillSlot;
3243       break;
3244     }
3245     }
3246
3247     if (VA.isRegLoc()) {
3248       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3249       if (isVarArg && IsWin64) {
3250         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3251         // shadow reg if callee is a varargs function.
3252         unsigned ShadowReg = 0;
3253         switch (VA.getLocReg()) {
3254         case X86::XMM0: ShadowReg = X86::RCX; break;
3255         case X86::XMM1: ShadowReg = X86::RDX; break;
3256         case X86::XMM2: ShadowReg = X86::R8; break;
3257         case X86::XMM3: ShadowReg = X86::R9; break;
3258         }
3259         if (ShadowReg)
3260           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3261       }
3262     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3263       assert(VA.isMemLoc());
3264       if (!StackPtr.getNode())
3265         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3266                                       getPointerTy(DAG.getDataLayout()));
3267       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3268                                              dl, DAG, VA, Flags));
3269     }
3270   }
3271
3272   if (!MemOpChains.empty())
3273     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3274
3275   if (Subtarget->isPICStyleGOT()) {
3276     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3277     // GOT pointer.
3278     if (!isTailCall) {
3279       RegsToPass.push_back(std::make_pair(
3280           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3281                                           getPointerTy(DAG.getDataLayout()))));
3282     } else {
3283       // If we are tail calling and generating PIC/GOT style code load the
3284       // address of the callee into ECX. The value in ecx is used as target of
3285       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3286       // for tail calls on PIC/GOT architectures. Normally we would just put the
3287       // address of GOT into ebx and then call target@PLT. But for tail calls
3288       // ebx would be restored (since ebx is callee saved) before jumping to the
3289       // target@PLT.
3290
3291       // Note: The actual moving to ECX is done further down.
3292       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3293       if (G && !G->getGlobal()->hasLocalLinkage() &&
3294           G->getGlobal()->hasDefaultVisibility())
3295         Callee = LowerGlobalAddress(Callee, DAG);
3296       else if (isa<ExternalSymbolSDNode>(Callee))
3297         Callee = LowerExternalSymbol(Callee, DAG);
3298     }
3299   }
3300
3301   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3302     // From AMD64 ABI document:
3303     // For calls that may call functions that use varargs or stdargs
3304     // (prototype-less calls or calls to functions containing ellipsis (...) in
3305     // the declaration) %al is used as hidden argument to specify the number
3306     // of SSE registers used. The contents of %al do not need to match exactly
3307     // the number of registers, but must be an ubound on the number of SSE
3308     // registers used and is in the range 0 - 8 inclusive.
3309
3310     // Count the number of XMM registers allocated.
3311     static const MCPhysReg XMMArgRegs[] = {
3312       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3313       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3314     };
3315     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3316     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3317            && "SSE registers cannot be used when SSE is disabled");
3318
3319     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3320                                         DAG.getConstant(NumXMMRegs, dl,
3321                                                         MVT::i8)));
3322   }
3323
3324   if (isVarArg && IsMustTail) {
3325     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3326     for (const auto &F : Forwards) {
3327       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3328       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3329     }
3330   }
3331
3332   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3333   // don't need this because the eligibility check rejects calls that require
3334   // shuffling arguments passed in memory.
3335   if (!IsSibcall && isTailCall) {
3336     // Force all the incoming stack arguments to be loaded from the stack
3337     // before any new outgoing arguments are stored to the stack, because the
3338     // outgoing stack slots may alias the incoming argument stack slots, and
3339     // the alias isn't otherwise explicit. This is slightly more conservative
3340     // than necessary, because it means that each store effectively depends
3341     // on every argument instead of just those arguments it would clobber.
3342     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3343
3344     SmallVector<SDValue, 8> MemOpChains2;
3345     SDValue FIN;
3346     int FI = 0;
3347     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3348       CCValAssign &VA = ArgLocs[i];
3349       if (VA.isRegLoc())
3350         continue;
3351       assert(VA.isMemLoc());
3352       SDValue Arg = OutVals[i];
3353       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3354       // Skip inalloca arguments.  They don't require any work.
3355       if (Flags.isInAlloca())
3356         continue;
3357       // Create frame index.
3358       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3359       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3360       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3361       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3362
3363       if (Flags.isByVal()) {
3364         // Copy relative to framepointer.
3365         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3366         if (!StackPtr.getNode())
3367           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3368                                         getPointerTy(DAG.getDataLayout()));
3369         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3370                              StackPtr, Source);
3371
3372         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3373                                                          ArgChain,
3374                                                          Flags, DAG, dl));
3375       } else {
3376         // Store relative to framepointer.
3377         MemOpChains2.push_back(DAG.getStore(
3378             ArgChain, dl, Arg, FIN,
3379             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3380             false, false, 0));
3381       }
3382     }
3383
3384     if (!MemOpChains2.empty())
3385       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3386
3387     // Store the return address to the appropriate stack slot.
3388     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3389                                      getPointerTy(DAG.getDataLayout()),
3390                                      RegInfo->getSlotSize(), FPDiff, dl);
3391   }
3392
3393   // Build a sequence of copy-to-reg nodes chained together with token chain
3394   // and flag operands which copy the outgoing args into registers.
3395   SDValue InFlag;
3396   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3397     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3398                              RegsToPass[i].second, InFlag);
3399     InFlag = Chain.getValue(1);
3400   }
3401
3402   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3403     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3404     // In the 64-bit large code model, we have to make all calls
3405     // through a register, since the call instruction's 32-bit
3406     // pc-relative offset may not be large enough to hold the whole
3407     // address.
3408   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3409     // If the callee is a GlobalAddress node (quite common, every direct call
3410     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3411     // it.
3412     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3413
3414     // We should use extra load for direct calls to dllimported functions in
3415     // non-JIT mode.
3416     const GlobalValue *GV = G->getGlobal();
3417     if (!GV->hasDLLImportStorageClass()) {
3418       unsigned char OpFlags = 0;
3419       bool ExtraLoad = false;
3420       unsigned WrapperKind = ISD::DELETED_NODE;
3421
3422       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3423       // external symbols most go through the PLT in PIC mode.  If the symbol
3424       // has hidden or protected visibility, or if it is static or local, then
3425       // we don't need to use the PLT - we can directly call it.
3426       if (Subtarget->isTargetELF() &&
3427           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3428           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3429         OpFlags = X86II::MO_PLT;
3430       } else if (Subtarget->isPICStyleStubAny() &&
3431                  !GV->isStrongDefinitionForLinker() &&
3432                  (!Subtarget->getTargetTriple().isMacOSX() ||
3433                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3434         // PC-relative references to external symbols should go through $stub,
3435         // unless we're building with the leopard linker or later, which
3436         // automatically synthesizes these stubs.
3437         OpFlags = X86II::MO_DARWIN_STUB;
3438       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3439                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3440         // If the function is marked as non-lazy, generate an indirect call
3441         // which loads from the GOT directly. This avoids runtime overhead
3442         // at the cost of eager binding (and one extra byte of encoding).
3443         OpFlags = X86II::MO_GOTPCREL;
3444         WrapperKind = X86ISD::WrapperRIP;
3445         ExtraLoad = true;
3446       }
3447
3448       Callee = DAG.getTargetGlobalAddress(
3449           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3450
3451       // Add a wrapper if needed.
3452       if (WrapperKind != ISD::DELETED_NODE)
3453         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3454                              getPointerTy(DAG.getDataLayout()), Callee);
3455       // Add extra indirection if needed.
3456       if (ExtraLoad)
3457         Callee = DAG.getLoad(
3458             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3459             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3460             false, 0);
3461     }
3462   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3463     unsigned char OpFlags = 0;
3464
3465     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3466     // external symbols should go through the PLT.
3467     if (Subtarget->isTargetELF() &&
3468         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3469       OpFlags = X86II::MO_PLT;
3470     } else if (Subtarget->isPICStyleStubAny() &&
3471                (!Subtarget->getTargetTriple().isMacOSX() ||
3472                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3473       // PC-relative references to external symbols should go through $stub,
3474       // unless we're building with the leopard linker or later, which
3475       // automatically synthesizes these stubs.
3476       OpFlags = X86II::MO_DARWIN_STUB;
3477     }
3478
3479     Callee = DAG.getTargetExternalSymbol(
3480         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3481   } else if (Subtarget->isTarget64BitILP32() &&
3482              Callee->getValueType(0) == MVT::i32) {
3483     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3484     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3485   }
3486
3487   // Returns a chain & a flag for retval copy to use.
3488   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3489   SmallVector<SDValue, 8> Ops;
3490
3491   if (!IsSibcall && isTailCall) {
3492     Chain = DAG.getCALLSEQ_END(Chain,
3493                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3494                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3495     InFlag = Chain.getValue(1);
3496   }
3497
3498   Ops.push_back(Chain);
3499   Ops.push_back(Callee);
3500
3501   if (isTailCall)
3502     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3503
3504   // Add argument registers to the end of the list so that they are known live
3505   // into the call.
3506   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3507     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3508                                   RegsToPass[i].second.getValueType()));
3509
3510   // Add a register mask operand representing the call-preserved registers.
3511   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3512   assert(Mask && "Missing call preserved mask for calling convention");
3513
3514   // If this is an invoke in a 32-bit function using a funclet-based
3515   // personality, assume the function clobbers all registers. If an exception
3516   // is thrown, the runtime will not restore CSRs.
3517   // FIXME: Model this more precisely so that we can register allocate across
3518   // the normal edge and spill and fill across the exceptional edge.
3519   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3520     const Function *CallerFn = MF.getFunction();
3521     EHPersonality Pers =
3522         CallerFn->hasPersonalityFn()
3523             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3524             : EHPersonality::Unknown;
3525     if (isFuncletEHPersonality(Pers))
3526       Mask = RegInfo->getNoPreservedMask();
3527   }
3528
3529   Ops.push_back(DAG.getRegisterMask(Mask));
3530
3531   if (InFlag.getNode())
3532     Ops.push_back(InFlag);
3533
3534   if (isTailCall) {
3535     // We used to do:
3536     //// If this is the first return lowered for this function, add the regs
3537     //// to the liveout set for the function.
3538     // This isn't right, although it's probably harmless on x86; liveouts
3539     // should be computed from returns not tail calls.  Consider a void
3540     // function making a tail call to a function returning int.
3541     MF.getFrameInfo()->setHasTailCall();
3542     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3543   }
3544
3545   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3546   InFlag = Chain.getValue(1);
3547
3548   // Create the CALLSEQ_END node.
3549   unsigned NumBytesForCalleeToPop;
3550   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3551                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3552     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3553   else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3554            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3555            SR == StackStructReturn)
3556     // If this is a call to a struct-return function, the callee
3557     // pops the hidden struct pointer, so we have to push it back.
3558     // This is common for Darwin/X86, Linux & Mingw32 targets.
3559     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3560     NumBytesForCalleeToPop = 4;
3561   else
3562     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3563
3564   // Returns a flag for retval copy to use.
3565   if (!IsSibcall) {
3566     Chain = DAG.getCALLSEQ_END(Chain,
3567                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3568                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3569                                                      true),
3570                                InFlag, dl);
3571     InFlag = Chain.getValue(1);
3572   }
3573
3574   // Handle result values, copying them out of physregs into vregs that we
3575   // return.
3576   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3577                          Ins, dl, DAG, InVals);
3578 }
3579
3580 //===----------------------------------------------------------------------===//
3581 //                Fast Calling Convention (tail call) implementation
3582 //===----------------------------------------------------------------------===//
3583
3584 //  Like std call, callee cleans arguments, convention except that ECX is
3585 //  reserved for storing the tail called function address. Only 2 registers are
3586 //  free for argument passing (inreg). Tail call optimization is performed
3587 //  provided:
3588 //                * tailcallopt is enabled
3589 //                * caller/callee are fastcc
3590 //  On X86_64 architecture with GOT-style position independent code only local
3591 //  (within module) calls are supported at the moment.
3592 //  To keep the stack aligned according to platform abi the function
3593 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3594 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3595 //  If a tail called function callee has more arguments than the caller the
3596 //  caller needs to make sure that there is room to move the RETADDR to. This is
3597 //  achieved by reserving an area the size of the argument delta right after the
3598 //  original RETADDR, but before the saved framepointer or the spilled registers
3599 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3600 //  stack layout:
3601 //    arg1
3602 //    arg2
3603 //    RETADDR
3604 //    [ new RETADDR
3605 //      move area ]
3606 //    (possible EBP)
3607 //    ESI
3608 //    EDI
3609 //    local1 ..
3610
3611 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3612 /// requirement.
3613 unsigned
3614 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3615                                                SelectionDAG& DAG) const {
3616   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3617   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3618   unsigned StackAlignment = TFI.getStackAlignment();
3619   uint64_t AlignMask = StackAlignment - 1;
3620   int64_t Offset = StackSize;
3621   unsigned SlotSize = RegInfo->getSlotSize();
3622   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3623     // Number smaller than 12 so just add the difference.
3624     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3625   } else {
3626     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3627     Offset = ((~AlignMask) & Offset) + StackAlignment +
3628       (StackAlignment-SlotSize);
3629   }
3630   return Offset;
3631 }
3632
3633 /// Return true if the given stack call argument is already available in the
3634 /// same position (relatively) of the caller's incoming argument stack.
3635 static
3636 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3637                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3638                          const X86InstrInfo *TII) {
3639   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3640   int FI = INT_MAX;
3641   if (Arg.getOpcode() == ISD::CopyFromReg) {
3642     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3643     if (!TargetRegisterInfo::isVirtualRegister(VR))
3644       return false;
3645     MachineInstr *Def = MRI->getVRegDef(VR);
3646     if (!Def)
3647       return false;
3648     if (!Flags.isByVal()) {
3649       if (!TII->isLoadFromStackSlot(Def, FI))
3650         return false;
3651     } else {
3652       unsigned Opcode = Def->getOpcode();
3653       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3654            Opcode == X86::LEA64_32r) &&
3655           Def->getOperand(1).isFI()) {
3656         FI = Def->getOperand(1).getIndex();
3657         Bytes = Flags.getByValSize();
3658       } else
3659         return false;
3660     }
3661   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3662     if (Flags.isByVal())
3663       // ByVal argument is passed in as a pointer but it's now being
3664       // dereferenced. e.g.
3665       // define @foo(%struct.X* %A) {
3666       //   tail call @bar(%struct.X* byval %A)
3667       // }
3668       return false;
3669     SDValue Ptr = Ld->getBasePtr();
3670     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3671     if (!FINode)
3672       return false;
3673     FI = FINode->getIndex();
3674   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3675     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3676     FI = FINode->getIndex();
3677     Bytes = Flags.getByValSize();
3678   } else
3679     return false;
3680
3681   assert(FI != INT_MAX);
3682   if (!MFI->isFixedObjectIndex(FI))
3683     return false;
3684   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3685 }
3686
3687 /// Check whether the call is eligible for tail call optimization. Targets
3688 /// that want to do tail call optimization should implement this function.
3689 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3690     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3691     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3692     const SmallVectorImpl<ISD::OutputArg> &Outs,
3693     const SmallVectorImpl<SDValue> &OutVals,
3694     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3695   if (!mayTailCallThisCC(CalleeCC))
3696     return false;
3697
3698   // If -tailcallopt is specified, make fastcc functions tail-callable.
3699   MachineFunction &MF = DAG.getMachineFunction();
3700   const Function *CallerF = MF.getFunction();
3701
3702   // If the function return type is x86_fp80 and the callee return type is not,
3703   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3704   // perform a tailcall optimization here.
3705   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3706     return false;
3707
3708   CallingConv::ID CallerCC = CallerF->getCallingConv();
3709   bool CCMatch = CallerCC == CalleeCC;
3710   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3711   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3712
3713   // Win64 functions have extra shadow space for argument homing. Don't do the
3714   // sibcall if the caller and callee have mismatched expectations for this
3715   // space.
3716   if (IsCalleeWin64 != IsCallerWin64)
3717     return false;
3718
3719   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3720     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3721       return true;
3722     return false;
3723   }
3724
3725   // Look for obvious safe cases to perform tail call optimization that do not
3726   // require ABI changes. This is what gcc calls sibcall.
3727
3728   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3729   // emit a special epilogue.
3730   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3731   if (RegInfo->needsStackRealignment(MF))
3732     return false;
3733
3734   // Also avoid sibcall optimization if either caller or callee uses struct
3735   // return semantics.
3736   if (isCalleeStructRet || isCallerStructRet)
3737     return false;
3738
3739   // Do not sibcall optimize vararg calls unless all arguments are passed via
3740   // registers.
3741   if (isVarArg && !Outs.empty()) {
3742     // Optimizing for varargs on Win64 is unlikely to be safe without
3743     // additional testing.
3744     if (IsCalleeWin64 || IsCallerWin64)
3745       return false;
3746
3747     SmallVector<CCValAssign, 16> ArgLocs;
3748     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3749                    *DAG.getContext());
3750
3751     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3752     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3753       if (!ArgLocs[i].isRegLoc())
3754         return false;
3755   }
3756
3757   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3758   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3759   // this into a sibcall.
3760   bool Unused = false;
3761   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3762     if (!Ins[i].Used) {
3763       Unused = true;
3764       break;
3765     }
3766   }
3767   if (Unused) {
3768     SmallVector<CCValAssign, 16> RVLocs;
3769     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3770                    *DAG.getContext());
3771     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3772     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3773       CCValAssign &VA = RVLocs[i];
3774       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3775         return false;
3776     }
3777   }
3778
3779   // If the calling conventions do not match, then we'd better make sure the
3780   // results are returned in the same way as what the caller expects.
3781   if (!CCMatch) {
3782     SmallVector<CCValAssign, 16> RVLocs1;
3783     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3784                     *DAG.getContext());
3785     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3786
3787     SmallVector<CCValAssign, 16> RVLocs2;
3788     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3789                     *DAG.getContext());
3790     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3791
3792     if (RVLocs1.size() != RVLocs2.size())
3793       return false;
3794     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3795       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3796         return false;
3797       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3798         return false;
3799       if (RVLocs1[i].isRegLoc()) {
3800         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3801           return false;
3802       } else {
3803         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3804           return false;
3805       }
3806     }
3807   }
3808
3809   unsigned StackArgsSize = 0;
3810
3811   // If the callee takes no arguments then go on to check the results of the
3812   // call.
3813   if (!Outs.empty()) {
3814     // Check if stack adjustment is needed. For now, do not do this if any
3815     // argument is passed on the stack.
3816     SmallVector<CCValAssign, 16> ArgLocs;
3817     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3818                    *DAG.getContext());
3819
3820     // Allocate shadow area for Win64
3821     if (IsCalleeWin64)
3822       CCInfo.AllocateStack(32, 8);
3823
3824     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3825     StackArgsSize = CCInfo.getNextStackOffset();
3826
3827     if (CCInfo.getNextStackOffset()) {
3828       // Check if the arguments are already laid out in the right way as
3829       // the caller's fixed stack objects.
3830       MachineFrameInfo *MFI = MF.getFrameInfo();
3831       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3832       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3833       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3834         CCValAssign &VA = ArgLocs[i];
3835         SDValue Arg = OutVals[i];
3836         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3837         if (VA.getLocInfo() == CCValAssign::Indirect)
3838           return false;
3839         if (!VA.isRegLoc()) {
3840           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3841                                    MFI, MRI, TII))
3842             return false;
3843         }
3844       }
3845     }
3846
3847     // If the tailcall address may be in a register, then make sure it's
3848     // possible to register allocate for it. In 32-bit, the call address can
3849     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3850     // callee-saved registers are restored. These happen to be the same
3851     // registers used to pass 'inreg' arguments so watch out for those.
3852     if (!Subtarget->is64Bit() &&
3853         ((!isa<GlobalAddressSDNode>(Callee) &&
3854           !isa<ExternalSymbolSDNode>(Callee)) ||
3855          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3856       unsigned NumInRegs = 0;
3857       // In PIC we need an extra register to formulate the address computation
3858       // for the callee.
3859       unsigned MaxInRegs =
3860         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3861
3862       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3863         CCValAssign &VA = ArgLocs[i];
3864         if (!VA.isRegLoc())
3865           continue;
3866         unsigned Reg = VA.getLocReg();
3867         switch (Reg) {
3868         default: break;
3869         case X86::EAX: case X86::EDX: case X86::ECX:
3870           if (++NumInRegs == MaxInRegs)
3871             return false;
3872           break;
3873         }
3874       }
3875     }
3876   }
3877
3878   bool CalleeWillPop =
3879       X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3880                        MF.getTarget().Options.GuaranteedTailCallOpt);
3881
3882   if (unsigned BytesToPop =
3883           MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3884     // If we have bytes to pop, the callee must pop them.
3885     bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3886     if (!CalleePopMatches)
3887       return false;
3888   } else if (CalleeWillPop && StackArgsSize > 0) {
3889     // If we don't have bytes to pop, make sure the callee doesn't pop any.
3890     return false;
3891   }
3892
3893   return true;
3894 }
3895
3896 FastISel *
3897 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3898                                   const TargetLibraryInfo *libInfo) const {
3899   return X86::createFastISel(funcInfo, libInfo);
3900 }
3901
3902 //===----------------------------------------------------------------------===//
3903 //                           Other Lowering Hooks
3904 //===----------------------------------------------------------------------===//
3905
3906 static bool MayFoldLoad(SDValue Op) {
3907   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3908 }
3909
3910 static bool MayFoldIntoStore(SDValue Op) {
3911   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3912 }
3913
3914 static bool isTargetShuffle(unsigned Opcode) {
3915   switch(Opcode) {
3916   default: return false;
3917   case X86ISD::BLENDI:
3918   case X86ISD::PSHUFB:
3919   case X86ISD::PSHUFD:
3920   case X86ISD::PSHUFHW:
3921   case X86ISD::PSHUFLW:
3922   case X86ISD::SHUFP:
3923   case X86ISD::INSERTPS:
3924   case X86ISD::PALIGNR:
3925   case X86ISD::MOVLHPS:
3926   case X86ISD::MOVLHPD:
3927   case X86ISD::MOVHLPS:
3928   case X86ISD::MOVLPS:
3929   case X86ISD::MOVLPD:
3930   case X86ISD::MOVSHDUP:
3931   case X86ISD::MOVSLDUP:
3932   case X86ISD::MOVDDUP:
3933   case X86ISD::MOVSS:
3934   case X86ISD::MOVSD:
3935   case X86ISD::UNPCKL:
3936   case X86ISD::UNPCKH:
3937   case X86ISD::VPERMILPI:
3938   case X86ISD::VPERM2X128:
3939   case X86ISD::VPERMI:
3940   case X86ISD::VPERMV:
3941   case X86ISD::VPERMV3:
3942     return true;
3943   }
3944 }
3945
3946 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3947                                     SDValue V1, unsigned TargetMask,
3948                                     SelectionDAG &DAG) {
3949   switch(Opc) {
3950   default: llvm_unreachable("Unknown x86 shuffle node");
3951   case X86ISD::PSHUFD:
3952   case X86ISD::PSHUFHW:
3953   case X86ISD::PSHUFLW:
3954   case X86ISD::VPERMILPI:
3955   case X86ISD::VPERMI:
3956     return DAG.getNode(Opc, dl, VT, V1,
3957                        DAG.getConstant(TargetMask, dl, MVT::i8));
3958   }
3959 }
3960
3961 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3962                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3963   switch(Opc) {
3964   default: llvm_unreachable("Unknown x86 shuffle node");
3965   case X86ISD::MOVLHPS:
3966   case X86ISD::MOVLHPD:
3967   case X86ISD::MOVHLPS:
3968   case X86ISD::MOVLPS:
3969   case X86ISD::MOVLPD:
3970   case X86ISD::MOVSS:
3971   case X86ISD::MOVSD:
3972   case X86ISD::UNPCKL:
3973   case X86ISD::UNPCKH:
3974     return DAG.getNode(Opc, dl, VT, V1, V2);
3975   }
3976 }
3977
3978 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3979   MachineFunction &MF = DAG.getMachineFunction();
3980   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3981   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3982   int ReturnAddrIndex = FuncInfo->getRAIndex();
3983
3984   if (ReturnAddrIndex == 0) {
3985     // Set up a frame object for the return address.
3986     unsigned SlotSize = RegInfo->getSlotSize();
3987     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3988                                                            -(int64_t)SlotSize,
3989                                                            false);
3990     FuncInfo->setRAIndex(ReturnAddrIndex);
3991   }
3992
3993   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3994 }
3995
3996 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3997                                        bool hasSymbolicDisplacement) {
3998   // Offset should fit into 32 bit immediate field.
3999   if (!isInt<32>(Offset))
4000     return false;
4001
4002   // If we don't have a symbolic displacement - we don't have any extra
4003   // restrictions.
4004   if (!hasSymbolicDisplacement)
4005     return true;
4006
4007   // FIXME: Some tweaks might be needed for medium code model.
4008   if (M != CodeModel::Small && M != CodeModel::Kernel)
4009     return false;
4010
4011   // For small code model we assume that latest object is 16MB before end of 31
4012   // bits boundary. We may also accept pretty large negative constants knowing
4013   // that all objects are in the positive half of address space.
4014   if (M == CodeModel::Small && Offset < 16*1024*1024)
4015     return true;
4016
4017   // For kernel code model we know that all object resist in the negative half
4018   // of 32bits address space. We may not accept negative offsets, since they may
4019   // be just off and we may accept pretty large positive ones.
4020   if (M == CodeModel::Kernel && Offset >= 0)
4021     return true;
4022
4023   return false;
4024 }
4025
4026 /// Determines whether the callee is required to pop its own arguments.
4027 /// Callee pop is necessary to support tail calls.
4028 bool X86::isCalleePop(CallingConv::ID CallingConv,
4029                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4030   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4031   // can guarantee TCO.
4032   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4033     return true;
4034
4035   switch (CallingConv) {
4036   default:
4037     return false;
4038   case CallingConv::X86_StdCall:
4039   case CallingConv::X86_FastCall:
4040   case CallingConv::X86_ThisCall:
4041   case CallingConv::X86_VectorCall:
4042     return !is64Bit;
4043   }
4044 }
4045
4046 /// \brief Return true if the condition is an unsigned comparison operation.
4047 static bool isX86CCUnsigned(unsigned X86CC) {
4048   switch (X86CC) {
4049   default: llvm_unreachable("Invalid integer condition!");
4050   case X86::COND_E:     return true;
4051   case X86::COND_G:     return false;
4052   case X86::COND_GE:    return false;
4053   case X86::COND_L:     return false;
4054   case X86::COND_LE:    return false;
4055   case X86::COND_NE:    return true;
4056   case X86::COND_B:     return true;
4057   case X86::COND_A:     return true;
4058   case X86::COND_BE:    return true;
4059   case X86::COND_AE:    return true;
4060   }
4061 }
4062
4063 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
4064   switch (SetCCOpcode) {
4065   default: llvm_unreachable("Invalid integer condition!");
4066   case ISD::SETEQ:  return X86::COND_E;
4067   case ISD::SETGT:  return X86::COND_G;
4068   case ISD::SETGE:  return X86::COND_GE;
4069   case ISD::SETLT:  return X86::COND_L;
4070   case ISD::SETLE:  return X86::COND_LE;
4071   case ISD::SETNE:  return X86::COND_NE;
4072   case ISD::SETULT: return X86::COND_B;
4073   case ISD::SETUGT: return X86::COND_A;
4074   case ISD::SETULE: return X86::COND_BE;
4075   case ISD::SETUGE: return X86::COND_AE;
4076   }
4077 }
4078
4079 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4080 /// condition code, returning the condition code and the LHS/RHS of the
4081 /// comparison to make.
4082 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
4083                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
4084   if (!isFP) {
4085     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4086       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4087         // X > -1   -> X == 0, jump !sign.
4088         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4089         return X86::COND_NS;
4090       }
4091       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4092         // X < 0   -> X == 0, jump on sign.
4093         return X86::COND_S;
4094       }
4095       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
4096         // X < 1   -> X <= 0
4097         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4098         return X86::COND_LE;
4099       }
4100     }
4101
4102     return TranslateIntegerX86CC(SetCCOpcode);
4103   }
4104
4105   // First determine if it is required or is profitable to flip the operands.
4106
4107   // If LHS is a foldable load, but RHS is not, flip the condition.
4108   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4109       !ISD::isNON_EXTLoad(RHS.getNode())) {
4110     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4111     std::swap(LHS, RHS);
4112   }
4113
4114   switch (SetCCOpcode) {
4115   default: break;
4116   case ISD::SETOLT:
4117   case ISD::SETOLE:
4118   case ISD::SETUGT:
4119   case ISD::SETUGE:
4120     std::swap(LHS, RHS);
4121     break;
4122   }
4123
4124   // On a floating point condition, the flags are set as follows:
4125   // ZF  PF  CF   op
4126   //  0 | 0 | 0 | X > Y
4127   //  0 | 0 | 1 | X < Y
4128   //  1 | 0 | 0 | X == Y
4129   //  1 | 1 | 1 | unordered
4130   switch (SetCCOpcode) {
4131   default: llvm_unreachable("Condcode should be pre-legalized away");
4132   case ISD::SETUEQ:
4133   case ISD::SETEQ:   return X86::COND_E;
4134   case ISD::SETOLT:              // flipped
4135   case ISD::SETOGT:
4136   case ISD::SETGT:   return X86::COND_A;
4137   case ISD::SETOLE:              // flipped
4138   case ISD::SETOGE:
4139   case ISD::SETGE:   return X86::COND_AE;
4140   case ISD::SETUGT:              // flipped
4141   case ISD::SETULT:
4142   case ISD::SETLT:   return X86::COND_B;
4143   case ISD::SETUGE:              // flipped
4144   case ISD::SETULE:
4145   case ISD::SETLE:   return X86::COND_BE;
4146   case ISD::SETONE:
4147   case ISD::SETNE:   return X86::COND_NE;
4148   case ISD::SETUO:   return X86::COND_P;
4149   case ISD::SETO:    return X86::COND_NP;
4150   case ISD::SETOEQ:
4151   case ISD::SETUNE:  return X86::COND_INVALID;
4152   }
4153 }
4154
4155 /// Is there a floating point cmov for the specific X86 condition code?
4156 /// Current x86 isa includes the following FP cmov instructions:
4157 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4158 static bool hasFPCMov(unsigned X86CC) {
4159   switch (X86CC) {
4160   default:
4161     return false;
4162   case X86::COND_B:
4163   case X86::COND_BE:
4164   case X86::COND_E:
4165   case X86::COND_P:
4166   case X86::COND_A:
4167   case X86::COND_AE:
4168   case X86::COND_NE:
4169   case X86::COND_NP:
4170     return true;
4171   }
4172 }
4173
4174 /// Returns true if the target can instruction select the
4175 /// specified FP immediate natively. If false, the legalizer will
4176 /// materialize the FP immediate as a load from a constant pool.
4177 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4178   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4179     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4180       return true;
4181   }
4182   return false;
4183 }
4184
4185 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4186                                               ISD::LoadExtType ExtTy,
4187                                               EVT NewVT) const {
4188   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4189   // relocation target a movq or addq instruction: don't let the load shrink.
4190   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4191   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4192     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4193       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4194   return true;
4195 }
4196
4197 /// \brief Returns true if it is beneficial to convert a load of a constant
4198 /// to just the constant itself.
4199 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4200                                                           Type *Ty) const {
4201   assert(Ty->isIntegerTy());
4202
4203   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4204   if (BitSize == 0 || BitSize > 64)
4205     return false;
4206   return true;
4207 }
4208
4209 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4210                                                 unsigned Index) const {
4211   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4212     return false;
4213
4214   return (Index == 0 || Index == ResVT.getVectorNumElements());
4215 }
4216
4217 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4218   // Speculate cttz only if we can directly use TZCNT.
4219   return Subtarget->hasBMI();
4220 }
4221
4222 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4223   // Speculate ctlz only if we can directly use LZCNT.
4224   return Subtarget->hasLZCNT();
4225 }
4226
4227 /// Return true if every element in Mask, beginning
4228 /// from position Pos and ending in Pos+Size is undef.
4229 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4230   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4231     if (0 <= Mask[i])
4232       return false;
4233   return true;
4234 }
4235
4236 /// Return true if Val is undef or if its value falls within the
4237 /// specified range (L, H].
4238 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4239   return (Val < 0) || (Val >= Low && Val < Hi);
4240 }
4241
4242 /// Val is either less than zero (undef) or equal to the specified value.
4243 static bool isUndefOrEqual(int Val, int CmpVal) {
4244   return (Val < 0 || Val == CmpVal);
4245 }
4246
4247 /// Return true if every element in Mask, beginning
4248 /// from position Pos and ending in Pos+Size, falls within the specified
4249 /// sequential range (Low, Low+Size]. or is undef.
4250 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4251                                        unsigned Pos, unsigned Size, int Low) {
4252   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4253     if (!isUndefOrEqual(Mask[i], Low))
4254       return false;
4255   return true;
4256 }
4257
4258 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4259 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4260 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4261   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4262   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4263     return false;
4264
4265   // The index should be aligned on a vecWidth-bit boundary.
4266   uint64_t Index =
4267     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4268
4269   MVT VT = N->getSimpleValueType(0);
4270   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4271   bool Result = (Index * ElSize) % vecWidth == 0;
4272
4273   return Result;
4274 }
4275
4276 /// Return true if the specified INSERT_SUBVECTOR
4277 /// operand specifies a subvector insert that is suitable for input to
4278 /// insertion of 128 or 256-bit subvectors
4279 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4280   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4281   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4282     return false;
4283   // The index should be aligned on a vecWidth-bit boundary.
4284   uint64_t Index =
4285     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4286
4287   MVT VT = N->getSimpleValueType(0);
4288   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4289   bool Result = (Index * ElSize) % vecWidth == 0;
4290
4291   return Result;
4292 }
4293
4294 bool X86::isVINSERT128Index(SDNode *N) {
4295   return isVINSERTIndex(N, 128);
4296 }
4297
4298 bool X86::isVINSERT256Index(SDNode *N) {
4299   return isVINSERTIndex(N, 256);
4300 }
4301
4302 bool X86::isVEXTRACT128Index(SDNode *N) {
4303   return isVEXTRACTIndex(N, 128);
4304 }
4305
4306 bool X86::isVEXTRACT256Index(SDNode *N) {
4307   return isVEXTRACTIndex(N, 256);
4308 }
4309
4310 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4311   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4312   assert(isa<ConstantSDNode>(N->getOperand(1).getNode()) &&
4313          "Illegal extract subvector for VEXTRACT");
4314
4315   uint64_t Index =
4316     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4317
4318   MVT VecVT = N->getOperand(0).getSimpleValueType();
4319   MVT ElVT = VecVT.getVectorElementType();
4320
4321   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4322   return Index / NumElemsPerChunk;
4323 }
4324
4325 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4326   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4327   assert(isa<ConstantSDNode>(N->getOperand(2).getNode()) &&
4328          "Illegal insert subvector for VINSERT");
4329
4330   uint64_t Index =
4331     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4332
4333   MVT VecVT = N->getSimpleValueType(0);
4334   MVT ElVT = VecVT.getVectorElementType();
4335
4336   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4337   return Index / NumElemsPerChunk;
4338 }
4339
4340 /// Return the appropriate immediate to extract the specified
4341 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4342 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4343   return getExtractVEXTRACTImmediate(N, 128);
4344 }
4345
4346 /// Return the appropriate immediate to extract the specified
4347 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4348 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4349   return getExtractVEXTRACTImmediate(N, 256);
4350 }
4351
4352 /// Return the appropriate immediate to insert at the specified
4353 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4354 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4355   return getInsertVINSERTImmediate(N, 128);
4356 }
4357
4358 /// Return the appropriate immediate to insert at the specified
4359 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4360 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4361   return getInsertVINSERTImmediate(N, 256);
4362 }
4363
4364 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4365 bool X86::isZeroNode(SDValue Elt) {
4366   return isNullConstant(Elt) || isNullFPConstant(Elt);
4367 }
4368
4369 // Build a vector of constants
4370 // Use an UNDEF node if MaskElt == -1.
4371 // Spilt 64-bit constants in the 32-bit mode.
4372 static SDValue getConstVector(ArrayRef<int> Values, MVT VT,
4373                               SelectionDAG &DAG,
4374                               SDLoc dl, bool IsMask = false) {
4375
4376   SmallVector<SDValue, 32>  Ops;
4377   bool Split = false;
4378
4379   MVT ConstVecVT = VT;
4380   unsigned NumElts = VT.getVectorNumElements();
4381   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4382   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4383     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4384     Split = true;
4385   }
4386
4387   MVT EltVT = ConstVecVT.getVectorElementType();
4388   for (unsigned i = 0; i < NumElts; ++i) {
4389     bool IsUndef = Values[i] < 0 && IsMask;
4390     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4391       DAG.getConstant(Values[i], dl, EltVT);
4392     Ops.push_back(OpNode);
4393     if (Split)
4394       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4395                     DAG.getConstant(0, dl, EltVT));
4396   }
4397   SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4398   if (Split)
4399     ConstsNode = DAG.getBitcast(VT, ConstsNode);
4400   return ConstsNode;
4401 }
4402
4403 /// Returns a vector of specified type with all zero elements.
4404 static SDValue getZeroVector(MVT VT, const X86Subtarget *Subtarget,
4405                              SelectionDAG &DAG, SDLoc dl) {
4406   assert(VT.isVector() && "Expected a vector type");
4407
4408   // Always build SSE zero vectors as <4 x i32> bitcasted
4409   // to their dest type. This ensures they get CSE'd.
4410   SDValue Vec;
4411   if (VT.is128BitVector()) {  // SSE
4412     if (Subtarget->hasSSE2()) {  // SSE2
4413       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4414       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4415     } else { // SSE1
4416       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4417       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4418     }
4419   } else if (VT.is256BitVector()) { // AVX
4420     if (Subtarget->hasInt256()) { // AVX2
4421       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4422       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4423       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4424     } else {
4425       // 256-bit logic and arithmetic instructions in AVX are all
4426       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4427       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4428       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4429       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4430     }
4431   } else if (VT.is512BitVector()) { // AVX-512
4432       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4433       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4434                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4435       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4436   } else if (VT.getVectorElementType() == MVT::i1) {
4437
4438     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4439             && "Unexpected vector type");
4440     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4441             && "Unexpected vector type");
4442     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4443     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4444     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4445   } else
4446     llvm_unreachable("Unexpected vector type");
4447
4448   return DAG.getBitcast(VT, Vec);
4449 }
4450
4451 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4452                                 SelectionDAG &DAG, SDLoc dl,
4453                                 unsigned vectorWidth) {
4454   assert((vectorWidth == 128 || vectorWidth == 256) &&
4455          "Unsupported vector width");
4456   EVT VT = Vec.getValueType();
4457   EVT ElVT = VT.getVectorElementType();
4458   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4459   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4460                                   VT.getVectorNumElements()/Factor);
4461
4462   // Extract from UNDEF is UNDEF.
4463   if (Vec.getOpcode() == ISD::UNDEF)
4464     return DAG.getUNDEF(ResultVT);
4465
4466   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4467   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4468   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4469
4470   // This is the index of the first element of the vectorWidth-bit chunk
4471   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4472   IdxVal &= ~(ElemsPerChunk - 1);
4473
4474   // If the input is a buildvector just emit a smaller one.
4475   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4476     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4477                        makeArrayRef(Vec->op_begin() + IdxVal, ElemsPerChunk));
4478
4479   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4480   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4481 }
4482
4483 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4484 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4485 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4486 /// instructions or a simple subregister reference. Idx is an index in the
4487 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4488 /// lowering EXTRACT_VECTOR_ELT operations easier.
4489 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4490                                    SelectionDAG &DAG, SDLoc dl) {
4491   assert((Vec.getValueType().is256BitVector() ||
4492           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4493   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4494 }
4495
4496 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4497 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4498                                    SelectionDAG &DAG, SDLoc dl) {
4499   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4500   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4501 }
4502
4503 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4504                                unsigned IdxVal, SelectionDAG &DAG,
4505                                SDLoc dl, unsigned vectorWidth) {
4506   assert((vectorWidth == 128 || vectorWidth == 256) &&
4507          "Unsupported vector width");
4508   // Inserting UNDEF is Result
4509   if (Vec.getOpcode() == ISD::UNDEF)
4510     return Result;
4511   EVT VT = Vec.getValueType();
4512   EVT ElVT = VT.getVectorElementType();
4513   EVT ResultVT = Result.getValueType();
4514
4515   // Insert the relevant vectorWidth bits.
4516   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4517   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4518
4519   // This is the index of the first element of the vectorWidth-bit chunk
4520   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4521   IdxVal &= ~(ElemsPerChunk - 1);
4522
4523   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4524   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4525 }
4526
4527 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4528 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4529 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4530 /// simple superregister reference.  Idx is an index in the 128 bits
4531 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4532 /// lowering INSERT_VECTOR_ELT operations easier.
4533 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4534                                   SelectionDAG &DAG, SDLoc dl) {
4535   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4536
4537   // For insertion into the zero index (low half) of a 256-bit vector, it is
4538   // more efficient to generate a blend with immediate instead of an insert*128.
4539   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4540   // extend the subvector to the size of the result vector. Make sure that
4541   // we are not recursing on that node by checking for undef here.
4542   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4543       Result.getOpcode() != ISD::UNDEF) {
4544     EVT ResultVT = Result.getValueType();
4545     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4546     SDValue Undef = DAG.getUNDEF(ResultVT);
4547     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4548                                  Vec, ZeroIndex);
4549
4550     // The blend instruction, and therefore its mask, depend on the data type.
4551     MVT ScalarType = ResultVT.getVectorElementType().getSimpleVT();
4552     if (ScalarType.isFloatingPoint()) {
4553       // Choose either vblendps (float) or vblendpd (double).
4554       unsigned ScalarSize = ScalarType.getSizeInBits();
4555       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4556       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4557       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4558       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4559     }
4560
4561     const X86Subtarget &Subtarget =
4562     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4563
4564     // AVX2 is needed for 256-bit integer blend support.
4565     // Integers must be cast to 32-bit because there is only vpblendd;
4566     // vpblendw can't be used for this because it has a handicapped mask.
4567
4568     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4569     // is still more efficient than using the wrong domain vinsertf128 that
4570     // will be created by InsertSubVector().
4571     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4572
4573     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4574     Result = DAG.getBitcast(CastVT, Result);
4575     Vec256 = DAG.getBitcast(CastVT, Vec256);
4576     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4577     return DAG.getBitcast(ResultVT, Vec256);
4578   }
4579
4580   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4581 }
4582
4583 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4584                                   SelectionDAG &DAG, SDLoc dl) {
4585   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4586   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4587 }
4588
4589 /// Insert i1-subvector to i1-vector.
4590 static SDValue Insert1BitVector(SDValue Op, SelectionDAG &DAG) {
4591
4592   SDLoc dl(Op);
4593   SDValue Vec = Op.getOperand(0);
4594   SDValue SubVec = Op.getOperand(1);
4595   SDValue Idx = Op.getOperand(2);
4596
4597   if (!isa<ConstantSDNode>(Idx))
4598     return SDValue();
4599
4600   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4601   if (IdxVal == 0  && Vec.isUndef()) // the operation is legal
4602     return Op;
4603
4604   MVT OpVT = Op.getSimpleValueType();
4605   MVT SubVecVT = SubVec.getSimpleValueType();
4606   unsigned NumElems = OpVT.getVectorNumElements();
4607   unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4608
4609   assert(IdxVal + SubVecNumElems <= NumElems &&
4610          IdxVal % SubVecVT.getSizeInBits() == 0 &&
4611          "Unexpected index value in INSERT_SUBVECTOR");
4612
4613   // There are 3 possible cases:
4614   // 1. Subvector should be inserted in the lower part (IdxVal == 0)
4615   // 2. Subvector should be inserted in the upper part
4616   //    (IdxVal + SubVecNumElems == NumElems)
4617   // 3. Subvector should be inserted in the middle (for example v2i1
4618   //    to v16i1, index 2)
4619
4620   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
4621   SDValue Undef = DAG.getUNDEF(OpVT);
4622   SDValue WideSubVec =
4623     DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef, SubVec, ZeroIdx);
4624   if (Vec.isUndef())
4625     return DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4626       DAG.getConstant(IdxVal, dl, MVT::i8));
4627
4628   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
4629     unsigned ShiftLeft = NumElems - SubVecNumElems;
4630     unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4631     WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4632       DAG.getConstant(ShiftLeft, dl, MVT::i8));
4633     return ShiftRight ? DAG.getNode(X86ISD::VSRLI, dl, OpVT, WideSubVec,
4634       DAG.getConstant(ShiftRight, dl, MVT::i8)) : WideSubVec;
4635   }
4636
4637   if (IdxVal == 0) {
4638     // Zero lower bits of the Vec
4639     SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4640     Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4641     Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4642     // Merge them together
4643     return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4644   }
4645
4646   // Simple case when we put subvector in the upper part
4647   if (IdxVal + SubVecNumElems == NumElems) {
4648     // Zero upper bits of the Vec
4649     WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec,
4650                         DAG.getConstant(IdxVal, dl, MVT::i8));
4651     SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4652     Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4653     Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4654     return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4655   }
4656   // Subvector should be inserted in the middle - use shuffle
4657   SmallVector<int, 64> Mask;
4658   for (unsigned i = 0; i < NumElems; ++i)
4659     Mask.push_back(i >= IdxVal && i < IdxVal + SubVecNumElems ?
4660                     i : i + NumElems);
4661   return DAG.getVectorShuffle(OpVT, dl, WideSubVec, Vec, Mask);
4662 }
4663
4664 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4665 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4666 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4667 /// large BUILD_VECTORS.
4668 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4669                                    unsigned NumElems, SelectionDAG &DAG,
4670                                    SDLoc dl) {
4671   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4672   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4673 }
4674
4675 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4676                                    unsigned NumElems, SelectionDAG &DAG,
4677                                    SDLoc dl) {
4678   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4679   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4680 }
4681
4682 /// Returns a vector of specified type with all bits set.
4683 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4684 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4685 /// Then bitcast to their original type, ensuring they get CSE'd.
4686 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4687                              SelectionDAG &DAG, SDLoc dl) {
4688   assert(VT.isVector() && "Expected a vector type");
4689
4690   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4691   SDValue Vec;
4692   if (VT.is512BitVector()) {
4693     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4694                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4695     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4696   } else if (VT.is256BitVector()) {
4697     if (Subtarget->hasInt256()) { // AVX2
4698       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4699       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4700     } else { // AVX
4701       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4702       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4703     }
4704   } else if (VT.is128BitVector()) {
4705     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4706   } else
4707     llvm_unreachable("Unexpected vector type");
4708
4709   return DAG.getBitcast(VT, Vec);
4710 }
4711
4712 /// Returns a vector_shuffle node for an unpackl operation.
4713 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4714                           SDValue V2) {
4715   unsigned NumElems = VT.getVectorNumElements();
4716   SmallVector<int, 8> Mask;
4717   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4718     Mask.push_back(i);
4719     Mask.push_back(i + NumElems);
4720   }
4721   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4722 }
4723
4724 /// Returns a vector_shuffle node for an unpackh operation.
4725 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4726                           SDValue V2) {
4727   unsigned NumElems = VT.getVectorNumElements();
4728   SmallVector<int, 8> Mask;
4729   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4730     Mask.push_back(i + Half);
4731     Mask.push_back(i + NumElems + Half);
4732   }
4733   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4734 }
4735
4736 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4737 /// This produces a shuffle where the low element of V2 is swizzled into the
4738 /// zero/undef vector, landing at element Idx.
4739 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4740 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4741                                            bool IsZero,
4742                                            const X86Subtarget *Subtarget,
4743                                            SelectionDAG &DAG) {
4744   MVT VT = V2.getSimpleValueType();
4745   SDValue V1 = IsZero
4746     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4747   unsigned NumElems = VT.getVectorNumElements();
4748   SmallVector<int, 16> MaskVec;
4749   for (unsigned i = 0; i != NumElems; ++i)
4750     // If this is the insertion idx, put the low elt of V2 here.
4751     MaskVec.push_back(i == Idx ? NumElems : i);
4752   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4753 }
4754
4755 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4756 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4757 /// uses one source. Note that this will set IsUnary for shuffles which use a
4758 /// single input multiple times, and in those cases it will
4759 /// adjust the mask to only have indices within that single input.
4760 static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
4761                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4762   unsigned NumElems = VT.getVectorNumElements();
4763   SDValue ImmN;
4764
4765   IsUnary = false;
4766   bool IsFakeUnary = false;
4767   switch(N->getOpcode()) {
4768   case X86ISD::BLENDI:
4769     ImmN = N->getOperand(N->getNumOperands()-1);
4770     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4771     break;
4772   case X86ISD::SHUFP:
4773     ImmN = N->getOperand(N->getNumOperands()-1);
4774     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4775     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4776     break;
4777   case X86ISD::INSERTPS:
4778     ImmN = N->getOperand(N->getNumOperands()-1);
4779     DecodeINSERTPSMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4780     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4781     break;
4782   case X86ISD::UNPCKH:
4783     DecodeUNPCKHMask(VT, Mask);
4784     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4785     break;
4786   case X86ISD::UNPCKL:
4787     DecodeUNPCKLMask(VT, Mask);
4788     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4789     break;
4790   case X86ISD::MOVHLPS:
4791     DecodeMOVHLPSMask(NumElems, Mask);
4792     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4793     break;
4794   case X86ISD::MOVLHPS:
4795     DecodeMOVLHPSMask(NumElems, Mask);
4796     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4797     break;
4798   case X86ISD::PALIGNR:
4799     ImmN = N->getOperand(N->getNumOperands()-1);
4800     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4801     break;
4802   case X86ISD::PSHUFD:
4803   case X86ISD::VPERMILPI:
4804     ImmN = N->getOperand(N->getNumOperands()-1);
4805     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4806     IsUnary = true;
4807     break;
4808   case X86ISD::PSHUFHW:
4809     ImmN = N->getOperand(N->getNumOperands()-1);
4810     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4811     IsUnary = true;
4812     break;
4813   case X86ISD::PSHUFLW:
4814     ImmN = N->getOperand(N->getNumOperands()-1);
4815     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4816     IsUnary = true;
4817     break;
4818   case X86ISD::PSHUFB: {
4819     IsUnary = true;
4820     SDValue MaskNode = N->getOperand(1);
4821     while (MaskNode->getOpcode() == ISD::BITCAST)
4822       MaskNode = MaskNode->getOperand(0);
4823
4824     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4825       // If we have a build-vector, then things are easy.
4826       MVT VT = MaskNode.getSimpleValueType();
4827       assert(VT.isVector() &&
4828              "Can't produce a non-vector with a build_vector!");
4829       if (!VT.isInteger())
4830         return false;
4831
4832       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4833
4834       SmallVector<uint64_t, 32> RawMask;
4835       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4836         SDValue Op = MaskNode->getOperand(i);
4837         if (Op->getOpcode() == ISD::UNDEF) {
4838           RawMask.push_back((uint64_t)SM_SentinelUndef);
4839           continue;
4840         }
4841         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4842         if (!CN)
4843           return false;
4844         APInt MaskElement = CN->getAPIntValue();
4845
4846         // We now have to decode the element which could be any integer size and
4847         // extract each byte of it.
4848         for (int j = 0; j < NumBytesPerElement; ++j) {
4849           // Note that this is x86 and so always little endian: the low byte is
4850           // the first byte of the mask.
4851           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4852           MaskElement = MaskElement.lshr(8);
4853         }
4854       }
4855       DecodePSHUFBMask(RawMask, Mask);
4856       break;
4857     }
4858
4859     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4860     if (!MaskLoad)
4861       return false;
4862
4863     SDValue Ptr = MaskLoad->getBasePtr();
4864     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4865         Ptr->getOpcode() == X86ISD::WrapperRIP)
4866       Ptr = Ptr->getOperand(0);
4867
4868     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4869     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4870       return false;
4871
4872     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4873       DecodePSHUFBMask(C, Mask);
4874       break;
4875     }
4876
4877     return false;
4878   }
4879   case X86ISD::VPERMI:
4880     ImmN = N->getOperand(N->getNumOperands()-1);
4881     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4882     IsUnary = true;
4883     break;
4884   case X86ISD::MOVSS:
4885   case X86ISD::MOVSD:
4886     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4887     break;
4888   case X86ISD::VPERM2X128:
4889     ImmN = N->getOperand(N->getNumOperands()-1);
4890     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4891     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4892     break;
4893   case X86ISD::MOVSLDUP:
4894     DecodeMOVSLDUPMask(VT, Mask);
4895     IsUnary = true;
4896     break;
4897   case X86ISD::MOVSHDUP:
4898     DecodeMOVSHDUPMask(VT, Mask);
4899     IsUnary = true;
4900     break;
4901   case X86ISD::MOVDDUP:
4902     DecodeMOVDDUPMask(VT, Mask);
4903     IsUnary = true;
4904     break;
4905   case X86ISD::MOVLHPD:
4906   case X86ISD::MOVLPD:
4907   case X86ISD::MOVLPS:
4908     // Not yet implemented
4909     return false;
4910   case X86ISD::VPERMV: {
4911     IsUnary = true;
4912     SDValue MaskNode = N->getOperand(0);
4913     while (MaskNode->getOpcode() == ISD::BITCAST)
4914       MaskNode = MaskNode->getOperand(0);
4915
4916     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4917     SmallVector<uint64_t, 32> RawMask;
4918     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4919       // If we have a build-vector, then things are easy.
4920       assert(MaskNode.getSimpleValueType().isInteger() &&
4921              MaskNode.getSimpleValueType().getVectorNumElements() ==
4922              VT.getVectorNumElements());
4923
4924       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4925         SDValue Op = MaskNode->getOperand(i);
4926         if (Op->getOpcode() == ISD::UNDEF)
4927           RawMask.push_back((uint64_t)SM_SentinelUndef);
4928         else if (isa<ConstantSDNode>(Op)) {
4929           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4930           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4931         } else
4932           return false;
4933       }
4934       DecodeVPERMVMask(RawMask, Mask);
4935       break;
4936     }
4937     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4938       unsigned NumEltsInMask = MaskNode->getNumOperands();
4939       MaskNode = MaskNode->getOperand(0);
4940       if (auto *CN = dyn_cast<ConstantSDNode>(MaskNode)) {
4941         APInt MaskEltValue = CN->getAPIntValue();
4942         for (unsigned i = 0; i < NumEltsInMask; ++i)
4943           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4944         DecodeVPERMVMask(RawMask, Mask);
4945         break;
4946       }
4947       // It may be a scalar load
4948     }
4949
4950     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4951     if (!MaskLoad)
4952       return false;
4953
4954     SDValue Ptr = MaskLoad->getBasePtr();
4955     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4956         Ptr->getOpcode() == X86ISD::WrapperRIP)
4957       Ptr = Ptr->getOperand(0);
4958
4959     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4960     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4961       return false;
4962
4963     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4964       DecodeVPERMVMask(C, VT, Mask);
4965       break;
4966     }
4967     return false;
4968   }
4969   case X86ISD::VPERMV3: {
4970     IsUnary = false;
4971     SDValue MaskNode = N->getOperand(1);
4972     while (MaskNode->getOpcode() == ISD::BITCAST)
4973       MaskNode = MaskNode->getOperand(1);
4974
4975     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4976       // If we have a build-vector, then things are easy.
4977       assert(MaskNode.getSimpleValueType().isInteger() &&
4978              MaskNode.getSimpleValueType().getVectorNumElements() ==
4979              VT.getVectorNumElements());
4980
4981       SmallVector<uint64_t, 32> RawMask;
4982       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4983
4984       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4985         SDValue Op = MaskNode->getOperand(i);
4986         if (Op->getOpcode() == ISD::UNDEF)
4987           RawMask.push_back((uint64_t)SM_SentinelUndef);
4988         else {
4989           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4990           if (!CN)
4991             return false;
4992           APInt MaskElement = CN->getAPIntValue();
4993           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4994         }
4995       }
4996       DecodeVPERMV3Mask(RawMask, Mask);
4997       break;
4998     }
4999
5000     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5001     if (!MaskLoad)
5002       return false;
5003
5004     SDValue Ptr = MaskLoad->getBasePtr();
5005     if (Ptr->getOpcode() == X86ISD::Wrapper ||
5006         Ptr->getOpcode() == X86ISD::WrapperRIP)
5007       Ptr = Ptr->getOperand(0);
5008
5009     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5010     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5011       return false;
5012
5013     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
5014       DecodeVPERMV3Mask(C, VT, Mask);
5015       break;
5016     }
5017     return false;
5018   }
5019   default: llvm_unreachable("unknown target shuffle node");
5020   }
5021
5022   // Empty mask indicates the decode failed.
5023   if (Mask.empty())
5024     return false;
5025
5026   // Check if we're getting a shuffle mask with zero'd elements.
5027   if (!AllowSentinelZero)
5028     if (std::any_of(Mask.begin(), Mask.end(),
5029                     [](int M){ return M == SM_SentinelZero; }))
5030       return false;
5031
5032   // If we have a fake unary shuffle, the shuffle mask is spread across two
5033   // inputs that are actually the same node. Re-map the mask to always point
5034   // into the first input.
5035   if (IsFakeUnary)
5036     for (int &M : Mask)
5037       if (M >= (int)Mask.size())
5038         M -= Mask.size();
5039
5040   return true;
5041 }
5042
5043 /// Returns the scalar element that will make up the ith
5044 /// element of the result of the vector shuffle.
5045 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5046                                    unsigned Depth) {
5047   if (Depth == 6)
5048     return SDValue();  // Limit search depth.
5049
5050   SDValue V = SDValue(N, 0);
5051   EVT VT = V.getValueType();
5052   unsigned Opcode = V.getOpcode();
5053
5054   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5055   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5056     int Elt = SV->getMaskElt(Index);
5057
5058     if (Elt < 0)
5059       return DAG.getUNDEF(VT.getVectorElementType());
5060
5061     unsigned NumElems = VT.getVectorNumElements();
5062     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5063                                          : SV->getOperand(1);
5064     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5065   }
5066
5067   // Recurse into target specific vector shuffles to find scalars.
5068   if (isTargetShuffle(Opcode)) {
5069     MVT ShufVT = V.getSimpleValueType();
5070     int NumElems = (int)ShufVT.getVectorNumElements();
5071     SmallVector<int, 16> ShuffleMask;
5072     bool IsUnary;
5073
5074     if (!getTargetShuffleMask(N, ShufVT, false, ShuffleMask, IsUnary))
5075       return SDValue();
5076
5077     int Elt = ShuffleMask[Index];
5078     if (Elt == SM_SentinelUndef)
5079       return DAG.getUNDEF(ShufVT.getVectorElementType());
5080
5081     assert(0 <= Elt && Elt < (2*NumElems) && "Shuffle index out of range");
5082     SDValue NewV = (Elt < NumElems) ? N->getOperand(0) : N->getOperand(1);
5083     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5084                                Depth+1);
5085   }
5086
5087   // Actual nodes that may contain scalar elements
5088   if (Opcode == ISD::BITCAST) {
5089     V = V.getOperand(0);
5090     EVT SrcVT = V.getValueType();
5091     unsigned NumElems = VT.getVectorNumElements();
5092
5093     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5094       return SDValue();
5095   }
5096
5097   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5098     return (Index == 0) ? V.getOperand(0)
5099                         : DAG.getUNDEF(VT.getVectorElementType());
5100
5101   if (V.getOpcode() == ISD::BUILD_VECTOR)
5102     return V.getOperand(Index);
5103
5104   return SDValue();
5105 }
5106
5107 /// Custom lower build_vector of v16i8.
5108 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5109                                        unsigned NumNonZero, unsigned NumZero,
5110                                        SelectionDAG &DAG,
5111                                        const X86Subtarget* Subtarget,
5112                                        const TargetLowering &TLI) {
5113   if (NumNonZero > 8)
5114     return SDValue();
5115
5116   SDLoc dl(Op);
5117   SDValue V;
5118   bool First = true;
5119
5120   // SSE4.1 - use PINSRB to insert each byte directly.
5121   if (Subtarget->hasSSE41()) {
5122     for (unsigned i = 0; i < 16; ++i) {
5123       bool isNonZero = (NonZeros & (1 << i)) != 0;
5124       if (isNonZero) {
5125         if (First) {
5126           if (NumZero)
5127             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
5128           else
5129             V = DAG.getUNDEF(MVT::v16i8);
5130           First = false;
5131         }
5132         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5133                         MVT::v16i8, V, Op.getOperand(i),
5134                         DAG.getIntPtrConstant(i, dl));
5135       }
5136     }
5137
5138     return V;
5139   }
5140
5141   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
5142   for (unsigned i = 0; i < 16; ++i) {
5143     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5144     if (ThisIsNonZero && First) {
5145       if (NumZero)
5146         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5147       else
5148         V = DAG.getUNDEF(MVT::v8i16);
5149       First = false;
5150     }
5151
5152     if ((i & 1) != 0) {
5153       SDValue ThisElt, LastElt;
5154       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5155       if (LastIsNonZero) {
5156         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5157                               MVT::i16, Op.getOperand(i-1));
5158       }
5159       if (ThisIsNonZero) {
5160         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5161         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5162                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
5163         if (LastIsNonZero)
5164           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5165       } else
5166         ThisElt = LastElt;
5167
5168       if (ThisElt.getNode())
5169         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5170                         DAG.getIntPtrConstant(i/2, dl));
5171     }
5172   }
5173
5174   return DAG.getBitcast(MVT::v16i8, V);
5175 }
5176
5177 /// Custom lower build_vector of v8i16.
5178 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5179                                      unsigned NumNonZero, unsigned NumZero,
5180                                      SelectionDAG &DAG,
5181                                      const X86Subtarget* Subtarget,
5182                                      const TargetLowering &TLI) {
5183   if (NumNonZero > 4)
5184     return SDValue();
5185
5186   SDLoc dl(Op);
5187   SDValue V;
5188   bool First = true;
5189   for (unsigned i = 0; i < 8; ++i) {
5190     bool isNonZero = (NonZeros & (1 << i)) != 0;
5191     if (isNonZero) {
5192       if (First) {
5193         if (NumZero)
5194           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5195         else
5196           V = DAG.getUNDEF(MVT::v8i16);
5197         First = false;
5198       }
5199       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5200                       MVT::v8i16, V, Op.getOperand(i),
5201                       DAG.getIntPtrConstant(i, dl));
5202     }
5203   }
5204
5205   return V;
5206 }
5207
5208 /// Custom lower build_vector of v4i32 or v4f32.
5209 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5210                                      const X86Subtarget *Subtarget,
5211                                      const TargetLowering &TLI) {
5212   // Find all zeroable elements.
5213   std::bitset<4> Zeroable;
5214   for (int i=0; i < 4; ++i) {
5215     SDValue Elt = Op->getOperand(i);
5216     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5217   }
5218   assert(Zeroable.size() - Zeroable.count() > 1 &&
5219          "We expect at least two non-zero elements!");
5220
5221   // We only know how to deal with build_vector nodes where elements are either
5222   // zeroable or extract_vector_elt with constant index.
5223   SDValue FirstNonZero;
5224   unsigned FirstNonZeroIdx;
5225   for (unsigned i=0; i < 4; ++i) {
5226     if (Zeroable[i])
5227       continue;
5228     SDValue Elt = Op->getOperand(i);
5229     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5230         !isa<ConstantSDNode>(Elt.getOperand(1)))
5231       return SDValue();
5232     // Make sure that this node is extracting from a 128-bit vector.
5233     MVT VT = Elt.getOperand(0).getSimpleValueType();
5234     if (!VT.is128BitVector())
5235       return SDValue();
5236     if (!FirstNonZero.getNode()) {
5237       FirstNonZero = Elt;
5238       FirstNonZeroIdx = i;
5239     }
5240   }
5241
5242   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5243   SDValue V1 = FirstNonZero.getOperand(0);
5244   MVT VT = V1.getSimpleValueType();
5245
5246   // See if this build_vector can be lowered as a blend with zero.
5247   SDValue Elt;
5248   unsigned EltMaskIdx, EltIdx;
5249   int Mask[4];
5250   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5251     if (Zeroable[EltIdx]) {
5252       // The zero vector will be on the right hand side.
5253       Mask[EltIdx] = EltIdx+4;
5254       continue;
5255     }
5256
5257     Elt = Op->getOperand(EltIdx);
5258     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5259     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5260     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5261       break;
5262     Mask[EltIdx] = EltIdx;
5263   }
5264
5265   if (EltIdx == 4) {
5266     // Let the shuffle legalizer deal with blend operations.
5267     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5268     if (V1.getSimpleValueType() != VT)
5269       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5270     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5271   }
5272
5273   // See if we can lower this build_vector to a INSERTPS.
5274   if (!Subtarget->hasSSE41())
5275     return SDValue();
5276
5277   SDValue V2 = Elt.getOperand(0);
5278   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5279     V1 = SDValue();
5280
5281   bool CanFold = true;
5282   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5283     if (Zeroable[i])
5284       continue;
5285
5286     SDValue Current = Op->getOperand(i);
5287     SDValue SrcVector = Current->getOperand(0);
5288     if (!V1.getNode())
5289       V1 = SrcVector;
5290     CanFold = SrcVector == V1 &&
5291       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5292   }
5293
5294   if (!CanFold)
5295     return SDValue();
5296
5297   assert(V1.getNode() && "Expected at least two non-zero elements!");
5298   if (V1.getSimpleValueType() != MVT::v4f32)
5299     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5300   if (V2.getSimpleValueType() != MVT::v4f32)
5301     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5302
5303   // Ok, we can emit an INSERTPS instruction.
5304   unsigned ZMask = Zeroable.to_ulong();
5305
5306   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5307   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5308   SDLoc DL(Op);
5309   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5310                                DAG.getIntPtrConstant(InsertPSMask, DL));
5311   return DAG.getBitcast(VT, Result);
5312 }
5313
5314 /// Return a vector logical shift node.
5315 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5316                          unsigned NumBits, SelectionDAG &DAG,
5317                          const TargetLowering &TLI, SDLoc dl) {
5318   assert(VT.is128BitVector() && "Unknown type for VShift");
5319   MVT ShVT = MVT::v2i64;
5320   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5321   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5322   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5323   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5324   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5325   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5326 }
5327
5328 static SDValue
5329 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5330
5331   // Check if the scalar load can be widened into a vector load. And if
5332   // the address is "base + cst" see if the cst can be "absorbed" into
5333   // the shuffle mask.
5334   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5335     SDValue Ptr = LD->getBasePtr();
5336     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5337       return SDValue();
5338     EVT PVT = LD->getValueType(0);
5339     if (PVT != MVT::i32 && PVT != MVT::f32)
5340       return SDValue();
5341
5342     int FI = -1;
5343     int64_t Offset = 0;
5344     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5345       FI = FINode->getIndex();
5346       Offset = 0;
5347     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5348                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5349       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5350       Offset = Ptr.getConstantOperandVal(1);
5351       Ptr = Ptr.getOperand(0);
5352     } else {
5353       return SDValue();
5354     }
5355
5356     // FIXME: 256-bit vector instructions don't require a strict alignment,
5357     // improve this code to support it better.
5358     unsigned RequiredAlign = VT.getSizeInBits()/8;
5359     SDValue Chain = LD->getChain();
5360     // Make sure the stack object alignment is at least 16 or 32.
5361     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5362     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5363       if (MFI->isFixedObjectIndex(FI)) {
5364         // Can't change the alignment. FIXME: It's possible to compute
5365         // the exact stack offset and reference FI + adjust offset instead.
5366         // If someone *really* cares about this. That's the way to implement it.
5367         return SDValue();
5368       } else {
5369         MFI->setObjectAlignment(FI, RequiredAlign);
5370       }
5371     }
5372
5373     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5374     // Ptr + (Offset & ~15).
5375     if (Offset < 0)
5376       return SDValue();
5377     if ((Offset % RequiredAlign) & 3)
5378       return SDValue();
5379     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5380     if (StartOffset) {
5381       SDLoc DL(Ptr);
5382       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5383                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5384     }
5385
5386     int EltNo = (Offset - StartOffset) >> 2;
5387     unsigned NumElems = VT.getVectorNumElements();
5388
5389     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5390     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5391                              LD->getPointerInfo().getWithOffset(StartOffset),
5392                              false, false, false, 0);
5393
5394     SmallVector<int, 8> Mask(NumElems, EltNo);
5395
5396     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5397   }
5398
5399   return SDValue();
5400 }
5401
5402 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5403 /// elements can be replaced by a single large load which has the same value as
5404 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5405 ///
5406 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5407 ///
5408 /// FIXME: we'd also like to handle the case where the last elements are zero
5409 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5410 /// There's even a handy isZeroNode for that purpose.
5411 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5412                                         SDLoc &DL, SelectionDAG &DAG,
5413                                         bool isAfterLegalize) {
5414   unsigned NumElems = Elts.size();
5415
5416   LoadSDNode *LDBase = nullptr;
5417   unsigned LastLoadedElt = -1U;
5418
5419   // For each element in the initializer, see if we've found a load or an undef.
5420   // If we don't find an initial load element, or later load elements are
5421   // non-consecutive, bail out.
5422   for (unsigned i = 0; i < NumElems; ++i) {
5423     SDValue Elt = Elts[i];
5424     // Look through a bitcast.
5425     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5426       Elt = Elt.getOperand(0);
5427     if (!Elt.getNode() ||
5428         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5429       return SDValue();
5430     if (!LDBase) {
5431       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5432         return SDValue();
5433       LDBase = cast<LoadSDNode>(Elt.getNode());
5434       LastLoadedElt = i;
5435       continue;
5436     }
5437     if (Elt.getOpcode() == ISD::UNDEF)
5438       continue;
5439
5440     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5441     EVT LdVT = Elt.getValueType();
5442     // Each loaded element must be the correct fractional portion of the
5443     // requested vector load.
5444     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5445       return SDValue();
5446     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5447       return SDValue();
5448     LastLoadedElt = i;
5449   }
5450
5451   // If we have found an entire vector of loads and undefs, then return a large
5452   // load of the entire vector width starting at the base pointer.  If we found
5453   // consecutive loads for the low half, generate a vzext_load node.
5454   if (LastLoadedElt == NumElems - 1) {
5455     assert(LDBase && "Did not find base load for merging consecutive loads");
5456     EVT EltVT = LDBase->getValueType(0);
5457     // Ensure that the input vector size for the merged loads matches the
5458     // cumulative size of the input elements.
5459     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5460       return SDValue();
5461
5462     if (isAfterLegalize &&
5463         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5464       return SDValue();
5465
5466     SDValue NewLd = SDValue();
5467
5468     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5469                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5470                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5471                         LDBase->getAlignment());
5472
5473     if (LDBase->hasAnyUseOfValue(1)) {
5474       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5475                                      SDValue(LDBase, 1),
5476                                      SDValue(NewLd.getNode(), 1));
5477       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5478       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5479                              SDValue(NewLd.getNode(), 1));
5480     }
5481
5482     return NewLd;
5483   }
5484
5485   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5486   //of a v4i32 / v4f32. It's probably worth generalizing.
5487   EVT EltVT = VT.getVectorElementType();
5488   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5489       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5490     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5491     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5492     SDValue ResNode =
5493         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5494                                 LDBase->getPointerInfo(),
5495                                 LDBase->getAlignment(),
5496                                 false/*isVolatile*/, true/*ReadMem*/,
5497                                 false/*WriteMem*/);
5498
5499     // Make sure the newly-created LOAD is in the same position as LDBase in
5500     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5501     // update uses of LDBase's output chain to use the TokenFactor.
5502     if (LDBase->hasAnyUseOfValue(1)) {
5503       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5504                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5505       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5506       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5507                              SDValue(ResNode.getNode(), 1));
5508     }
5509
5510     return DAG.getBitcast(VT, ResNode);
5511   }
5512   return SDValue();
5513 }
5514
5515 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5516 /// to generate a splat value for the following cases:
5517 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5518 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5519 /// a scalar load, or a constant.
5520 /// The VBROADCAST node is returned when a pattern is found,
5521 /// or SDValue() otherwise.
5522 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5523                                     SelectionDAG &DAG) {
5524   // VBROADCAST requires AVX.
5525   // TODO: Splats could be generated for non-AVX CPUs using SSE
5526   // instructions, but there's less potential gain for only 128-bit vectors.
5527   if (!Subtarget->hasAVX())
5528     return SDValue();
5529
5530   MVT VT = Op.getSimpleValueType();
5531   SDLoc dl(Op);
5532
5533   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5534          "Unsupported vector type for broadcast.");
5535
5536   SDValue Ld;
5537   bool ConstSplatVal;
5538
5539   switch (Op.getOpcode()) {
5540     default:
5541       // Unknown pattern found.
5542       return SDValue();
5543
5544     case ISD::BUILD_VECTOR: {
5545       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5546       BitVector UndefElements;
5547       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5548
5549       // We need a splat of a single value to use broadcast, and it doesn't
5550       // make any sense if the value is only in one element of the vector.
5551       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5552         return SDValue();
5553
5554       Ld = Splat;
5555       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5556                        Ld.getOpcode() == ISD::ConstantFP);
5557
5558       // Make sure that all of the users of a non-constant load are from the
5559       // BUILD_VECTOR node.
5560       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5561         return SDValue();
5562       break;
5563     }
5564
5565     case ISD::VECTOR_SHUFFLE: {
5566       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5567
5568       // Shuffles must have a splat mask where the first element is
5569       // broadcasted.
5570       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5571         return SDValue();
5572
5573       SDValue Sc = Op.getOperand(0);
5574       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5575           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5576
5577         if (!Subtarget->hasInt256())
5578           return SDValue();
5579
5580         // Use the register form of the broadcast instruction available on AVX2.
5581         if (VT.getSizeInBits() >= 256)
5582           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5583         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5584       }
5585
5586       Ld = Sc.getOperand(0);
5587       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5588                        Ld.getOpcode() == ISD::ConstantFP);
5589
5590       // The scalar_to_vector node and the suspected
5591       // load node must have exactly one user.
5592       // Constants may have multiple users.
5593
5594       // AVX-512 has register version of the broadcast
5595       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5596         Ld.getValueType().getSizeInBits() >= 32;
5597       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5598           !hasRegVer))
5599         return SDValue();
5600       break;
5601     }
5602   }
5603
5604   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5605   bool IsGE256 = (VT.getSizeInBits() >= 256);
5606
5607   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5608   // instruction to save 8 or more bytes of constant pool data.
5609   // TODO: If multiple splats are generated to load the same constant,
5610   // it may be detrimental to overall size. There needs to be a way to detect
5611   // that condition to know if this is truly a size win.
5612   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5613
5614   // Handle broadcasting a single constant scalar from the constant pool
5615   // into a vector.
5616   // On Sandybridge (no AVX2), it is still better to load a constant vector
5617   // from the constant pool and not to broadcast it from a scalar.
5618   // But override that restriction when optimizing for size.
5619   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5620   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5621     EVT CVT = Ld.getValueType();
5622     assert(!CVT.isVector() && "Must not broadcast a vector type");
5623
5624     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5625     // For size optimization, also splat v2f64 and v2i64, and for size opt
5626     // with AVX2, also splat i8 and i16.
5627     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5628     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5629         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5630       const Constant *C = nullptr;
5631       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5632         C = CI->getConstantIntValue();
5633       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5634         C = CF->getConstantFPValue();
5635
5636       assert(C && "Invalid constant type");
5637
5638       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5639       SDValue CP =
5640           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5641       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5642       Ld = DAG.getLoad(
5643           CVT, dl, DAG.getEntryNode(), CP,
5644           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5645           false, false, Alignment);
5646
5647       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5648     }
5649   }
5650
5651   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5652
5653   // Handle AVX2 in-register broadcasts.
5654   if (!IsLoad && Subtarget->hasInt256() &&
5655       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5656     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5657
5658   // The scalar source must be a normal load.
5659   if (!IsLoad)
5660     return SDValue();
5661
5662   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5663       (Subtarget->hasVLX() && ScalarSize == 64))
5664     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5665
5666   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5667   // double since there is no vbroadcastsd xmm
5668   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5669     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5670       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5671   }
5672
5673   // Unsupported broadcast.
5674   return SDValue();
5675 }
5676
5677 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5678 /// underlying vector and index.
5679 ///
5680 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5681 /// index.
5682 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5683                                          SDValue ExtIdx) {
5684   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5685   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5686     return Idx;
5687
5688   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5689   // lowered this:
5690   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5691   // to:
5692   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5693   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5694   //                           undef)
5695   //                       Constant<0>)
5696   // In this case the vector is the extract_subvector expression and the index
5697   // is 2, as specified by the shuffle.
5698   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5699   SDValue ShuffleVec = SVOp->getOperand(0);
5700   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5701   assert(ShuffleVecVT.getVectorElementType() ==
5702          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5703
5704   int ShuffleIdx = SVOp->getMaskElt(Idx);
5705   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5706     ExtractedFromVec = ShuffleVec;
5707     return ShuffleIdx;
5708   }
5709   return Idx;
5710 }
5711
5712 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5713   MVT VT = Op.getSimpleValueType();
5714
5715   // Skip if insert_vec_elt is not supported.
5716   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5717   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5718     return SDValue();
5719
5720   SDLoc DL(Op);
5721   unsigned NumElems = Op.getNumOperands();
5722
5723   SDValue VecIn1;
5724   SDValue VecIn2;
5725   SmallVector<unsigned, 4> InsertIndices;
5726   SmallVector<int, 8> Mask(NumElems, -1);
5727
5728   for (unsigned i = 0; i != NumElems; ++i) {
5729     unsigned Opc = Op.getOperand(i).getOpcode();
5730
5731     if (Opc == ISD::UNDEF)
5732       continue;
5733
5734     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5735       // Quit if more than 1 elements need inserting.
5736       if (InsertIndices.size() > 1)
5737         return SDValue();
5738
5739       InsertIndices.push_back(i);
5740       continue;
5741     }
5742
5743     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5744     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5745     // Quit if non-constant index.
5746     if (!isa<ConstantSDNode>(ExtIdx))
5747       return SDValue();
5748     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5749
5750     // Quit if extracted from vector of different type.
5751     if (ExtractedFromVec.getValueType() != VT)
5752       return SDValue();
5753
5754     if (!VecIn1.getNode())
5755       VecIn1 = ExtractedFromVec;
5756     else if (VecIn1 != ExtractedFromVec) {
5757       if (!VecIn2.getNode())
5758         VecIn2 = ExtractedFromVec;
5759       else if (VecIn2 != ExtractedFromVec)
5760         // Quit if more than 2 vectors to shuffle
5761         return SDValue();
5762     }
5763
5764     if (ExtractedFromVec == VecIn1)
5765       Mask[i] = Idx;
5766     else if (ExtractedFromVec == VecIn2)
5767       Mask[i] = Idx + NumElems;
5768   }
5769
5770   if (!VecIn1.getNode())
5771     return SDValue();
5772
5773   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5774   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5775   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5776     unsigned Idx = InsertIndices[i];
5777     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5778                      DAG.getIntPtrConstant(Idx, DL));
5779   }
5780
5781   return NV;
5782 }
5783
5784 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5785   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5786          Op.getScalarValueSizeInBits() == 1 &&
5787          "Can not convert non-constant vector");
5788   uint64_t Immediate = 0;
5789   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5790     SDValue In = Op.getOperand(idx);
5791     if (In.getOpcode() != ISD::UNDEF)
5792       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5793   }
5794   SDLoc dl(Op);
5795   MVT VT =
5796    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5797   return DAG.getConstant(Immediate, dl, VT);
5798 }
5799 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5800 SDValue
5801 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5802
5803   MVT VT = Op.getSimpleValueType();
5804   assert((VT.getVectorElementType() == MVT::i1) &&
5805          "Unexpected type in LowerBUILD_VECTORvXi1!");
5806
5807   SDLoc dl(Op);
5808   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5809     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5810     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5811     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5812   }
5813
5814   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5815     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5816     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5817     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5818   }
5819
5820   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5821     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5822     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5823       return DAG.getBitcast(VT, Imm);
5824     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5825     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5826                         DAG.getIntPtrConstant(0, dl));
5827   }
5828
5829   // Vector has one or more non-const elements
5830   uint64_t Immediate = 0;
5831   SmallVector<unsigned, 16> NonConstIdx;
5832   bool IsSplat = true;
5833   bool HasConstElts = false;
5834   int SplatIdx = -1;
5835   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5836     SDValue In = Op.getOperand(idx);
5837     if (In.getOpcode() == ISD::UNDEF)
5838       continue;
5839     if (!isa<ConstantSDNode>(In))
5840       NonConstIdx.push_back(idx);
5841     else {
5842       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5843       HasConstElts = true;
5844     }
5845     if (SplatIdx == -1)
5846       SplatIdx = idx;
5847     else if (In != Op.getOperand(SplatIdx))
5848       IsSplat = false;
5849   }
5850
5851   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5852   if (IsSplat)
5853     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5854                        DAG.getConstant(1, dl, VT),
5855                        DAG.getConstant(0, dl, VT));
5856
5857   // insert elements one by one
5858   SDValue DstVec;
5859   SDValue Imm;
5860   if (Immediate) {
5861     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5862     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5863   }
5864   else if (HasConstElts)
5865     Imm = DAG.getConstant(0, dl, VT);
5866   else
5867     Imm = DAG.getUNDEF(VT);
5868   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5869     DstVec = DAG.getBitcast(VT, Imm);
5870   else {
5871     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5872     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5873                          DAG.getIntPtrConstant(0, dl));
5874   }
5875
5876   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5877     unsigned InsertIdx = NonConstIdx[i];
5878     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5879                          Op.getOperand(InsertIdx),
5880                          DAG.getIntPtrConstant(InsertIdx, dl));
5881   }
5882   return DstVec;
5883 }
5884
5885 /// \brief Return true if \p N implements a horizontal binop and return the
5886 /// operands for the horizontal binop into V0 and V1.
5887 ///
5888 /// This is a helper function of LowerToHorizontalOp().
5889 /// This function checks that the build_vector \p N in input implements a
5890 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5891 /// operation to match.
5892 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5893 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5894 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5895 /// arithmetic sub.
5896 ///
5897 /// This function only analyzes elements of \p N whose indices are
5898 /// in range [BaseIdx, LastIdx).
5899 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5900                               SelectionDAG &DAG,
5901                               unsigned BaseIdx, unsigned LastIdx,
5902                               SDValue &V0, SDValue &V1) {
5903   EVT VT = N->getValueType(0);
5904
5905   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5906   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5907          "Invalid Vector in input!");
5908
5909   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5910   bool CanFold = true;
5911   unsigned ExpectedVExtractIdx = BaseIdx;
5912   unsigned NumElts = LastIdx - BaseIdx;
5913   V0 = DAG.getUNDEF(VT);
5914   V1 = DAG.getUNDEF(VT);
5915
5916   // Check if N implements a horizontal binop.
5917   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5918     SDValue Op = N->getOperand(i + BaseIdx);
5919
5920     // Skip UNDEFs.
5921     if (Op->getOpcode() == ISD::UNDEF) {
5922       // Update the expected vector extract index.
5923       if (i * 2 == NumElts)
5924         ExpectedVExtractIdx = BaseIdx;
5925       ExpectedVExtractIdx += 2;
5926       continue;
5927     }
5928
5929     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5930
5931     if (!CanFold)
5932       break;
5933
5934     SDValue Op0 = Op.getOperand(0);
5935     SDValue Op1 = Op.getOperand(1);
5936
5937     // Try to match the following pattern:
5938     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5939     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5940         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5941         Op0.getOperand(0) == Op1.getOperand(0) &&
5942         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5943         isa<ConstantSDNode>(Op1.getOperand(1)));
5944     if (!CanFold)
5945       break;
5946
5947     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5948     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5949
5950     if (i * 2 < NumElts) {
5951       if (V0.getOpcode() == ISD::UNDEF) {
5952         V0 = Op0.getOperand(0);
5953         if (V0.getValueType() != VT)
5954           return false;
5955       }
5956     } else {
5957       if (V1.getOpcode() == ISD::UNDEF) {
5958         V1 = Op0.getOperand(0);
5959         if (V1.getValueType() != VT)
5960           return false;
5961       }
5962       if (i * 2 == NumElts)
5963         ExpectedVExtractIdx = BaseIdx;
5964     }
5965
5966     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5967     if (I0 == ExpectedVExtractIdx)
5968       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5969     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5970       // Try to match the following dag sequence:
5971       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5972       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5973     } else
5974       CanFold = false;
5975
5976     ExpectedVExtractIdx += 2;
5977   }
5978
5979   return CanFold;
5980 }
5981
5982 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5983 /// a concat_vector.
5984 ///
5985 /// This is a helper function of LowerToHorizontalOp().
5986 /// This function expects two 256-bit vectors called V0 and V1.
5987 /// At first, each vector is split into two separate 128-bit vectors.
5988 /// Then, the resulting 128-bit vectors are used to implement two
5989 /// horizontal binary operations.
5990 ///
5991 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5992 ///
5993 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5994 /// the two new horizontal binop.
5995 /// When Mode is set, the first horizontal binop dag node would take as input
5996 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5997 /// horizontal binop dag node would take as input the lower 128-bit of V1
5998 /// and the upper 128-bit of V1.
5999 ///   Example:
6000 ///     HADD V0_LO, V0_HI
6001 ///     HADD V1_LO, V1_HI
6002 ///
6003 /// Otherwise, the first horizontal binop dag node takes as input the lower
6004 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6005 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
6006 ///   Example:
6007 ///     HADD V0_LO, V1_LO
6008 ///     HADD V0_HI, V1_HI
6009 ///
6010 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6011 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6012 /// the upper 128-bits of the result.
6013 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6014                                      SDLoc DL, SelectionDAG &DAG,
6015                                      unsigned X86Opcode, bool Mode,
6016                                      bool isUndefLO, bool isUndefHI) {
6017   EVT VT = V0.getValueType();
6018   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6019          "Invalid nodes in input!");
6020
6021   unsigned NumElts = VT.getVectorNumElements();
6022   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6023   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6024   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6025   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6026   EVT NewVT = V0_LO.getValueType();
6027
6028   SDValue LO = DAG.getUNDEF(NewVT);
6029   SDValue HI = DAG.getUNDEF(NewVT);
6030
6031   if (Mode) {
6032     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6033     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6034       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6035     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6036       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6037   } else {
6038     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6039     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6040                        V1_LO->getOpcode() != ISD::UNDEF))
6041       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6042
6043     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6044                        V1_HI->getOpcode() != ISD::UNDEF))
6045       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6046   }
6047
6048   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6049 }
6050
6051 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
6052 /// node.
6053 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
6054                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6055   MVT VT = BV->getSimpleValueType(0);
6056   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
6057       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
6058     return SDValue();
6059
6060   SDLoc DL(BV);
6061   unsigned NumElts = VT.getVectorNumElements();
6062   SDValue InVec0 = DAG.getUNDEF(VT);
6063   SDValue InVec1 = DAG.getUNDEF(VT);
6064
6065   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6066           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6067
6068   // Odd-numbered elements in the input build vector are obtained from
6069   // adding two integer/float elements.
6070   // Even-numbered elements in the input build vector are obtained from
6071   // subtracting two integer/float elements.
6072   unsigned ExpectedOpcode = ISD::FSUB;
6073   unsigned NextExpectedOpcode = ISD::FADD;
6074   bool AddFound = false;
6075   bool SubFound = false;
6076
6077   for (unsigned i = 0, e = NumElts; i != e; ++i) {
6078     SDValue Op = BV->getOperand(i);
6079
6080     // Skip 'undef' values.
6081     unsigned Opcode = Op.getOpcode();
6082     if (Opcode == ISD::UNDEF) {
6083       std::swap(ExpectedOpcode, NextExpectedOpcode);
6084       continue;
6085     }
6086
6087     // Early exit if we found an unexpected opcode.
6088     if (Opcode != ExpectedOpcode)
6089       return SDValue();
6090
6091     SDValue Op0 = Op.getOperand(0);
6092     SDValue Op1 = Op.getOperand(1);
6093
6094     // Try to match the following pattern:
6095     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6096     // Early exit if we cannot match that sequence.
6097     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6098         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6099         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6100         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6101         Op0.getOperand(1) != Op1.getOperand(1))
6102       return SDValue();
6103
6104     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6105     if (I0 != i)
6106       return SDValue();
6107
6108     // We found a valid add/sub node. Update the information accordingly.
6109     if (i & 1)
6110       AddFound = true;
6111     else
6112       SubFound = true;
6113
6114     // Update InVec0 and InVec1.
6115     if (InVec0.getOpcode() == ISD::UNDEF) {
6116       InVec0 = Op0.getOperand(0);
6117       if (InVec0.getSimpleValueType() != VT)
6118         return SDValue();
6119     }
6120     if (InVec1.getOpcode() == ISD::UNDEF) {
6121       InVec1 = Op1.getOperand(0);
6122       if (InVec1.getSimpleValueType() != VT)
6123         return SDValue();
6124     }
6125
6126     // Make sure that operands in input to each add/sub node always
6127     // come from a same pair of vectors.
6128     if (InVec0 != Op0.getOperand(0)) {
6129       if (ExpectedOpcode == ISD::FSUB)
6130         return SDValue();
6131
6132       // FADD is commutable. Try to commute the operands
6133       // and then test again.
6134       std::swap(Op0, Op1);
6135       if (InVec0 != Op0.getOperand(0))
6136         return SDValue();
6137     }
6138
6139     if (InVec1 != Op1.getOperand(0))
6140       return SDValue();
6141
6142     // Update the pair of expected opcodes.
6143     std::swap(ExpectedOpcode, NextExpectedOpcode);
6144   }
6145
6146   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6147   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6148       InVec1.getOpcode() != ISD::UNDEF)
6149     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6150
6151   return SDValue();
6152 }
6153
6154 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
6155 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
6156                                    const X86Subtarget *Subtarget,
6157                                    SelectionDAG &DAG) {
6158   MVT VT = BV->getSimpleValueType(0);
6159   unsigned NumElts = VT.getVectorNumElements();
6160   unsigned NumUndefsLO = 0;
6161   unsigned NumUndefsHI = 0;
6162   unsigned Half = NumElts/2;
6163
6164   // Count the number of UNDEF operands in the build_vector in input.
6165   for (unsigned i = 0, e = Half; i != e; ++i)
6166     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6167       NumUndefsLO++;
6168
6169   for (unsigned i = Half, e = NumElts; i != e; ++i)
6170     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6171       NumUndefsHI++;
6172
6173   // Early exit if this is either a build_vector of all UNDEFs or all the
6174   // operands but one are UNDEF.
6175   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6176     return SDValue();
6177
6178   SDLoc DL(BV);
6179   SDValue InVec0, InVec1;
6180   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6181     // Try to match an SSE3 float HADD/HSUB.
6182     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6183       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6184
6185     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6186       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6187   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6188     // Try to match an SSSE3 integer HADD/HSUB.
6189     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6190       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6191
6192     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6193       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6194   }
6195
6196   if (!Subtarget->hasAVX())
6197     return SDValue();
6198
6199   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6200     // Try to match an AVX horizontal add/sub of packed single/double
6201     // precision floating point values from 256-bit vectors.
6202     SDValue InVec2, InVec3;
6203     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6204         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6205         ((InVec0.getOpcode() == ISD::UNDEF ||
6206           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6207         ((InVec1.getOpcode() == ISD::UNDEF ||
6208           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6209       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6210
6211     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6212         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6213         ((InVec0.getOpcode() == ISD::UNDEF ||
6214           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6215         ((InVec1.getOpcode() == ISD::UNDEF ||
6216           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6217       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6218   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6219     // Try to match an AVX2 horizontal add/sub of signed integers.
6220     SDValue InVec2, InVec3;
6221     unsigned X86Opcode;
6222     bool CanFold = true;
6223
6224     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6225         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6226         ((InVec0.getOpcode() == ISD::UNDEF ||
6227           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6228         ((InVec1.getOpcode() == ISD::UNDEF ||
6229           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6230       X86Opcode = X86ISD::HADD;
6231     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6232         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6233         ((InVec0.getOpcode() == ISD::UNDEF ||
6234           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6235         ((InVec1.getOpcode() == ISD::UNDEF ||
6236           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6237       X86Opcode = X86ISD::HSUB;
6238     else
6239       CanFold = false;
6240
6241     if (CanFold) {
6242       // Fold this build_vector into a single horizontal add/sub.
6243       // Do this only if the target has AVX2.
6244       if (Subtarget->hasAVX2())
6245         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6246
6247       // Do not try to expand this build_vector into a pair of horizontal
6248       // add/sub if we can emit a pair of scalar add/sub.
6249       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6250         return SDValue();
6251
6252       // Convert this build_vector into a pair of horizontal binop followed by
6253       // a concat vector.
6254       bool isUndefLO = NumUndefsLO == Half;
6255       bool isUndefHI = NumUndefsHI == Half;
6256       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6257                                    isUndefLO, isUndefHI);
6258     }
6259   }
6260
6261   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6262        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6263     unsigned X86Opcode;
6264     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6265       X86Opcode = X86ISD::HADD;
6266     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6267       X86Opcode = X86ISD::HSUB;
6268     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6269       X86Opcode = X86ISD::FHADD;
6270     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6271       X86Opcode = X86ISD::FHSUB;
6272     else
6273       return SDValue();
6274
6275     // Don't try to expand this build_vector into a pair of horizontal add/sub
6276     // if we can simply emit a pair of scalar add/sub.
6277     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6278       return SDValue();
6279
6280     // Convert this build_vector into two horizontal add/sub followed by
6281     // a concat vector.
6282     bool isUndefLO = NumUndefsLO == Half;
6283     bool isUndefHI = NumUndefsHI == Half;
6284     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6285                                  isUndefLO, isUndefHI);
6286   }
6287
6288   return SDValue();
6289 }
6290
6291 SDValue
6292 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6293   SDLoc dl(Op);
6294
6295   MVT VT = Op.getSimpleValueType();
6296   MVT ExtVT = VT.getVectorElementType();
6297   unsigned NumElems = Op.getNumOperands();
6298
6299   // Generate vectors for predicate vectors.
6300   if (VT.getVectorElementType() == MVT::i1 && Subtarget->hasAVX512())
6301     return LowerBUILD_VECTORvXi1(Op, DAG);
6302
6303   // Vectors containing all zeros can be matched by pxor and xorps later
6304   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6305     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6306     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6307     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6308       return Op;
6309
6310     return getZeroVector(VT, Subtarget, DAG, dl);
6311   }
6312
6313   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6314   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6315   // vpcmpeqd on 256-bit vectors.
6316   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6317     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6318       return Op;
6319
6320     if (!VT.is512BitVector())
6321       return getOnesVector(VT, Subtarget, DAG, dl);
6322   }
6323
6324   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6325   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6326     return AddSub;
6327   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6328     return HorizontalOp;
6329   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6330     return Broadcast;
6331
6332   unsigned EVTBits = ExtVT.getSizeInBits();
6333
6334   unsigned NumZero  = 0;
6335   unsigned NumNonZero = 0;
6336   uint64_t NonZeros = 0;
6337   bool IsAllConstants = true;
6338   SmallSet<SDValue, 8> Values;
6339   for (unsigned i = 0; i < NumElems; ++i) {
6340     SDValue Elt = Op.getOperand(i);
6341     if (Elt.getOpcode() == ISD::UNDEF)
6342       continue;
6343     Values.insert(Elt);
6344     if (Elt.getOpcode() != ISD::Constant &&
6345         Elt.getOpcode() != ISD::ConstantFP)
6346       IsAllConstants = false;
6347     if (X86::isZeroNode(Elt))
6348       NumZero++;
6349     else {
6350       assert(i < sizeof(NonZeros) * 8); // Make sure the shift is within range.
6351       NonZeros |= ((uint64_t)1 << i);
6352       NumNonZero++;
6353     }
6354   }
6355
6356   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6357   if (NumNonZero == 0)
6358     return DAG.getUNDEF(VT);
6359
6360   // Special case for single non-zero, non-undef, element.
6361   if (NumNonZero == 1) {
6362     unsigned Idx = countTrailingZeros(NonZeros);
6363     SDValue Item = Op.getOperand(Idx);
6364
6365     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6366     // the value are obviously zero, truncate the value to i32 and do the
6367     // insertion that way.  Only do this if the value is non-constant or if the
6368     // value is a constant being inserted into element 0.  It is cheaper to do
6369     // a constant pool load than it is to do a movd + shuffle.
6370     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6371         (!IsAllConstants || Idx == 0)) {
6372       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6373         // Handle SSE only.
6374         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6375         MVT VecVT = MVT::v4i32;
6376
6377         // Truncate the value (which may itself be a constant) to i32, and
6378         // convert it to a vector with movd (S2V+shuffle to zero extend).
6379         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6380         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6381         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6382                                       Item, Idx * 2, true, Subtarget, DAG));
6383       }
6384     }
6385
6386     // If we have a constant or non-constant insertion into the low element of
6387     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6388     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6389     // depending on what the source datatype is.
6390     if (Idx == 0) {
6391       if (NumZero == 0)
6392         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6393
6394       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6395           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6396         if (VT.is512BitVector()) {
6397           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6398           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6399                              Item, DAG.getIntPtrConstant(0, dl));
6400         }
6401         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6402                "Expected an SSE value type!");
6403         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6404         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6405         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6406       }
6407
6408       // We can't directly insert an i8 or i16 into a vector, so zero extend
6409       // it to i32 first.
6410       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6411         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6412         if (VT.is256BitVector()) {
6413           if (Subtarget->hasAVX()) {
6414             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6415             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6416           } else {
6417             // Without AVX, we need to extend to a 128-bit vector and then
6418             // insert into the 256-bit vector.
6419             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6420             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6421             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6422           }
6423         } else {
6424           assert(VT.is128BitVector() && "Expected an SSE value type!");
6425           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6426           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6427         }
6428         return DAG.getBitcast(VT, Item);
6429       }
6430     }
6431
6432     // Is it a vector logical left shift?
6433     if (NumElems == 2 && Idx == 1 &&
6434         X86::isZeroNode(Op.getOperand(0)) &&
6435         !X86::isZeroNode(Op.getOperand(1))) {
6436       unsigned NumBits = VT.getSizeInBits();
6437       return getVShift(true, VT,
6438                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6439                                    VT, Op.getOperand(1)),
6440                        NumBits/2, DAG, *this, dl);
6441     }
6442
6443     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6444       return SDValue();
6445
6446     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6447     // is a non-constant being inserted into an element other than the low one,
6448     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6449     // movd/movss) to move this into the low element, then shuffle it into
6450     // place.
6451     if (EVTBits == 32) {
6452       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6453       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6454     }
6455   }
6456
6457   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6458   if (Values.size() == 1) {
6459     if (EVTBits == 32) {
6460       // Instead of a shuffle like this:
6461       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6462       // Check if it's possible to issue this instead.
6463       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6464       unsigned Idx = countTrailingZeros(NonZeros);
6465       SDValue Item = Op.getOperand(Idx);
6466       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6467         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6468     }
6469     return SDValue();
6470   }
6471
6472   // A vector full of immediates; various special cases are already
6473   // handled, so this is best done with a single constant-pool load.
6474   if (IsAllConstants)
6475     return SDValue();
6476
6477   // For AVX-length vectors, see if we can use a vector load to get all of the
6478   // elements, otherwise build the individual 128-bit pieces and use
6479   // shuffles to put them in place.
6480   if (VT.is256BitVector() || VT.is512BitVector()) {
6481     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6482
6483     // Check for a build vector of consecutive loads.
6484     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6485       return LD;
6486
6487     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6488
6489     // Build both the lower and upper subvector.
6490     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6491                                 makeArrayRef(&V[0], NumElems/2));
6492     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6493                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6494
6495     // Recreate the wider vector with the lower and upper part.
6496     if (VT.is256BitVector())
6497       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6498     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6499   }
6500
6501   // Let legalizer expand 2-wide build_vectors.
6502   if (EVTBits == 64) {
6503     if (NumNonZero == 1) {
6504       // One half is zero or undef.
6505       unsigned Idx = countTrailingZeros(NonZeros);
6506       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6507                                Op.getOperand(Idx));
6508       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6509     }
6510     return SDValue();
6511   }
6512
6513   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6514   if (EVTBits == 8 && NumElems == 16)
6515     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros, NumNonZero, NumZero,
6516                                           DAG, Subtarget, *this))
6517       return V;
6518
6519   if (EVTBits == 16 && NumElems == 8)
6520     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros, NumNonZero, NumZero,
6521                                           DAG, Subtarget, *this))
6522       return V;
6523
6524   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6525   if (EVTBits == 32 && NumElems == 4)
6526     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6527       return V;
6528
6529   // If element VT is == 32 bits, turn it into a number of shuffles.
6530   SmallVector<SDValue, 8> V(NumElems);
6531   if (NumElems == 4 && NumZero > 0) {
6532     for (unsigned i = 0; i < 4; ++i) {
6533       bool isZero = !(NonZeros & (1ULL << i));
6534       if (isZero)
6535         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6536       else
6537         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6538     }
6539
6540     for (unsigned i = 0; i < 2; ++i) {
6541       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6542         default: break;
6543         case 0:
6544           V[i] = V[i*2];  // Must be a zero vector.
6545           break;
6546         case 1:
6547           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6548           break;
6549         case 2:
6550           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6551           break;
6552         case 3:
6553           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6554           break;
6555       }
6556     }
6557
6558     bool Reverse1 = (NonZeros & 0x3) == 2;
6559     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6560     int MaskVec[] = {
6561       Reverse1 ? 1 : 0,
6562       Reverse1 ? 0 : 1,
6563       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6564       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6565     };
6566     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6567   }
6568
6569   if (Values.size() > 1 && VT.is128BitVector()) {
6570     // Check for a build vector of consecutive loads.
6571     for (unsigned i = 0; i < NumElems; ++i)
6572       V[i] = Op.getOperand(i);
6573
6574     // Check for elements which are consecutive loads.
6575     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6576       return LD;
6577
6578     // Check for a build vector from mostly shuffle plus few inserting.
6579     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6580       return Sh;
6581
6582     // For SSE 4.1, use insertps to put the high elements into the low element.
6583     if (Subtarget->hasSSE41()) {
6584       SDValue Result;
6585       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6586         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6587       else
6588         Result = DAG.getUNDEF(VT);
6589
6590       for (unsigned i = 1; i < NumElems; ++i) {
6591         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6592         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6593                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6594       }
6595       return Result;
6596     }
6597
6598     // Otherwise, expand into a number of unpckl*, start by extending each of
6599     // our (non-undef) elements to the full vector width with the element in the
6600     // bottom slot of the vector (which generates no code for SSE).
6601     for (unsigned i = 0; i < NumElems; ++i) {
6602       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6603         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6604       else
6605         V[i] = DAG.getUNDEF(VT);
6606     }
6607
6608     // Next, we iteratively mix elements, e.g. for v4f32:
6609     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6610     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6611     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6612     unsigned EltStride = NumElems >> 1;
6613     while (EltStride != 0) {
6614       for (unsigned i = 0; i < EltStride; ++i) {
6615         // If V[i+EltStride] is undef and this is the first round of mixing,
6616         // then it is safe to just drop this shuffle: V[i] is already in the
6617         // right place, the one element (since it's the first round) being
6618         // inserted as undef can be dropped.  This isn't safe for successive
6619         // rounds because they will permute elements within both vectors.
6620         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6621             EltStride == NumElems/2)
6622           continue;
6623
6624         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6625       }
6626       EltStride >>= 1;
6627     }
6628     return V[0];
6629   }
6630   return SDValue();
6631 }
6632
6633 // 256-bit AVX can use the vinsertf128 instruction
6634 // to create 256-bit vectors from two other 128-bit ones.
6635 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6636   SDLoc dl(Op);
6637   MVT ResVT = Op.getSimpleValueType();
6638
6639   assert((ResVT.is256BitVector() ||
6640           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6641
6642   SDValue V1 = Op.getOperand(0);
6643   SDValue V2 = Op.getOperand(1);
6644   unsigned NumElems = ResVT.getVectorNumElements();
6645   if (ResVT.is256BitVector())
6646     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6647
6648   if (Op.getNumOperands() == 4) {
6649     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6650                                   ResVT.getVectorNumElements()/2);
6651     SDValue V3 = Op.getOperand(2);
6652     SDValue V4 = Op.getOperand(3);
6653     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6654       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6655   }
6656   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6657 }
6658
6659 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6660                                        const X86Subtarget *Subtarget,
6661                                        SelectionDAG & DAG) {
6662   SDLoc dl(Op);
6663   MVT ResVT = Op.getSimpleValueType();
6664   unsigned NumOfOperands = Op.getNumOperands();
6665
6666   assert(isPowerOf2_32(NumOfOperands) &&
6667          "Unexpected number of operands in CONCAT_VECTORS");
6668
6669   SDValue Undef = DAG.getUNDEF(ResVT);
6670   if (NumOfOperands > 2) {
6671     // Specialize the cases when all, or all but one, of the operands are undef.
6672     unsigned NumOfDefinedOps = 0;
6673     unsigned OpIdx = 0;
6674     for (unsigned i = 0; i < NumOfOperands; i++)
6675       if (!Op.getOperand(i).isUndef()) {
6676         NumOfDefinedOps++;
6677         OpIdx = i;
6678       }
6679     if (NumOfDefinedOps == 0)
6680       return Undef;
6681     if (NumOfDefinedOps == 1) {
6682       unsigned SubVecNumElts =
6683         Op.getOperand(OpIdx).getValueType().getVectorNumElements();
6684       SDValue IdxVal = DAG.getIntPtrConstant(SubVecNumElts * OpIdx, dl);
6685       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef,
6686                          Op.getOperand(OpIdx), IdxVal);
6687     }
6688
6689     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6690                                   ResVT.getVectorNumElements()/2);
6691     SmallVector<SDValue, 2> Ops;
6692     for (unsigned i = 0; i < NumOfOperands/2; i++)
6693       Ops.push_back(Op.getOperand(i));
6694     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6695     Ops.clear();
6696     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6697       Ops.push_back(Op.getOperand(i));
6698     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6699     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6700   }
6701
6702   // 2 operands
6703   SDValue V1 = Op.getOperand(0);
6704   SDValue V2 = Op.getOperand(1);
6705   unsigned NumElems = ResVT.getVectorNumElements();
6706   assert(V1.getValueType() == V2.getValueType() &&
6707          V1.getValueType().getVectorNumElements() == NumElems/2 &&
6708          "Unexpected operands in CONCAT_VECTORS");
6709
6710   if (ResVT.getSizeInBits() >= 16)
6711     return Op; // The operation is legal with KUNPCK
6712
6713   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6714   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6715   SDValue ZeroVec = getZeroVector(ResVT, Subtarget, DAG, dl);
6716   if (IsZeroV1 && IsZeroV2)
6717     return ZeroVec;
6718
6719   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6720   if (V2.isUndef())
6721     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6722   if (IsZeroV2)
6723     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V1, ZeroIdx);
6724
6725   SDValue IdxVal = DAG.getIntPtrConstant(NumElems/2, dl);
6726   if (V1.isUndef())
6727     V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, IdxVal);
6728
6729   if (IsZeroV1)
6730     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V2, IdxVal);
6731
6732   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6733   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, V1, V2, IdxVal);
6734 }
6735
6736 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6737                                    const X86Subtarget *Subtarget,
6738                                    SelectionDAG &DAG) {
6739   MVT VT = Op.getSimpleValueType();
6740   if (VT.getVectorElementType() == MVT::i1)
6741     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6742
6743   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6744          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6745           Op.getNumOperands() == 4)));
6746
6747   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6748   // from two other 128-bit ones.
6749
6750   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6751   return LowerAVXCONCAT_VECTORS(Op, DAG);
6752 }
6753
6754 //===----------------------------------------------------------------------===//
6755 // Vector shuffle lowering
6756 //
6757 // This is an experimental code path for lowering vector shuffles on x86. It is
6758 // designed to handle arbitrary vector shuffles and blends, gracefully
6759 // degrading performance as necessary. It works hard to recognize idiomatic
6760 // shuffles and lower them to optimal instruction patterns without leaving
6761 // a framework that allows reasonably efficient handling of all vector shuffle
6762 // patterns.
6763 //===----------------------------------------------------------------------===//
6764
6765 /// \brief Tiny helper function to identify a no-op mask.
6766 ///
6767 /// This is a somewhat boring predicate function. It checks whether the mask
6768 /// array input, which is assumed to be a single-input shuffle mask of the kind
6769 /// used by the X86 shuffle instructions (not a fully general
6770 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6771 /// in-place shuffle are 'no-op's.
6772 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6773   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6774     if (Mask[i] != -1 && Mask[i] != i)
6775       return false;
6776   return true;
6777 }
6778
6779 /// \brief Helper function to classify a mask as a single-input mask.
6780 ///
6781 /// This isn't a generic single-input test because in the vector shuffle
6782 /// lowering we canonicalize single inputs to be the first input operand. This
6783 /// means we can more quickly test for a single input by only checking whether
6784 /// an input from the second operand exists. We also assume that the size of
6785 /// mask corresponds to the size of the input vectors which isn't true in the
6786 /// fully general case.
6787 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6788   for (int M : Mask)
6789     if (M >= (int)Mask.size())
6790       return false;
6791   return true;
6792 }
6793
6794 /// \brief Test whether there are elements crossing 128-bit lanes in this
6795 /// shuffle mask.
6796 ///
6797 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6798 /// and we routinely test for these.
6799 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6800   int LaneSize = 128 / VT.getScalarSizeInBits();
6801   int Size = Mask.size();
6802   for (int i = 0; i < Size; ++i)
6803     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6804       return true;
6805   return false;
6806 }
6807
6808 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6809 ///
6810 /// This checks a shuffle mask to see if it is performing the same
6811 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6812 /// that it is also not lane-crossing. It may however involve a blend from the
6813 /// same lane of a second vector.
6814 ///
6815 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6816 /// non-trivial to compute in the face of undef lanes. The representation is
6817 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6818 /// entries from both V1 and V2 inputs to the wider mask.
6819 static bool
6820 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6821                                 SmallVectorImpl<int> &RepeatedMask) {
6822   int LaneSize = 128 / VT.getScalarSizeInBits();
6823   RepeatedMask.resize(LaneSize, -1);
6824   int Size = Mask.size();
6825   for (int i = 0; i < Size; ++i) {
6826     if (Mask[i] < 0)
6827       continue;
6828     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6829       // This entry crosses lanes, so there is no way to model this shuffle.
6830       return false;
6831
6832     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6833     if (RepeatedMask[i % LaneSize] == -1)
6834       // This is the first non-undef entry in this slot of a 128-bit lane.
6835       RepeatedMask[i % LaneSize] =
6836           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6837     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6838       // Found a mismatch with the repeated mask.
6839       return false;
6840   }
6841   return true;
6842 }
6843
6844 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6845 /// arguments.
6846 ///
6847 /// This is a fast way to test a shuffle mask against a fixed pattern:
6848 ///
6849 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6850 ///
6851 /// It returns true if the mask is exactly as wide as the argument list, and
6852 /// each element of the mask is either -1 (signifying undef) or the value given
6853 /// in the argument.
6854 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6855                                 ArrayRef<int> ExpectedMask) {
6856   if (Mask.size() != ExpectedMask.size())
6857     return false;
6858
6859   int Size = Mask.size();
6860
6861   // If the values are build vectors, we can look through them to find
6862   // equivalent inputs that make the shuffles equivalent.
6863   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6864   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6865
6866   for (int i = 0; i < Size; ++i)
6867     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6868       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6869       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6870       if (!MaskBV || !ExpectedBV ||
6871           MaskBV->getOperand(Mask[i] % Size) !=
6872               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6873         return false;
6874     }
6875
6876   return true;
6877 }
6878
6879 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6880 ///
6881 /// This helper function produces an 8-bit shuffle immediate corresponding to
6882 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6883 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6884 /// example.
6885 ///
6886 /// NB: We rely heavily on "undef" masks preserving the input lane.
6887 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6888                                           SelectionDAG &DAG) {
6889   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6890   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6891   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6892   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6893   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6894
6895   unsigned Imm = 0;
6896   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6897   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6898   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6899   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6900   return DAG.getConstant(Imm, DL, MVT::i8);
6901 }
6902
6903 /// \brief Compute whether each element of a shuffle is zeroable.
6904 ///
6905 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6906 /// Either it is an undef element in the shuffle mask, the element of the input
6907 /// referenced is undef, or the element of the input referenced is known to be
6908 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6909 /// as many lanes with this technique as possible to simplify the remaining
6910 /// shuffle.
6911 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6912                                                      SDValue V1, SDValue V2) {
6913   SmallBitVector Zeroable(Mask.size(), false);
6914
6915   while (V1.getOpcode() == ISD::BITCAST)
6916     V1 = V1->getOperand(0);
6917   while (V2.getOpcode() == ISD::BITCAST)
6918     V2 = V2->getOperand(0);
6919
6920   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6921   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6922
6923   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6924     int M = Mask[i];
6925     // Handle the easy cases.
6926     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6927       Zeroable[i] = true;
6928       continue;
6929     }
6930
6931     // If this is an index into a build_vector node (which has the same number
6932     // of elements), dig out the input value and use it.
6933     SDValue V = M < Size ? V1 : V2;
6934     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6935       continue;
6936
6937     SDValue Input = V.getOperand(M % Size);
6938     // The UNDEF opcode check really should be dead code here, but not quite
6939     // worth asserting on (it isn't invalid, just unexpected).
6940     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6941       Zeroable[i] = true;
6942   }
6943
6944   return Zeroable;
6945 }
6946
6947 // X86 has dedicated unpack instructions that can handle specific blend
6948 // operations: UNPCKH and UNPCKL.
6949 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6950                                            SDValue V1, SDValue V2,
6951                                            SelectionDAG &DAG) {
6952   int NumElts = VT.getVectorNumElements();
6953   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6954   SmallVector<int, 8> Unpckl;
6955   SmallVector<int, 8> Unpckh;
6956
6957   for (int i = 0; i < NumElts; ++i) {
6958     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6959     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6960     int HiPos = LoPos + NumEltsInLane / 2;
6961     Unpckl.push_back(LoPos);
6962     Unpckh.push_back(HiPos);
6963   }
6964
6965   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6966     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6967   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6968     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6969
6970   // Commute and try again.
6971   ShuffleVectorSDNode::commuteMask(Unpckl);
6972   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6973     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6974
6975   ShuffleVectorSDNode::commuteMask(Unpckh);
6976   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6977     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6978
6979   return SDValue();
6980 }
6981
6982 /// \brief Try to emit a bitmask instruction for a shuffle.
6983 ///
6984 /// This handles cases where we can model a blend exactly as a bitmask due to
6985 /// one of the inputs being zeroable.
6986 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6987                                            SDValue V2, ArrayRef<int> Mask,
6988                                            SelectionDAG &DAG) {
6989   MVT EltVT = VT.getVectorElementType();
6990   int NumEltBits = EltVT.getSizeInBits();
6991   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6992   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6993   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6994                                     IntEltVT);
6995   if (EltVT.isFloatingPoint()) {
6996     Zero = DAG.getBitcast(EltVT, Zero);
6997     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6998   }
6999   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
7000   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7001   SDValue V;
7002   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7003     if (Zeroable[i])
7004       continue;
7005     if (Mask[i] % Size != i)
7006       return SDValue(); // Not a blend.
7007     if (!V)
7008       V = Mask[i] < Size ? V1 : V2;
7009     else if (V != (Mask[i] < Size ? V1 : V2))
7010       return SDValue(); // Can only let one input through the mask.
7011
7012     VMaskOps[i] = AllOnes;
7013   }
7014   if (!V)
7015     return SDValue(); // No non-zeroable elements!
7016
7017   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
7018   V = DAG.getNode(VT.isFloatingPoint()
7019                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
7020                   DL, VT, V, VMask);
7021   return V;
7022 }
7023
7024 /// \brief Try to emit a blend instruction for a shuffle using bit math.
7025 ///
7026 /// This is used as a fallback approach when first class blend instructions are
7027 /// unavailable. Currently it is only suitable for integer vectors, but could
7028 /// be generalized for floating point vectors if desirable.
7029 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
7030                                             SDValue V2, ArrayRef<int> Mask,
7031                                             SelectionDAG &DAG) {
7032   assert(VT.isInteger() && "Only supports integer vector types!");
7033   MVT EltVT = VT.getVectorElementType();
7034   int NumEltBits = EltVT.getSizeInBits();
7035   SDValue Zero = DAG.getConstant(0, DL, EltVT);
7036   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
7037                                     EltVT);
7038   SmallVector<SDValue, 16> MaskOps;
7039   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7040     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
7041       return SDValue(); // Shuffled input!
7042     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
7043   }
7044
7045   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
7046   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
7047   // We have to cast V2 around.
7048   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
7049   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
7050                                       DAG.getBitcast(MaskVT, V1Mask),
7051                                       DAG.getBitcast(MaskVT, V2)));
7052   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
7053 }
7054
7055 /// \brief Try to emit a blend instruction for a shuffle.
7056 ///
7057 /// This doesn't do any checks for the availability of instructions for blending
7058 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7059 /// be matched in the backend with the type given. What it does check for is
7060 /// that the shuffle mask is a blend, or convertible into a blend with zero.
7061 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7062                                          SDValue V2, ArrayRef<int> Original,
7063                                          const X86Subtarget *Subtarget,
7064                                          SelectionDAG &DAG) {
7065   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7066   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7067   SmallVector<int, 8> Mask(Original.begin(), Original.end());
7068   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7069   bool ForceV1Zero = false, ForceV2Zero = false;
7070
7071   // Attempt to generate the binary blend mask. If an input is zero then
7072   // we can use any lane.
7073   // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
7074   unsigned BlendMask = 0;
7075   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7076     int M = Mask[i];
7077     if (M < 0)
7078       continue;
7079     if (M == i)
7080       continue;
7081     if (M == i + Size) {
7082       BlendMask |= 1u << i;
7083       continue;
7084     }
7085     if (Zeroable[i]) {
7086       if (V1IsZero) {
7087         ForceV1Zero = true;
7088         Mask[i] = i;
7089         continue;
7090       }
7091       if (V2IsZero) {
7092         ForceV2Zero = true;
7093         BlendMask |= 1u << i;
7094         Mask[i] = i + Size;
7095         continue;
7096       }
7097     }
7098     return SDValue(); // Shuffled input!
7099   }
7100
7101   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
7102   if (ForceV1Zero)
7103     V1 = getZeroVector(VT, Subtarget, DAG, DL);
7104   if (ForceV2Zero)
7105     V2 = getZeroVector(VT, Subtarget, DAG, DL);
7106
7107   auto ScaleBlendMask = [](unsigned BlendMask, int Size, int Scale) {
7108     unsigned ScaledMask = 0;
7109     for (int i = 0; i != Size; ++i)
7110       if (BlendMask & (1u << i))
7111         for (int j = 0; j != Scale; ++j)
7112           ScaledMask |= 1u << (i * Scale + j);
7113     return ScaledMask;
7114   };
7115
7116   switch (VT.SimpleTy) {
7117   case MVT::v2f64:
7118   case MVT::v4f32:
7119   case MVT::v4f64:
7120   case MVT::v8f32:
7121     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7122                        DAG.getConstant(BlendMask, DL, MVT::i8));
7123
7124   case MVT::v4i64:
7125   case MVT::v8i32:
7126     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7127     // FALLTHROUGH
7128   case MVT::v2i64:
7129   case MVT::v4i32:
7130     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7131     // that instruction.
7132     if (Subtarget->hasAVX2()) {
7133       // Scale the blend by the number of 32-bit dwords per element.
7134       int Scale =  VT.getScalarSizeInBits() / 32;
7135       BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7136       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7137       V1 = DAG.getBitcast(BlendVT, V1);
7138       V2 = DAG.getBitcast(BlendVT, V2);
7139       return DAG.getBitcast(
7140           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7141                           DAG.getConstant(BlendMask, DL, MVT::i8)));
7142     }
7143     // FALLTHROUGH
7144   case MVT::v8i16: {
7145     // For integer shuffles we need to expand the mask and cast the inputs to
7146     // v8i16s prior to blending.
7147     int Scale = 8 / VT.getVectorNumElements();
7148     BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7149     V1 = DAG.getBitcast(MVT::v8i16, V1);
7150     V2 = DAG.getBitcast(MVT::v8i16, V2);
7151     return DAG.getBitcast(VT,
7152                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7153                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
7154   }
7155
7156   case MVT::v16i16: {
7157     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7158     SmallVector<int, 8> RepeatedMask;
7159     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7160       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7161       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7162       BlendMask = 0;
7163       for (int i = 0; i < 8; ++i)
7164         if (RepeatedMask[i] >= 16)
7165           BlendMask |= 1u << i;
7166       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7167                          DAG.getConstant(BlendMask, DL, MVT::i8));
7168     }
7169   }
7170     // FALLTHROUGH
7171   case MVT::v16i8:
7172   case MVT::v32i8: {
7173     assert((VT.is128BitVector() || Subtarget->hasAVX2()) &&
7174            "256-bit byte-blends require AVX2 support!");
7175
7176     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
7177     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
7178       return Masked;
7179
7180     // Scale the blend by the number of bytes per element.
7181     int Scale = VT.getScalarSizeInBits() / 8;
7182
7183     // This form of blend is always done on bytes. Compute the byte vector
7184     // type.
7185     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
7186
7187     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7188     // mix of LLVM's code generator and the x86 backend. We tell the code
7189     // generator that boolean values in the elements of an x86 vector register
7190     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7191     // mapping a select to operand #1, and 'false' mapping to operand #2. The
7192     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7193     // of the element (the remaining are ignored) and 0 in that high bit would
7194     // mean operand #1 while 1 in the high bit would mean operand #2. So while
7195     // the LLVM model for boolean values in vector elements gets the relevant
7196     // bit set, it is set backwards and over constrained relative to x86's
7197     // actual model.
7198     SmallVector<SDValue, 32> VSELECTMask;
7199     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7200       for (int j = 0; j < Scale; ++j)
7201         VSELECTMask.push_back(
7202             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7203                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7204                                           MVT::i8));
7205
7206     V1 = DAG.getBitcast(BlendVT, V1);
7207     V2 = DAG.getBitcast(BlendVT, V2);
7208     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7209                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
7210                                                       BlendVT, VSELECTMask),
7211                                           V1, V2));
7212   }
7213
7214   default:
7215     llvm_unreachable("Not a supported integer vector type!");
7216   }
7217 }
7218
7219 /// \brief Try to lower as a blend of elements from two inputs followed by
7220 /// a single-input permutation.
7221 ///
7222 /// This matches the pattern where we can blend elements from two inputs and
7223 /// then reduce the shuffle to a single-input permutation.
7224 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7225                                                    SDValue V2,
7226                                                    ArrayRef<int> Mask,
7227                                                    SelectionDAG &DAG) {
7228   // We build up the blend mask while checking whether a blend is a viable way
7229   // to reduce the shuffle.
7230   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7231   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7232
7233   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7234     if (Mask[i] < 0)
7235       continue;
7236
7237     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7238
7239     if (BlendMask[Mask[i] % Size] == -1)
7240       BlendMask[Mask[i] % Size] = Mask[i];
7241     else if (BlendMask[Mask[i] % Size] != Mask[i])
7242       return SDValue(); // Can't blend in the needed input!
7243
7244     PermuteMask[i] = Mask[i] % Size;
7245   }
7246
7247   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7248   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7249 }
7250
7251 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7252 /// blends and permutes.
7253 ///
7254 /// This matches the extremely common pattern for handling combined
7255 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7256 /// operations. It will try to pick the best arrangement of shuffles and
7257 /// blends.
7258 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7259                                                           SDValue V1,
7260                                                           SDValue V2,
7261                                                           ArrayRef<int> Mask,
7262                                                           SelectionDAG &DAG) {
7263   // Shuffle the input elements into the desired positions in V1 and V2 and
7264   // blend them together.
7265   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7266   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7267   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7268   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7269     if (Mask[i] >= 0 && Mask[i] < Size) {
7270       V1Mask[i] = Mask[i];
7271       BlendMask[i] = i;
7272     } else if (Mask[i] >= Size) {
7273       V2Mask[i] = Mask[i] - Size;
7274       BlendMask[i] = i + Size;
7275     }
7276
7277   // Try to lower with the simpler initial blend strategy unless one of the
7278   // input shuffles would be a no-op. We prefer to shuffle inputs as the
7279   // shuffle may be able to fold with a load or other benefit. However, when
7280   // we'll have to do 2x as many shuffles in order to achieve this, blending
7281   // first is a better strategy.
7282   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7283     if (SDValue BlendPerm =
7284             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7285       return BlendPerm;
7286
7287   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7288   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7289   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7290 }
7291
7292 /// \brief Try to lower a vector shuffle as a byte rotation.
7293 ///
7294 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7295 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7296 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7297 /// try to generically lower a vector shuffle through such an pattern. It
7298 /// does not check for the profitability of lowering either as PALIGNR or
7299 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7300 /// This matches shuffle vectors that look like:
7301 ///
7302 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7303 ///
7304 /// Essentially it concatenates V1 and V2, shifts right by some number of
7305 /// elements, and takes the low elements as the result. Note that while this is
7306 /// specified as a *right shift* because x86 is little-endian, it is a *left
7307 /// rotate* of the vector lanes.
7308 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7309                                               SDValue V2,
7310                                               ArrayRef<int> Mask,
7311                                               const X86Subtarget *Subtarget,
7312                                               SelectionDAG &DAG) {
7313   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7314
7315   int NumElts = Mask.size();
7316   int NumLanes = VT.getSizeInBits() / 128;
7317   int NumLaneElts = NumElts / NumLanes;
7318
7319   // We need to detect various ways of spelling a rotation:
7320   //   [11, 12, 13, 14, 15,  0,  1,  2]
7321   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7322   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7323   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7324   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7325   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7326   int Rotation = 0;
7327   SDValue Lo, Hi;
7328   for (int l = 0; l < NumElts; l += NumLaneElts) {
7329     for (int i = 0; i < NumLaneElts; ++i) {
7330       if (Mask[l + i] == -1)
7331         continue;
7332       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7333
7334       // Get the mod-Size index and lane correct it.
7335       int LaneIdx = (Mask[l + i] % NumElts) - l;
7336       // Make sure it was in this lane.
7337       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7338         return SDValue();
7339
7340       // Determine where a rotated vector would have started.
7341       int StartIdx = i - LaneIdx;
7342       if (StartIdx == 0)
7343         // The identity rotation isn't interesting, stop.
7344         return SDValue();
7345
7346       // If we found the tail of a vector the rotation must be the missing
7347       // front. If we found the head of a vector, it must be how much of the
7348       // head.
7349       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7350
7351       if (Rotation == 0)
7352         Rotation = CandidateRotation;
7353       else if (Rotation != CandidateRotation)
7354         // The rotations don't match, so we can't match this mask.
7355         return SDValue();
7356
7357       // Compute which value this mask is pointing at.
7358       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7359
7360       // Compute which of the two target values this index should be assigned
7361       // to. This reflects whether the high elements are remaining or the low
7362       // elements are remaining.
7363       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7364
7365       // Either set up this value if we've not encountered it before, or check
7366       // that it remains consistent.
7367       if (!TargetV)
7368         TargetV = MaskV;
7369       else if (TargetV != MaskV)
7370         // This may be a rotation, but it pulls from the inputs in some
7371         // unsupported interleaving.
7372         return SDValue();
7373     }
7374   }
7375
7376   // Check that we successfully analyzed the mask, and normalize the results.
7377   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7378   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7379   if (!Lo)
7380     Lo = Hi;
7381   else if (!Hi)
7382     Hi = Lo;
7383
7384   // The actual rotate instruction rotates bytes, so we need to scale the
7385   // rotation based on how many bytes are in the vector lane.
7386   int Scale = 16 / NumLaneElts;
7387
7388   // SSSE3 targets can use the palignr instruction.
7389   if (Subtarget->hasSSSE3()) {
7390     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7391     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7392     Lo = DAG.getBitcast(AlignVT, Lo);
7393     Hi = DAG.getBitcast(AlignVT, Hi);
7394
7395     return DAG.getBitcast(
7396         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7397                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7398   }
7399
7400   assert(VT.is128BitVector() &&
7401          "Rotate-based lowering only supports 128-bit lowering!");
7402   assert(Mask.size() <= 16 &&
7403          "Can shuffle at most 16 bytes in a 128-bit vector!");
7404
7405   // Default SSE2 implementation
7406   int LoByteShift = 16 - Rotation * Scale;
7407   int HiByteShift = Rotation * Scale;
7408
7409   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7410   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7411   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7412
7413   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7414                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7415   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7416                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7417   return DAG.getBitcast(VT,
7418                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7419 }
7420
7421 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7422 ///
7423 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7424 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7425 /// matches elements from one of the input vectors shuffled to the left or
7426 /// right with zeroable elements 'shifted in'. It handles both the strictly
7427 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7428 /// quad word lane.
7429 ///
7430 /// PSHL : (little-endian) left bit shift.
7431 /// [ zz, 0, zz,  2 ]
7432 /// [ -1, 4, zz, -1 ]
7433 /// PSRL : (little-endian) right bit shift.
7434 /// [  1, zz,  3, zz]
7435 /// [ -1, -1,  7, zz]
7436 /// PSLLDQ : (little-endian) left byte shift
7437 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7438 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7439 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7440 /// PSRLDQ : (little-endian) right byte shift
7441 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7442 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7443 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7444 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7445                                          SDValue V2, ArrayRef<int> Mask,
7446                                          SelectionDAG &DAG) {
7447   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7448
7449   int Size = Mask.size();
7450   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7451
7452   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7453     for (int i = 0; i < Size; i += Scale)
7454       for (int j = 0; j < Shift; ++j)
7455         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7456           return false;
7457
7458     return true;
7459   };
7460
7461   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7462     for (int i = 0; i != Size; i += Scale) {
7463       unsigned Pos = Left ? i + Shift : i;
7464       unsigned Low = Left ? i : i + Shift;
7465       unsigned Len = Scale - Shift;
7466       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7467                                       Low + (V == V1 ? 0 : Size)))
7468         return SDValue();
7469     }
7470
7471     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7472     bool ByteShift = ShiftEltBits > 64;
7473     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7474                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7475     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7476
7477     // Normalize the scale for byte shifts to still produce an i64 element
7478     // type.
7479     Scale = ByteShift ? Scale / 2 : Scale;
7480
7481     // We need to round trip through the appropriate type for the shift.
7482     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7483     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7484     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7485            "Illegal integer vector type");
7486     V = DAG.getBitcast(ShiftVT, V);
7487
7488     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7489                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7490     return DAG.getBitcast(VT, V);
7491   };
7492
7493   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7494   // keep doubling the size of the integer elements up to that. We can
7495   // then shift the elements of the integer vector by whole multiples of
7496   // their width within the elements of the larger integer vector. Test each
7497   // multiple to see if we can find a match with the moved element indices
7498   // and that the shifted in elements are all zeroable.
7499   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7500     for (int Shift = 1; Shift != Scale; ++Shift)
7501       for (bool Left : {true, false})
7502         if (CheckZeros(Shift, Scale, Left))
7503           for (SDValue V : {V1, V2})
7504             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7505               return Match;
7506
7507   // no match
7508   return SDValue();
7509 }
7510
7511 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7512 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7513                                            SDValue V2, ArrayRef<int> Mask,
7514                                            SelectionDAG &DAG) {
7515   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7516   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7517
7518   int Size = Mask.size();
7519   int HalfSize = Size / 2;
7520   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7521
7522   // Upper half must be undefined.
7523   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7524     return SDValue();
7525
7526   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7527   // Remainder of lower half result is zero and upper half is all undef.
7528   auto LowerAsEXTRQ = [&]() {
7529     // Determine the extraction length from the part of the
7530     // lower half that isn't zeroable.
7531     int Len = HalfSize;
7532     for (; Len > 0; --Len)
7533       if (!Zeroable[Len - 1])
7534         break;
7535     assert(Len > 0 && "Zeroable shuffle mask");
7536
7537     // Attempt to match first Len sequential elements from the lower half.
7538     SDValue Src;
7539     int Idx = -1;
7540     for (int i = 0; i != Len; ++i) {
7541       int M = Mask[i];
7542       if (M < 0)
7543         continue;
7544       SDValue &V = (M < Size ? V1 : V2);
7545       M = M % Size;
7546
7547       // The extracted elements must start at a valid index and all mask
7548       // elements must be in the lower half.
7549       if (i > M || M >= HalfSize)
7550         return SDValue();
7551
7552       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7553         Src = V;
7554         Idx = M - i;
7555         continue;
7556       }
7557       return SDValue();
7558     }
7559
7560     if (Idx < 0)
7561       return SDValue();
7562
7563     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7564     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7565     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7566     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7567                        DAG.getConstant(BitLen, DL, MVT::i8),
7568                        DAG.getConstant(BitIdx, DL, MVT::i8));
7569   };
7570
7571   if (SDValue ExtrQ = LowerAsEXTRQ())
7572     return ExtrQ;
7573
7574   // INSERTQ: Extract lowest Len elements from lower half of second source and
7575   // insert over first source, starting at Idx.
7576   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7577   auto LowerAsInsertQ = [&]() {
7578     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7579       SDValue Base;
7580
7581       // Attempt to match first source from mask before insertion point.
7582       if (isUndefInRange(Mask, 0, Idx)) {
7583         /* EMPTY */
7584       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7585         Base = V1;
7586       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7587         Base = V2;
7588       } else {
7589         continue;
7590       }
7591
7592       // Extend the extraction length looking to match both the insertion of
7593       // the second source and the remaining elements of the first.
7594       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7595         SDValue Insert;
7596         int Len = Hi - Idx;
7597
7598         // Match insertion.
7599         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7600           Insert = V1;
7601         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7602           Insert = V2;
7603         } else {
7604           continue;
7605         }
7606
7607         // Match the remaining elements of the lower half.
7608         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7609           /* EMPTY */
7610         } else if ((!Base || (Base == V1)) &&
7611                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7612           Base = V1;
7613         } else if ((!Base || (Base == V2)) &&
7614                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7615                                               Size + Hi)) {
7616           Base = V2;
7617         } else {
7618           continue;
7619         }
7620
7621         // We may not have a base (first source) - this can safely be undefined.
7622         if (!Base)
7623           Base = DAG.getUNDEF(VT);
7624
7625         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7626         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7627         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7628                            DAG.getConstant(BitLen, DL, MVT::i8),
7629                            DAG.getConstant(BitIdx, DL, MVT::i8));
7630       }
7631     }
7632
7633     return SDValue();
7634   };
7635
7636   if (SDValue InsertQ = LowerAsInsertQ())
7637     return InsertQ;
7638
7639   return SDValue();
7640 }
7641
7642 /// \brief Lower a vector shuffle as a zero or any extension.
7643 ///
7644 /// Given a specific number of elements, element bit width, and extension
7645 /// stride, produce either a zero or any extension based on the available
7646 /// features of the subtarget. The extended elements are consecutive and
7647 /// begin and can start from an offseted element index in the input; to
7648 /// avoid excess shuffling the offset must either being in the bottom lane
7649 /// or at the start of a higher lane. All extended elements must be from
7650 /// the same lane.
7651 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7652     SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7653     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7654   assert(Scale > 1 && "Need a scale to extend.");
7655   int EltBits = VT.getScalarSizeInBits();
7656   int NumElements = VT.getVectorNumElements();
7657   int NumEltsPerLane = 128 / EltBits;
7658   int OffsetLane = Offset / NumEltsPerLane;
7659   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7660          "Only 8, 16, and 32 bit elements can be extended.");
7661   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7662   assert(0 <= Offset && "Extension offset must be positive.");
7663   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7664          "Extension offset must be in the first lane or start an upper lane.");
7665
7666   // Check that an index is in same lane as the base offset.
7667   auto SafeOffset = [&](int Idx) {
7668     return OffsetLane == (Idx / NumEltsPerLane);
7669   };
7670
7671   // Shift along an input so that the offset base moves to the first element.
7672   auto ShuffleOffset = [&](SDValue V) {
7673     if (!Offset)
7674       return V;
7675
7676     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7677     for (int i = 0; i * Scale < NumElements; ++i) {
7678       int SrcIdx = i + Offset;
7679       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7680     }
7681     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7682   };
7683
7684   // Found a valid zext mask! Try various lowering strategies based on the
7685   // input type and available ISA extensions.
7686   if (Subtarget->hasSSE41()) {
7687     // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7688     // PUNPCK will catch this in a later shuffle match.
7689     if (Offset && Scale == 2 && VT.is128BitVector())
7690       return SDValue();
7691     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7692                                  NumElements / Scale);
7693     InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7694     return DAG.getBitcast(VT, InputV);
7695   }
7696
7697   assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
7698
7699   // For any extends we can cheat for larger element sizes and use shuffle
7700   // instructions that can fold with a load and/or copy.
7701   if (AnyExt && EltBits == 32) {
7702     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7703                          -1};
7704     return DAG.getBitcast(
7705         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7706                         DAG.getBitcast(MVT::v4i32, InputV),
7707                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7708   }
7709   if (AnyExt && EltBits == 16 && Scale > 2) {
7710     int PSHUFDMask[4] = {Offset / 2, -1,
7711                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7712     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7713                          DAG.getBitcast(MVT::v4i32, InputV),
7714                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7715     int PSHUFWMask[4] = {1, -1, -1, -1};
7716     unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7717     return DAG.getBitcast(
7718         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7719                         DAG.getBitcast(MVT::v8i16, InputV),
7720                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7721   }
7722
7723   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7724   // to 64-bits.
7725   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7726     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7727     assert(VT.is128BitVector() && "Unexpected vector width!");
7728
7729     int LoIdx = Offset * EltBits;
7730     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7731                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7732                                          DAG.getConstant(EltBits, DL, MVT::i8),
7733                                          DAG.getConstant(LoIdx, DL, MVT::i8)));
7734
7735     if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7736         !SafeOffset(Offset + 1))
7737       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7738
7739     int HiIdx = (Offset + 1) * EltBits;
7740     SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7741                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7742                                          DAG.getConstant(EltBits, DL, MVT::i8),
7743                                          DAG.getConstant(HiIdx, DL, MVT::i8)));
7744     return DAG.getNode(ISD::BITCAST, DL, VT,
7745                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7746   }
7747
7748   // If this would require more than 2 unpack instructions to expand, use
7749   // pshufb when available. We can only use more than 2 unpack instructions
7750   // when zero extending i8 elements which also makes it easier to use pshufb.
7751   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7752     assert(NumElements == 16 && "Unexpected byte vector width!");
7753     SDValue PSHUFBMask[16];
7754     for (int i = 0; i < 16; ++i) {
7755       int Idx = Offset + (i / Scale);
7756       PSHUFBMask[i] = DAG.getConstant(
7757           (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7758     }
7759     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7760     return DAG.getBitcast(VT,
7761                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7762                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7763                                                   MVT::v16i8, PSHUFBMask)));
7764   }
7765
7766   // If we are extending from an offset, ensure we start on a boundary that
7767   // we can unpack from.
7768   int AlignToUnpack = Offset % (NumElements / Scale);
7769   if (AlignToUnpack) {
7770     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7771     for (int i = AlignToUnpack; i < NumElements; ++i)
7772       ShMask[i - AlignToUnpack] = i;
7773     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7774     Offset -= AlignToUnpack;
7775   }
7776
7777   // Otherwise emit a sequence of unpacks.
7778   do {
7779     unsigned UnpackLoHi = X86ISD::UNPCKL;
7780     if (Offset >= (NumElements / 2)) {
7781       UnpackLoHi = X86ISD::UNPCKH;
7782       Offset -= (NumElements / 2);
7783     }
7784
7785     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7786     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7787                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7788     InputV = DAG.getBitcast(InputVT, InputV);
7789     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7790     Scale /= 2;
7791     EltBits *= 2;
7792     NumElements /= 2;
7793   } while (Scale > 1);
7794   return DAG.getBitcast(VT, InputV);
7795 }
7796
7797 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7798 ///
7799 /// This routine will try to do everything in its power to cleverly lower
7800 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7801 /// check for the profitability of this lowering,  it tries to aggressively
7802 /// match this pattern. It will use all of the micro-architectural details it
7803 /// can to emit an efficient lowering. It handles both blends with all-zero
7804 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7805 /// masking out later).
7806 ///
7807 /// The reason we have dedicated lowering for zext-style shuffles is that they
7808 /// are both incredibly common and often quite performance sensitive.
7809 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7810     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7811     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7812   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7813
7814   int Bits = VT.getSizeInBits();
7815   int NumLanes = Bits / 128;
7816   int NumElements = VT.getVectorNumElements();
7817   int NumEltsPerLane = NumElements / NumLanes;
7818   assert(VT.getScalarSizeInBits() <= 32 &&
7819          "Exceeds 32-bit integer zero extension limit");
7820   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7821
7822   // Define a helper function to check a particular ext-scale and lower to it if
7823   // valid.
7824   auto Lower = [&](int Scale) -> SDValue {
7825     SDValue InputV;
7826     bool AnyExt = true;
7827     int Offset = 0;
7828     int Matches = 0;
7829     for (int i = 0; i < NumElements; ++i) {
7830       int M = Mask[i];
7831       if (M == -1)
7832         continue; // Valid anywhere but doesn't tell us anything.
7833       if (i % Scale != 0) {
7834         // Each of the extended elements need to be zeroable.
7835         if (!Zeroable[i])
7836           return SDValue();
7837
7838         // We no longer are in the anyext case.
7839         AnyExt = false;
7840         continue;
7841       }
7842
7843       // Each of the base elements needs to be consecutive indices into the
7844       // same input vector.
7845       SDValue V = M < NumElements ? V1 : V2;
7846       M = M % NumElements;
7847       if (!InputV) {
7848         InputV = V;
7849         Offset = M - (i / Scale);
7850       } else if (InputV != V)
7851         return SDValue(); // Flip-flopping inputs.
7852
7853       // Offset must start in the lowest 128-bit lane or at the start of an
7854       // upper lane.
7855       // FIXME: Is it ever worth allowing a negative base offset?
7856       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7857             (Offset % NumEltsPerLane) == 0))
7858         return SDValue();
7859
7860       // If we are offsetting, all referenced entries must come from the same
7861       // lane.
7862       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7863         return SDValue();
7864
7865       if ((M % NumElements) != (Offset + (i / Scale)))
7866         return SDValue(); // Non-consecutive strided elements.
7867       Matches++;
7868     }
7869
7870     // If we fail to find an input, we have a zero-shuffle which should always
7871     // have already been handled.
7872     // FIXME: Maybe handle this here in case during blending we end up with one?
7873     if (!InputV)
7874       return SDValue();
7875
7876     // If we are offsetting, don't extend if we only match a single input, we
7877     // can always do better by using a basic PSHUF or PUNPCK.
7878     if (Offset != 0 && Matches < 2)
7879       return SDValue();
7880
7881     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7882         DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7883   };
7884
7885   // The widest scale possible for extending is to a 64-bit integer.
7886   assert(Bits % 64 == 0 &&
7887          "The number of bits in a vector must be divisible by 64 on x86!");
7888   int NumExtElements = Bits / 64;
7889
7890   // Each iteration, try extending the elements half as much, but into twice as
7891   // many elements.
7892   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7893     assert(NumElements % NumExtElements == 0 &&
7894            "The input vector size must be divisible by the extended size.");
7895     if (SDValue V = Lower(NumElements / NumExtElements))
7896       return V;
7897   }
7898
7899   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7900   if (Bits != 128)
7901     return SDValue();
7902
7903   // Returns one of the source operands if the shuffle can be reduced to a
7904   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7905   auto CanZExtLowHalf = [&]() {
7906     for (int i = NumElements / 2; i != NumElements; ++i)
7907       if (!Zeroable[i])
7908         return SDValue();
7909     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7910       return V1;
7911     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7912       return V2;
7913     return SDValue();
7914   };
7915
7916   if (SDValue V = CanZExtLowHalf()) {
7917     V = DAG.getBitcast(MVT::v2i64, V);
7918     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7919     return DAG.getBitcast(VT, V);
7920   }
7921
7922   // No viable ext lowering found.
7923   return SDValue();
7924 }
7925
7926 /// \brief Try to get a scalar value for a specific element of a vector.
7927 ///
7928 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7929 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7930                                               SelectionDAG &DAG) {
7931   MVT VT = V.getSimpleValueType();
7932   MVT EltVT = VT.getVectorElementType();
7933   while (V.getOpcode() == ISD::BITCAST)
7934     V = V.getOperand(0);
7935   // If the bitcasts shift the element size, we can't extract an equivalent
7936   // element from it.
7937   MVT NewVT = V.getSimpleValueType();
7938   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7939     return SDValue();
7940
7941   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7942       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7943     // Ensure the scalar operand is the same size as the destination.
7944     // FIXME: Add support for scalar truncation where possible.
7945     SDValue S = V.getOperand(Idx);
7946     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7947       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7948   }
7949
7950   return SDValue();
7951 }
7952
7953 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7954 ///
7955 /// This is particularly important because the set of instructions varies
7956 /// significantly based on whether the operand is a load or not.
7957 static bool isShuffleFoldableLoad(SDValue V) {
7958   while (V.getOpcode() == ISD::BITCAST)
7959     V = V.getOperand(0);
7960
7961   return ISD::isNON_EXTLoad(V.getNode());
7962 }
7963
7964 /// \brief Try to lower insertion of a single element into a zero vector.
7965 ///
7966 /// This is a common pattern that we have especially efficient patterns to lower
7967 /// across all subtarget feature sets.
7968 static SDValue lowerVectorShuffleAsElementInsertion(
7969     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7970     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7971   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7972   MVT ExtVT = VT;
7973   MVT EltVT = VT.getVectorElementType();
7974
7975   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7976                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7977                 Mask.begin();
7978   bool IsV1Zeroable = true;
7979   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7980     if (i != V2Index && !Zeroable[i]) {
7981       IsV1Zeroable = false;
7982       break;
7983     }
7984
7985   // Check for a single input from a SCALAR_TO_VECTOR node.
7986   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7987   // all the smarts here sunk into that routine. However, the current
7988   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7989   // vector shuffle lowering is dead.
7990   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7991                                                DAG);
7992   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7993     // We need to zext the scalar if it is smaller than an i32.
7994     V2S = DAG.getBitcast(EltVT, V2S);
7995     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7996       // Using zext to expand a narrow element won't work for non-zero
7997       // insertions.
7998       if (!IsV1Zeroable)
7999         return SDValue();
8000
8001       // Zero-extend directly to i32.
8002       ExtVT = MVT::v4i32;
8003       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
8004     }
8005     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
8006   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
8007              EltVT == MVT::i16) {
8008     // Either not inserting from the low element of the input or the input
8009     // element size is too small to use VZEXT_MOVL to clear the high bits.
8010     return SDValue();
8011   }
8012
8013   if (!IsV1Zeroable) {
8014     // If V1 can't be treated as a zero vector we have fewer options to lower
8015     // this. We can't support integer vectors or non-zero targets cheaply, and
8016     // the V1 elements can't be permuted in any way.
8017     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
8018     if (!VT.isFloatingPoint() || V2Index != 0)
8019       return SDValue();
8020     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
8021     V1Mask[V2Index] = -1;
8022     if (!isNoopShuffleMask(V1Mask))
8023       return SDValue();
8024     // This is essentially a special case blend operation, but if we have
8025     // general purpose blend operations, they are always faster. Bail and let
8026     // the rest of the lowering handle these as blends.
8027     if (Subtarget->hasSSE41())
8028       return SDValue();
8029
8030     // Otherwise, use MOVSD or MOVSS.
8031     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
8032            "Only two types of floating point element types to handle!");
8033     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
8034                        ExtVT, V1, V2);
8035   }
8036
8037   // This lowering only works for the low element with floating point vectors.
8038   if (VT.isFloatingPoint() && V2Index != 0)
8039     return SDValue();
8040
8041   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
8042   if (ExtVT != VT)
8043     V2 = DAG.getBitcast(VT, V2);
8044
8045   if (V2Index != 0) {
8046     // If we have 4 or fewer lanes we can cheaply shuffle the element into
8047     // the desired position. Otherwise it is more efficient to do a vector
8048     // shift left. We know that we can do a vector shift left because all
8049     // the inputs are zero.
8050     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
8051       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
8052       V2Shuffle[V2Index] = 0;
8053       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
8054     } else {
8055       V2 = DAG.getBitcast(MVT::v2i64, V2);
8056       V2 = DAG.getNode(
8057           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
8058           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
8059                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
8060                               DAG.getDataLayout(), VT)));
8061       V2 = DAG.getBitcast(VT, V2);
8062     }
8063   }
8064   return V2;
8065 }
8066
8067 /// \brief Try to lower broadcast of a single - truncated - integer element,
8068 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
8069 ///
8070 /// This assumes we have AVX2.
8071 static SDValue lowerVectorShuffleAsTruncBroadcast(SDLoc DL, MVT VT, SDValue V0,
8072                                                   int BroadcastIdx,
8073                                                   const X86Subtarget *Subtarget,
8074                                                   SelectionDAG &DAG) {
8075   assert(Subtarget->hasAVX2() &&
8076          "We can only lower integer broadcasts with AVX2!");
8077
8078   EVT EltVT = VT.getVectorElementType();
8079   EVT V0VT = V0.getValueType();
8080
8081   assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
8082   assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
8083
8084   EVT V0EltVT = V0VT.getVectorElementType();
8085   if (!V0EltVT.isInteger())
8086     return SDValue();
8087
8088   const unsigned EltSize = EltVT.getSizeInBits();
8089   const unsigned V0EltSize = V0EltVT.getSizeInBits();
8090
8091   // This is only a truncation if the original element type is larger.
8092   if (V0EltSize <= EltSize)
8093     return SDValue();
8094
8095   assert(((V0EltSize % EltSize) == 0) &&
8096          "Scalar type sizes must all be powers of 2 on x86!");
8097
8098   const unsigned V0Opc = V0.getOpcode();
8099   const unsigned Scale = V0EltSize / EltSize;
8100   const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
8101
8102   if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
8103       V0Opc != ISD::BUILD_VECTOR)
8104     return SDValue();
8105
8106   SDValue Scalar = V0.getOperand(V0BroadcastIdx);
8107
8108   // If we're extracting non-least-significant bits, shift so we can truncate.
8109   // Hopefully, we can fold away the trunc/srl/load into the broadcast.
8110   // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
8111   // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
8112   if (const int OffsetIdx = BroadcastIdx % Scale)
8113     Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
8114             DAG.getConstant(OffsetIdx * EltSize, DL, Scalar.getValueType()));
8115
8116   return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
8117                      DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
8118 }
8119
8120 /// \brief Try to lower broadcast of a single element.
8121 ///
8122 /// For convenience, this code also bundles all of the subtarget feature set
8123 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8124 /// a convenient way to factor it out.
8125 /// FIXME: This is very similar to LowerVectorBroadcast - can we merge them?
8126 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
8127                                              ArrayRef<int> Mask,
8128                                              const X86Subtarget *Subtarget,
8129                                              SelectionDAG &DAG) {
8130   if (!Subtarget->hasAVX())
8131     return SDValue();
8132   if (VT.isInteger() && !Subtarget->hasAVX2())
8133     return SDValue();
8134
8135   // Check that the mask is a broadcast.
8136   int BroadcastIdx = -1;
8137   for (int M : Mask)
8138     if (M >= 0 && BroadcastIdx == -1)
8139       BroadcastIdx = M;
8140     else if (M >= 0 && M != BroadcastIdx)
8141       return SDValue();
8142
8143   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8144                                             "a sorted mask where the broadcast "
8145                                             "comes from V1.");
8146
8147   // Go up the chain of (vector) values to find a scalar load that we can
8148   // combine with the broadcast.
8149   for (;;) {
8150     switch (V.getOpcode()) {
8151     case ISD::CONCAT_VECTORS: {
8152       int OperandSize = Mask.size() / V.getNumOperands();
8153       V = V.getOperand(BroadcastIdx / OperandSize);
8154       BroadcastIdx %= OperandSize;
8155       continue;
8156     }
8157
8158     case ISD::INSERT_SUBVECTOR: {
8159       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8160       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8161       if (!ConstantIdx)
8162         break;
8163
8164       int BeginIdx = (int)ConstantIdx->getZExtValue();
8165       int EndIdx =
8166           BeginIdx + (int)VInner.getSimpleValueType().getVectorNumElements();
8167       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8168         BroadcastIdx -= BeginIdx;
8169         V = VInner;
8170       } else {
8171         V = VOuter;
8172       }
8173       continue;
8174     }
8175     }
8176     break;
8177   }
8178
8179   // Check if this is a broadcast of a scalar. We special case lowering
8180   // for scalars so that we can more effectively fold with loads.
8181   // First, look through bitcast: if the original value has a larger element
8182   // type than the shuffle, the broadcast element is in essence truncated.
8183   // Make that explicit to ease folding.
8184   if (V.getOpcode() == ISD::BITCAST && VT.isInteger())
8185     if (SDValue TruncBroadcast = lowerVectorShuffleAsTruncBroadcast(
8186             DL, VT, V.getOperand(0), BroadcastIdx, Subtarget, DAG))
8187       return TruncBroadcast;
8188
8189   MVT BroadcastVT = VT;
8190
8191   // Peek through any bitcast (only useful for loads).
8192   SDValue BC = V;
8193   while (BC.getOpcode() == ISD::BITCAST)
8194     BC = BC.getOperand(0);
8195
8196   // Also check the simpler case, where we can directly reuse the scalar.
8197   if (V.getOpcode() == ISD::BUILD_VECTOR ||
8198       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8199     V = V.getOperand(BroadcastIdx);
8200
8201     // If the scalar isn't a load, we can't broadcast from it in AVX1.
8202     // Only AVX2 has register broadcasts.
8203     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8204       return SDValue();
8205   } else if (MayFoldLoad(BC) && !cast<LoadSDNode>(BC)->isVolatile()) {
8206     // 32-bit targets need to load i64 as a f64 and then bitcast the result.
8207     if (!Subtarget->is64Bit() && VT.getScalarType() == MVT::i64)
8208       BroadcastVT = MVT::getVectorVT(MVT::f64, VT.getVectorNumElements());
8209
8210     // If we are broadcasting a load that is only used by the shuffle
8211     // then we can reduce the vector load to the broadcasted scalar load.
8212     LoadSDNode *Ld = cast<LoadSDNode>(BC);
8213     SDValue BaseAddr = Ld->getOperand(1);
8214     EVT AddrVT = BaseAddr.getValueType();
8215     EVT SVT = BroadcastVT.getScalarType();
8216     unsigned Offset = BroadcastIdx * SVT.getStoreSize();
8217     SDValue NewAddr = DAG.getNode(
8218         ISD::ADD, DL, AddrVT, BaseAddr,
8219         DAG.getConstant(Offset, DL, AddrVT));
8220     V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
8221                     DAG.getMachineFunction().getMachineMemOperand(
8222                         Ld->getMemOperand(), Offset, SVT.getStoreSize()));
8223   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8224     // We can't broadcast from a vector register without AVX2, and we can only
8225     // broadcast from the zero-element of a vector register.
8226     return SDValue();
8227   }
8228
8229   V = DAG.getNode(X86ISD::VBROADCAST, DL, BroadcastVT, V);
8230   return DAG.getBitcast(VT, V);
8231 }
8232
8233 // Check for whether we can use INSERTPS to perform the shuffle. We only use
8234 // INSERTPS when the V1 elements are already in the correct locations
8235 // because otherwise we can just always use two SHUFPS instructions which
8236 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
8237 // perform INSERTPS if a single V1 element is out of place and all V2
8238 // elements are zeroable.
8239 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
8240                                             ArrayRef<int> Mask,
8241                                             SelectionDAG &DAG) {
8242   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8243   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8244   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8245   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8246
8247   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8248
8249   unsigned ZMask = 0;
8250   int V1DstIndex = -1;
8251   int V2DstIndex = -1;
8252   bool V1UsedInPlace = false;
8253
8254   for (int i = 0; i < 4; ++i) {
8255     // Synthesize a zero mask from the zeroable elements (includes undefs).
8256     if (Zeroable[i]) {
8257       ZMask |= 1 << i;
8258       continue;
8259     }
8260
8261     // Flag if we use any V1 inputs in place.
8262     if (i == Mask[i]) {
8263       V1UsedInPlace = true;
8264       continue;
8265     }
8266
8267     // We can only insert a single non-zeroable element.
8268     if (V1DstIndex != -1 || V2DstIndex != -1)
8269       return SDValue();
8270
8271     if (Mask[i] < 4) {
8272       // V1 input out of place for insertion.
8273       V1DstIndex = i;
8274     } else {
8275       // V2 input for insertion.
8276       V2DstIndex = i;
8277     }
8278   }
8279
8280   // Don't bother if we have no (non-zeroable) element for insertion.
8281   if (V1DstIndex == -1 && V2DstIndex == -1)
8282     return SDValue();
8283
8284   // Determine element insertion src/dst indices. The src index is from the
8285   // start of the inserted vector, not the start of the concatenated vector.
8286   unsigned V2SrcIndex = 0;
8287   if (V1DstIndex != -1) {
8288     // If we have a V1 input out of place, we use V1 as the V2 element insertion
8289     // and don't use the original V2 at all.
8290     V2SrcIndex = Mask[V1DstIndex];
8291     V2DstIndex = V1DstIndex;
8292     V2 = V1;
8293   } else {
8294     V2SrcIndex = Mask[V2DstIndex] - 4;
8295   }
8296
8297   // If no V1 inputs are used in place, then the result is created only from
8298   // the zero mask and the V2 insertion - so remove V1 dependency.
8299   if (!V1UsedInPlace)
8300     V1 = DAG.getUNDEF(MVT::v4f32);
8301
8302   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8303   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8304
8305   // Insert the V2 element into the desired position.
8306   SDLoc DL(Op);
8307   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8308                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
8309 }
8310
8311 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8312 /// UNPCK instruction.
8313 ///
8314 /// This specifically targets cases where we end up with alternating between
8315 /// the two inputs, and so can permute them into something that feeds a single
8316 /// UNPCK instruction. Note that this routine only targets integer vectors
8317 /// because for floating point vectors we have a generalized SHUFPS lowering
8318 /// strategy that handles everything that doesn't *exactly* match an unpack,
8319 /// making this clever lowering unnecessary.
8320 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8321                                                     SDValue V1, SDValue V2,
8322                                                     ArrayRef<int> Mask,
8323                                                     SelectionDAG &DAG) {
8324   assert(!VT.isFloatingPoint() &&
8325          "This routine only supports integer vectors.");
8326   assert(!isSingleInputShuffleMask(Mask) &&
8327          "This routine should only be used when blending two inputs.");
8328   assert(Mask.size() >= 2 && "Single element masks are invalid.");
8329
8330   int Size = Mask.size();
8331
8332   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8333     return M >= 0 && M % Size < Size / 2;
8334   });
8335   int NumHiInputs = std::count_if(
8336       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8337
8338   bool UnpackLo = NumLoInputs >= NumHiInputs;
8339
8340   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8341     SmallVector<int, 32> V1Mask(Mask.size(), -1);
8342     SmallVector<int, 32> V2Mask(Mask.size(), -1);
8343
8344     for (int i = 0; i < Size; ++i) {
8345       if (Mask[i] < 0)
8346         continue;
8347
8348       // Each element of the unpack contains Scale elements from this mask.
8349       int UnpackIdx = i / Scale;
8350
8351       // We only handle the case where V1 feeds the first slots of the unpack.
8352       // We rely on canonicalization to ensure this is the case.
8353       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8354         return SDValue();
8355
8356       // Setup the mask for this input. The indexing is tricky as we have to
8357       // handle the unpack stride.
8358       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8359       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8360           Mask[i] % Size;
8361     }
8362
8363     // If we will have to shuffle both inputs to use the unpack, check whether
8364     // we can just unpack first and shuffle the result. If so, skip this unpack.
8365     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8366         !isNoopShuffleMask(V2Mask))
8367       return SDValue();
8368
8369     // Shuffle the inputs into place.
8370     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8371     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8372
8373     // Cast the inputs to the type we will use to unpack them.
8374     V1 = DAG.getBitcast(UnpackVT, V1);
8375     V2 = DAG.getBitcast(UnpackVT, V2);
8376
8377     // Unpack the inputs and cast the result back to the desired type.
8378     return DAG.getBitcast(
8379         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8380                         UnpackVT, V1, V2));
8381   };
8382
8383   // We try each unpack from the largest to the smallest to try and find one
8384   // that fits this mask.
8385   int OrigNumElements = VT.getVectorNumElements();
8386   int OrigScalarSize = VT.getScalarSizeInBits();
8387   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8388     int Scale = ScalarSize / OrigScalarSize;
8389     int NumElements = OrigNumElements / Scale;
8390     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8391     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8392       return Unpack;
8393   }
8394
8395   // If none of the unpack-rooted lowerings worked (or were profitable) try an
8396   // initial unpack.
8397   if (NumLoInputs == 0 || NumHiInputs == 0) {
8398     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8399            "We have to have *some* inputs!");
8400     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8401
8402     // FIXME: We could consider the total complexity of the permute of each
8403     // possible unpacking. Or at the least we should consider how many
8404     // half-crossings are created.
8405     // FIXME: We could consider commuting the unpacks.
8406
8407     SmallVector<int, 32> PermMask;
8408     PermMask.assign(Size, -1);
8409     for (int i = 0; i < Size; ++i) {
8410       if (Mask[i] < 0)
8411         continue;
8412
8413       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8414
8415       PermMask[i] =
8416           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8417     }
8418     return DAG.getVectorShuffle(
8419         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8420                             DL, VT, V1, V2),
8421         DAG.getUNDEF(VT), PermMask);
8422   }
8423
8424   return SDValue();
8425 }
8426
8427 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8428 ///
8429 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8430 /// support for floating point shuffles but not integer shuffles. These
8431 /// instructions will incur a domain crossing penalty on some chips though so
8432 /// it is better to avoid lowering through this for integer vectors where
8433 /// possible.
8434 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8435                                        const X86Subtarget *Subtarget,
8436                                        SelectionDAG &DAG) {
8437   SDLoc DL(Op);
8438   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8439   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8440   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8441   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8442   ArrayRef<int> Mask = SVOp->getMask();
8443   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8444
8445   if (isSingleInputShuffleMask(Mask)) {
8446     // Use low duplicate instructions for masks that match their pattern.
8447     if (Subtarget->hasSSE3())
8448       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8449         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8450
8451     // Straight shuffle of a single input vector. Simulate this by using the
8452     // single input as both of the "inputs" to this instruction..
8453     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8454
8455     if (Subtarget->hasAVX()) {
8456       // If we have AVX, we can use VPERMILPS which will allow folding a load
8457       // into the shuffle.
8458       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8459                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8460     }
8461
8462     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8463                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8464   }
8465   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8466   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8467
8468   // If we have a single input, insert that into V1 if we can do so cheaply.
8469   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8470     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8471             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8472       return Insertion;
8473     // Try inverting the insertion since for v2 masks it is easy to do and we
8474     // can't reliably sort the mask one way or the other.
8475     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8476                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8477     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8478             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8479       return Insertion;
8480   }
8481
8482   // Try to use one of the special instruction patterns to handle two common
8483   // blend patterns if a zero-blend above didn't work.
8484   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8485       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8486     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8487       // We can either use a special instruction to load over the low double or
8488       // to move just the low double.
8489       return DAG.getNode(
8490           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8491           DL, MVT::v2f64, V2,
8492           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8493
8494   if (Subtarget->hasSSE41())
8495     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8496                                                   Subtarget, DAG))
8497       return Blend;
8498
8499   // Use dedicated unpack instructions for masks that match their pattern.
8500   if (SDValue V =
8501           lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8502     return V;
8503
8504   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8505   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8506                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8507 }
8508
8509 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8510 ///
8511 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8512 /// the integer unit to minimize domain crossing penalties. However, for blends
8513 /// it falls back to the floating point shuffle operation with appropriate bit
8514 /// casting.
8515 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8516                                        const X86Subtarget *Subtarget,
8517                                        SelectionDAG &DAG) {
8518   SDLoc DL(Op);
8519   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8520   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8521   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8522   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8523   ArrayRef<int> Mask = SVOp->getMask();
8524   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8525
8526   if (isSingleInputShuffleMask(Mask)) {
8527     // Check for being able to broadcast a single element.
8528     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8529                                                           Mask, Subtarget, DAG))
8530       return Broadcast;
8531
8532     // Straight shuffle of a single input vector. For everything from SSE2
8533     // onward this has a single fast instruction with no scary immediates.
8534     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8535     V1 = DAG.getBitcast(MVT::v4i32, V1);
8536     int WidenedMask[4] = {
8537         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8538         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8539     return DAG.getBitcast(
8540         MVT::v2i64,
8541         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8542                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8543   }
8544   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8545   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8546   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8547   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8548
8549   // If we have a blend of two PACKUS operations an the blend aligns with the
8550   // low and half halves, we can just merge the PACKUS operations. This is
8551   // particularly important as it lets us merge shuffles that this routine itself
8552   // creates.
8553   auto GetPackNode = [](SDValue V) {
8554     while (V.getOpcode() == ISD::BITCAST)
8555       V = V.getOperand(0);
8556
8557     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8558   };
8559   if (SDValue V1Pack = GetPackNode(V1))
8560     if (SDValue V2Pack = GetPackNode(V2))
8561       return DAG.getBitcast(MVT::v2i64,
8562                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8563                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8564                                                      : V1Pack.getOperand(1),
8565                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8566                                                      : V2Pack.getOperand(1)));
8567
8568   // Try to use shift instructions.
8569   if (SDValue Shift =
8570           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8571     return Shift;
8572
8573   // When loading a scalar and then shuffling it into a vector we can often do
8574   // the insertion cheaply.
8575   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8576           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8577     return Insertion;
8578   // Try inverting the insertion since for v2 masks it is easy to do and we
8579   // can't reliably sort the mask one way or the other.
8580   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8581   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8582           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8583     return Insertion;
8584
8585   // We have different paths for blend lowering, but they all must use the
8586   // *exact* same predicate.
8587   bool IsBlendSupported = Subtarget->hasSSE41();
8588   if (IsBlendSupported)
8589     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8590                                                   Subtarget, DAG))
8591       return Blend;
8592
8593   // Use dedicated unpack instructions for masks that match their pattern.
8594   if (SDValue V =
8595           lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8596     return V;
8597
8598   // Try to use byte rotation instructions.
8599   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8600   if (Subtarget->hasSSSE3())
8601     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8602             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8603       return Rotate;
8604
8605   // If we have direct support for blends, we should lower by decomposing into
8606   // a permute. That will be faster than the domain cross.
8607   if (IsBlendSupported)
8608     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8609                                                       Mask, DAG);
8610
8611   // We implement this with SHUFPD which is pretty lame because it will likely
8612   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8613   // However, all the alternatives are still more cycles and newer chips don't
8614   // have this problem. It would be really nice if x86 had better shuffles here.
8615   V1 = DAG.getBitcast(MVT::v2f64, V1);
8616   V2 = DAG.getBitcast(MVT::v2f64, V2);
8617   return DAG.getBitcast(MVT::v2i64,
8618                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8619 }
8620
8621 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8622 ///
8623 /// This is used to disable more specialized lowerings when the shufps lowering
8624 /// will happen to be efficient.
8625 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8626   // This routine only handles 128-bit shufps.
8627   assert(Mask.size() == 4 && "Unsupported mask size!");
8628
8629   // To lower with a single SHUFPS we need to have the low half and high half
8630   // each requiring a single input.
8631   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8632     return false;
8633   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8634     return false;
8635
8636   return true;
8637 }
8638
8639 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8640 ///
8641 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8642 /// It makes no assumptions about whether this is the *best* lowering, it simply
8643 /// uses it.
8644 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8645                                             ArrayRef<int> Mask, SDValue V1,
8646                                             SDValue V2, SelectionDAG &DAG) {
8647   SDValue LowV = V1, HighV = V2;
8648   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8649
8650   int NumV2Elements =
8651       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8652
8653   if (NumV2Elements == 1) {
8654     int V2Index =
8655         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8656         Mask.begin();
8657
8658     // Compute the index adjacent to V2Index and in the same half by toggling
8659     // the low bit.
8660     int V2AdjIndex = V2Index ^ 1;
8661
8662     if (Mask[V2AdjIndex] == -1) {
8663       // Handles all the cases where we have a single V2 element and an undef.
8664       // This will only ever happen in the high lanes because we commute the
8665       // vector otherwise.
8666       if (V2Index < 2)
8667         std::swap(LowV, HighV);
8668       NewMask[V2Index] -= 4;
8669     } else {
8670       // Handle the case where the V2 element ends up adjacent to a V1 element.
8671       // To make this work, blend them together as the first step.
8672       int V1Index = V2AdjIndex;
8673       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8674       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8675                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8676
8677       // Now proceed to reconstruct the final blend as we have the necessary
8678       // high or low half formed.
8679       if (V2Index < 2) {
8680         LowV = V2;
8681         HighV = V1;
8682       } else {
8683         HighV = V2;
8684       }
8685       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8686       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8687     }
8688   } else if (NumV2Elements == 2) {
8689     if (Mask[0] < 4 && Mask[1] < 4) {
8690       // Handle the easy case where we have V1 in the low lanes and V2 in the
8691       // high lanes.
8692       NewMask[2] -= 4;
8693       NewMask[3] -= 4;
8694     } else if (Mask[2] < 4 && Mask[3] < 4) {
8695       // We also handle the reversed case because this utility may get called
8696       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8697       // arrange things in the right direction.
8698       NewMask[0] -= 4;
8699       NewMask[1] -= 4;
8700       HighV = V1;
8701       LowV = V2;
8702     } else {
8703       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8704       // trying to place elements directly, just blend them and set up the final
8705       // shuffle to place them.
8706
8707       // The first two blend mask elements are for V1, the second two are for
8708       // V2.
8709       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8710                           Mask[2] < 4 ? Mask[2] : Mask[3],
8711                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8712                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8713       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8714                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8715
8716       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8717       // a blend.
8718       LowV = HighV = V1;
8719       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8720       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8721       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8722       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8723     }
8724   }
8725   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8726                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8727 }
8728
8729 /// \brief Lower 4-lane 32-bit floating point shuffles.
8730 ///
8731 /// Uses instructions exclusively from the floating point unit to minimize
8732 /// domain crossing penalties, as these are sufficient to implement all v4f32
8733 /// shuffles.
8734 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8735                                        const X86Subtarget *Subtarget,
8736                                        SelectionDAG &DAG) {
8737   SDLoc DL(Op);
8738   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8739   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8740   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8741   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8742   ArrayRef<int> Mask = SVOp->getMask();
8743   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8744
8745   int NumV2Elements =
8746       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8747
8748   if (NumV2Elements == 0) {
8749     // Check for being able to broadcast a single element.
8750     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8751                                                           Mask, Subtarget, DAG))
8752       return Broadcast;
8753
8754     // Use even/odd duplicate instructions for masks that match their pattern.
8755     if (Subtarget->hasSSE3()) {
8756       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8757         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8758       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8759         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8760     }
8761
8762     if (Subtarget->hasAVX()) {
8763       // If we have AVX, we can use VPERMILPS which will allow folding a load
8764       // into the shuffle.
8765       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8766                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8767     }
8768
8769     // Otherwise, use a straight shuffle of a single input vector. We pass the
8770     // input vector to both operands to simulate this with a SHUFPS.
8771     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8772                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8773   }
8774
8775   // There are special ways we can lower some single-element blends. However, we
8776   // have custom ways we can lower more complex single-element blends below that
8777   // we defer to if both this and BLENDPS fail to match, so restrict this to
8778   // when the V2 input is targeting element 0 of the mask -- that is the fast
8779   // case here.
8780   if (NumV2Elements == 1 && Mask[0] >= 4)
8781     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8782                                                          Mask, Subtarget, DAG))
8783       return V;
8784
8785   if (Subtarget->hasSSE41()) {
8786     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8787                                                   Subtarget, DAG))
8788       return Blend;
8789
8790     // Use INSERTPS if we can complete the shuffle efficiently.
8791     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8792       return V;
8793
8794     if (!isSingleSHUFPSMask(Mask))
8795       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8796               DL, MVT::v4f32, V1, V2, Mask, DAG))
8797         return BlendPerm;
8798   }
8799
8800   // Use dedicated unpack instructions for masks that match their pattern.
8801   if (SDValue V =
8802           lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8803     return V;
8804
8805   // Otherwise fall back to a SHUFPS lowering strategy.
8806   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8807 }
8808
8809 /// \brief Lower 4-lane i32 vector shuffles.
8810 ///
8811 /// We try to handle these with integer-domain shuffles where we can, but for
8812 /// blends we use the floating point domain blend instructions.
8813 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8814                                        const X86Subtarget *Subtarget,
8815                                        SelectionDAG &DAG) {
8816   SDLoc DL(Op);
8817   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8818   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8819   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8820   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8821   ArrayRef<int> Mask = SVOp->getMask();
8822   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8823
8824   // Whenever we can lower this as a zext, that instruction is strictly faster
8825   // than any alternative. It also allows us to fold memory operands into the
8826   // shuffle in many cases.
8827   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8828                                                          Mask, Subtarget, DAG))
8829     return ZExt;
8830
8831   int NumV2Elements =
8832       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8833
8834   if (NumV2Elements == 0) {
8835     // Check for being able to broadcast a single element.
8836     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8837                                                           Mask, Subtarget, DAG))
8838       return Broadcast;
8839
8840     // Straight shuffle of a single input vector. For everything from SSE2
8841     // onward this has a single fast instruction with no scary immediates.
8842     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8843     // but we aren't actually going to use the UNPCK instruction because doing
8844     // so prevents folding a load into this instruction or making a copy.
8845     const int UnpackLoMask[] = {0, 0, 1, 1};
8846     const int UnpackHiMask[] = {2, 2, 3, 3};
8847     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8848       Mask = UnpackLoMask;
8849     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8850       Mask = UnpackHiMask;
8851
8852     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8853                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8854   }
8855
8856   // Try to use shift instructions.
8857   if (SDValue Shift =
8858           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8859     return Shift;
8860
8861   // There are special ways we can lower some single-element blends.
8862   if (NumV2Elements == 1)
8863     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8864                                                          Mask, Subtarget, DAG))
8865       return V;
8866
8867   // We have different paths for blend lowering, but they all must use the
8868   // *exact* same predicate.
8869   bool IsBlendSupported = Subtarget->hasSSE41();
8870   if (IsBlendSupported)
8871     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8872                                                   Subtarget, DAG))
8873       return Blend;
8874
8875   if (SDValue Masked =
8876           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8877     return Masked;
8878
8879   // Use dedicated unpack instructions for masks that match their pattern.
8880   if (SDValue V =
8881           lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8882     return V;
8883
8884   // Try to use byte rotation instructions.
8885   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8886   if (Subtarget->hasSSSE3())
8887     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8888             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8889       return Rotate;
8890
8891   // If we have direct support for blends, we should lower by decomposing into
8892   // a permute. That will be faster than the domain cross.
8893   if (IsBlendSupported)
8894     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8895                                                       Mask, DAG);
8896
8897   // Try to lower by permuting the inputs into an unpack instruction.
8898   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8899                                                             V2, Mask, DAG))
8900     return Unpack;
8901
8902   // We implement this with SHUFPS because it can blend from two vectors.
8903   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8904   // up the inputs, bypassing domain shift penalties that we would encur if we
8905   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8906   // relevant.
8907   return DAG.getBitcast(
8908       MVT::v4i32,
8909       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8910                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8911 }
8912
8913 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8914 /// shuffle lowering, and the most complex part.
8915 ///
8916 /// The lowering strategy is to try to form pairs of input lanes which are
8917 /// targeted at the same half of the final vector, and then use a dword shuffle
8918 /// to place them onto the right half, and finally unpack the paired lanes into
8919 /// their final position.
8920 ///
8921 /// The exact breakdown of how to form these dword pairs and align them on the
8922 /// correct sides is really tricky. See the comments within the function for
8923 /// more of the details.
8924 ///
8925 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8926 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8927 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8928 /// vector, form the analogous 128-bit 8-element Mask.
8929 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8930     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8931     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8932   assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
8933   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8934
8935   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8936   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8937   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8938
8939   SmallVector<int, 4> LoInputs;
8940   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8941                [](int M) { return M >= 0; });
8942   std::sort(LoInputs.begin(), LoInputs.end());
8943   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8944   SmallVector<int, 4> HiInputs;
8945   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8946                [](int M) { return M >= 0; });
8947   std::sort(HiInputs.begin(), HiInputs.end());
8948   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8949   int NumLToL =
8950       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8951   int NumHToL = LoInputs.size() - NumLToL;
8952   int NumLToH =
8953       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8954   int NumHToH = HiInputs.size() - NumLToH;
8955   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8956   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8957   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8958   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8959
8960   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8961   // such inputs we can swap two of the dwords across the half mark and end up
8962   // with <=2 inputs to each half in each half. Once there, we can fall through
8963   // to the generic code below. For example:
8964   //
8965   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8966   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8967   //
8968   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8969   // and an existing 2-into-2 on the other half. In this case we may have to
8970   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8971   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8972   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8973   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8974   // half than the one we target for fixing) will be fixed when we re-enter this
8975   // path. We will also combine away any sequence of PSHUFD instructions that
8976   // result into a single instruction. Here is an example of the tricky case:
8977   //
8978   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8979   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8980   //
8981   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8982   //
8983   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8984   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8985   //
8986   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8987   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8988   //
8989   // The result is fine to be handled by the generic logic.
8990   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8991                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8992                           int AOffset, int BOffset) {
8993     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8994            "Must call this with A having 3 or 1 inputs from the A half.");
8995     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8996            "Must call this with B having 1 or 3 inputs from the B half.");
8997     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8998            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8999
9000     bool ThreeAInputs = AToAInputs.size() == 3;
9001
9002     // Compute the index of dword with only one word among the three inputs in
9003     // a half by taking the sum of the half with three inputs and subtracting
9004     // the sum of the actual three inputs. The difference is the remaining
9005     // slot.
9006     int ADWord, BDWord;
9007     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
9008     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
9009     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
9010     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
9011     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
9012     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
9013     int TripleNonInputIdx =
9014         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
9015     TripleDWord = TripleNonInputIdx / 2;
9016
9017     // We use xor with one to compute the adjacent DWord to whichever one the
9018     // OneInput is in.
9019     OneInputDWord = (OneInput / 2) ^ 1;
9020
9021     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
9022     // and BToA inputs. If there is also such a problem with the BToB and AToB
9023     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
9024     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
9025     // is essential that we don't *create* a 3<-1 as then we might oscillate.
9026     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
9027       // Compute how many inputs will be flipped by swapping these DWords. We
9028       // need
9029       // to balance this to ensure we don't form a 3-1 shuffle in the other
9030       // half.
9031       int NumFlippedAToBInputs =
9032           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
9033           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
9034       int NumFlippedBToBInputs =
9035           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
9036           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
9037       if ((NumFlippedAToBInputs == 1 &&
9038            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
9039           (NumFlippedBToBInputs == 1 &&
9040            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
9041         // We choose whether to fix the A half or B half based on whether that
9042         // half has zero flipped inputs. At zero, we may not be able to fix it
9043         // with that half. We also bias towards fixing the B half because that
9044         // will more commonly be the high half, and we have to bias one way.
9045         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
9046                                                        ArrayRef<int> Inputs) {
9047           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
9048           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
9049                                          PinnedIdx ^ 1) != Inputs.end();
9050           // Determine whether the free index is in the flipped dword or the
9051           // unflipped dword based on where the pinned index is. We use this bit
9052           // in an xor to conditionally select the adjacent dword.
9053           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
9054           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9055                                              FixFreeIdx) != Inputs.end();
9056           if (IsFixIdxInput == IsFixFreeIdxInput)
9057             FixFreeIdx += 1;
9058           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9059                                         FixFreeIdx) != Inputs.end();
9060           assert(IsFixIdxInput != IsFixFreeIdxInput &&
9061                  "We need to be changing the number of flipped inputs!");
9062           int PSHUFHalfMask[] = {0, 1, 2, 3};
9063           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
9064           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
9065                           MVT::v8i16, V,
9066                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
9067
9068           for (int &M : Mask)
9069             if (M != -1 && M == FixIdx)
9070               M = FixFreeIdx;
9071             else if (M != -1 && M == FixFreeIdx)
9072               M = FixIdx;
9073         };
9074         if (NumFlippedBToBInputs != 0) {
9075           int BPinnedIdx =
9076               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
9077           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
9078         } else {
9079           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
9080           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
9081           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
9082         }
9083       }
9084     }
9085
9086     int PSHUFDMask[] = {0, 1, 2, 3};
9087     PSHUFDMask[ADWord] = BDWord;
9088     PSHUFDMask[BDWord] = ADWord;
9089     V = DAG.getBitcast(
9090         VT,
9091         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9092                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9093
9094     // Adjust the mask to match the new locations of A and B.
9095     for (int &M : Mask)
9096       if (M != -1 && M/2 == ADWord)
9097         M = 2 * BDWord + M % 2;
9098       else if (M != -1 && M/2 == BDWord)
9099         M = 2 * ADWord + M % 2;
9100
9101     // Recurse back into this routine to re-compute state now that this isn't
9102     // a 3 and 1 problem.
9103     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
9104                                                      DAG);
9105   };
9106   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
9107     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
9108   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
9109     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
9110
9111   // At this point there are at most two inputs to the low and high halves from
9112   // each half. That means the inputs can always be grouped into dwords and
9113   // those dwords can then be moved to the correct half with a dword shuffle.
9114   // We use at most one low and one high word shuffle to collect these paired
9115   // inputs into dwords, and finally a dword shuffle to place them.
9116   int PSHUFLMask[4] = {-1, -1, -1, -1};
9117   int PSHUFHMask[4] = {-1, -1, -1, -1};
9118   int PSHUFDMask[4] = {-1, -1, -1, -1};
9119
9120   // First fix the masks for all the inputs that are staying in their
9121   // original halves. This will then dictate the targets of the cross-half
9122   // shuffles.
9123   auto fixInPlaceInputs =
9124       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
9125                     MutableArrayRef<int> SourceHalfMask,
9126                     MutableArrayRef<int> HalfMask, int HalfOffset) {
9127     if (InPlaceInputs.empty())
9128       return;
9129     if (InPlaceInputs.size() == 1) {
9130       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9131           InPlaceInputs[0] - HalfOffset;
9132       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
9133       return;
9134     }
9135     if (IncomingInputs.empty()) {
9136       // Just fix all of the in place inputs.
9137       for (int Input : InPlaceInputs) {
9138         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
9139         PSHUFDMask[Input / 2] = Input / 2;
9140       }
9141       return;
9142     }
9143
9144     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
9145     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9146         InPlaceInputs[0] - HalfOffset;
9147     // Put the second input next to the first so that they are packed into
9148     // a dword. We find the adjacent index by toggling the low bit.
9149     int AdjIndex = InPlaceInputs[0] ^ 1;
9150     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
9151     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
9152     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
9153   };
9154   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
9155   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
9156
9157   // Now gather the cross-half inputs and place them into a free dword of
9158   // their target half.
9159   // FIXME: This operation could almost certainly be simplified dramatically to
9160   // look more like the 3-1 fixing operation.
9161   auto moveInputsToRightHalf = [&PSHUFDMask](
9162       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
9163       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
9164       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
9165       int DestOffset) {
9166     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
9167       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
9168     };
9169     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
9170                                                int Word) {
9171       int LowWord = Word & ~1;
9172       int HighWord = Word | 1;
9173       return isWordClobbered(SourceHalfMask, LowWord) ||
9174              isWordClobbered(SourceHalfMask, HighWord);
9175     };
9176
9177     if (IncomingInputs.empty())
9178       return;
9179
9180     if (ExistingInputs.empty()) {
9181       // Map any dwords with inputs from them into the right half.
9182       for (int Input : IncomingInputs) {
9183         // If the source half mask maps over the inputs, turn those into
9184         // swaps and use the swapped lane.
9185         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
9186           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
9187             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
9188                 Input - SourceOffset;
9189             // We have to swap the uses in our half mask in one sweep.
9190             for (int &M : HalfMask)
9191               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
9192                 M = Input;
9193               else if (M == Input)
9194                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9195           } else {
9196             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
9197                        Input - SourceOffset &&
9198                    "Previous placement doesn't match!");
9199           }
9200           // Note that this correctly re-maps both when we do a swap and when
9201           // we observe the other side of the swap above. We rely on that to
9202           // avoid swapping the members of the input list directly.
9203           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9204         }
9205
9206         // Map the input's dword into the correct half.
9207         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
9208           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
9209         else
9210           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
9211                      Input / 2 &&
9212                  "Previous placement doesn't match!");
9213       }
9214
9215       // And just directly shift any other-half mask elements to be same-half
9216       // as we will have mirrored the dword containing the element into the
9217       // same position within that half.
9218       for (int &M : HalfMask)
9219         if (M >= SourceOffset && M < SourceOffset + 4) {
9220           M = M - SourceOffset + DestOffset;
9221           assert(M >= 0 && "This should never wrap below zero!");
9222         }
9223       return;
9224     }
9225
9226     // Ensure we have the input in a viable dword of its current half. This
9227     // is particularly tricky because the original position may be clobbered
9228     // by inputs being moved and *staying* in that half.
9229     if (IncomingInputs.size() == 1) {
9230       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9231         int InputFixed = std::find(std::begin(SourceHalfMask),
9232                                    std::end(SourceHalfMask), -1) -
9233                          std::begin(SourceHalfMask) + SourceOffset;
9234         SourceHalfMask[InputFixed - SourceOffset] =
9235             IncomingInputs[0] - SourceOffset;
9236         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
9237                      InputFixed);
9238         IncomingInputs[0] = InputFixed;
9239       }
9240     } else if (IncomingInputs.size() == 2) {
9241       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
9242           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9243         // We have two non-adjacent or clobbered inputs we need to extract from
9244         // the source half. To do this, we need to map them into some adjacent
9245         // dword slot in the source mask.
9246         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
9247                               IncomingInputs[1] - SourceOffset};
9248
9249         // If there is a free slot in the source half mask adjacent to one of
9250         // the inputs, place the other input in it. We use (Index XOR 1) to
9251         // compute an adjacent index.
9252         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
9253             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
9254           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
9255           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9256           InputsFixed[1] = InputsFixed[0] ^ 1;
9257         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
9258                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
9259           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
9260           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
9261           InputsFixed[0] = InputsFixed[1] ^ 1;
9262         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
9263                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9264           // The two inputs are in the same DWord but it is clobbered and the
9265           // adjacent DWord isn't used at all. Move both inputs to the free
9266           // slot.
9267           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9268           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9269           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9270           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9271         } else {
9272           // The only way we hit this point is if there is no clobbering
9273           // (because there are no off-half inputs to this half) and there is no
9274           // free slot adjacent to one of the inputs. In this case, we have to
9275           // swap an input with a non-input.
9276           for (int i = 0; i < 4; ++i)
9277             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9278                    "We can't handle any clobbers here!");
9279           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9280                  "Cannot have adjacent inputs here!");
9281
9282           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9283           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9284
9285           // We also have to update the final source mask in this case because
9286           // it may need to undo the above swap.
9287           for (int &M : FinalSourceHalfMask)
9288             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9289               M = InputsFixed[1] + SourceOffset;
9290             else if (M == InputsFixed[1] + SourceOffset)
9291               M = (InputsFixed[0] ^ 1) + SourceOffset;
9292
9293           InputsFixed[1] = InputsFixed[0] ^ 1;
9294         }
9295
9296         // Point everything at the fixed inputs.
9297         for (int &M : HalfMask)
9298           if (M == IncomingInputs[0])
9299             M = InputsFixed[0] + SourceOffset;
9300           else if (M == IncomingInputs[1])
9301             M = InputsFixed[1] + SourceOffset;
9302
9303         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9304         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9305       }
9306     } else {
9307       llvm_unreachable("Unhandled input size!");
9308     }
9309
9310     // Now hoist the DWord down to the right half.
9311     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9312     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9313     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9314     for (int &M : HalfMask)
9315       for (int Input : IncomingInputs)
9316         if (M == Input)
9317           M = FreeDWord * 2 + Input % 2;
9318   };
9319   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9320                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
9321   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9322                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
9323
9324   // Now enact all the shuffles we've computed to move the inputs into their
9325   // target half.
9326   if (!isNoopShuffleMask(PSHUFLMask))
9327     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9328                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9329   if (!isNoopShuffleMask(PSHUFHMask))
9330     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9331                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9332   if (!isNoopShuffleMask(PSHUFDMask))
9333     V = DAG.getBitcast(
9334         VT,
9335         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9336                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9337
9338   // At this point, each half should contain all its inputs, and we can then
9339   // just shuffle them into their final position.
9340   assert(std::count_if(LoMask.begin(), LoMask.end(),
9341                        [](int M) { return M >= 4; }) == 0 &&
9342          "Failed to lift all the high half inputs to the low mask!");
9343   assert(std::count_if(HiMask.begin(), HiMask.end(),
9344                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9345          "Failed to lift all the low half inputs to the high mask!");
9346
9347   // Do a half shuffle for the low mask.
9348   if (!isNoopShuffleMask(LoMask))
9349     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9350                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9351
9352   // Do a half shuffle with the high mask after shifting its values down.
9353   for (int &M : HiMask)
9354     if (M >= 0)
9355       M -= 4;
9356   if (!isNoopShuffleMask(HiMask))
9357     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9358                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9359
9360   return V;
9361 }
9362
9363 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9364 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9365                                           SDValue V2, ArrayRef<int> Mask,
9366                                           SelectionDAG &DAG, bool &V1InUse,
9367                                           bool &V2InUse) {
9368   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9369   SDValue V1Mask[16];
9370   SDValue V2Mask[16];
9371   V1InUse = false;
9372   V2InUse = false;
9373
9374   int Size = Mask.size();
9375   int Scale = 16 / Size;
9376   for (int i = 0; i < 16; ++i) {
9377     if (Mask[i / Scale] == -1) {
9378       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9379     } else {
9380       const int ZeroMask = 0x80;
9381       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9382                                           : ZeroMask;
9383       int V2Idx = Mask[i / Scale] < Size
9384                       ? ZeroMask
9385                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
9386       if (Zeroable[i / Scale])
9387         V1Idx = V2Idx = ZeroMask;
9388       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9389       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9390       V1InUse |= (ZeroMask != V1Idx);
9391       V2InUse |= (ZeroMask != V2Idx);
9392     }
9393   }
9394
9395   if (V1InUse)
9396     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9397                      DAG.getBitcast(MVT::v16i8, V1),
9398                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9399   if (V2InUse)
9400     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9401                      DAG.getBitcast(MVT::v16i8, V2),
9402                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9403
9404   // If we need shuffled inputs from both, blend the two.
9405   SDValue V;
9406   if (V1InUse && V2InUse)
9407     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9408   else
9409     V = V1InUse ? V1 : V2;
9410
9411   // Cast the result back to the correct type.
9412   return DAG.getBitcast(VT, V);
9413 }
9414
9415 /// \brief Generic lowering of 8-lane i16 shuffles.
9416 ///
9417 /// This handles both single-input shuffles and combined shuffle/blends with
9418 /// two inputs. The single input shuffles are immediately delegated to
9419 /// a dedicated lowering routine.
9420 ///
9421 /// The blends are lowered in one of three fundamental ways. If there are few
9422 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9423 /// of the input is significantly cheaper when lowered as an interleaving of
9424 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9425 /// halves of the inputs separately (making them have relatively few inputs)
9426 /// and then concatenate them.
9427 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9428                                        const X86Subtarget *Subtarget,
9429                                        SelectionDAG &DAG) {
9430   SDLoc DL(Op);
9431   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9432   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9433   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9434   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9435   ArrayRef<int> OrigMask = SVOp->getMask();
9436   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9437                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9438   MutableArrayRef<int> Mask(MaskStorage);
9439
9440   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9441
9442   // Whenever we can lower this as a zext, that instruction is strictly faster
9443   // than any alternative.
9444   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9445           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9446     return ZExt;
9447
9448   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9449   (void)isV1;
9450   auto isV2 = [](int M) { return M >= 8; };
9451
9452   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9453
9454   if (NumV2Inputs == 0) {
9455     // Check for being able to broadcast a single element.
9456     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9457                                                           Mask, Subtarget, DAG))
9458       return Broadcast;
9459
9460     // Try to use shift instructions.
9461     if (SDValue Shift =
9462             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9463       return Shift;
9464
9465     // Use dedicated unpack instructions for masks that match their pattern.
9466     if (SDValue V =
9467             lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9468       return V;
9469
9470     // Try to use byte rotation instructions.
9471     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9472                                                         Mask, Subtarget, DAG))
9473       return Rotate;
9474
9475     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9476                                                      Subtarget, DAG);
9477   }
9478
9479   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9480          "All single-input shuffles should be canonicalized to be V1-input "
9481          "shuffles.");
9482
9483   // Try to use shift instructions.
9484   if (SDValue Shift =
9485           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9486     return Shift;
9487
9488   // See if we can use SSE4A Extraction / Insertion.
9489   if (Subtarget->hasSSE4A())
9490     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9491       return V;
9492
9493   // There are special ways we can lower some single-element blends.
9494   if (NumV2Inputs == 1)
9495     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9496                                                          Mask, Subtarget, DAG))
9497       return V;
9498
9499   // We have different paths for blend lowering, but they all must use the
9500   // *exact* same predicate.
9501   bool IsBlendSupported = Subtarget->hasSSE41();
9502   if (IsBlendSupported)
9503     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9504                                                   Subtarget, DAG))
9505       return Blend;
9506
9507   if (SDValue Masked =
9508           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9509     return Masked;
9510
9511   // Use dedicated unpack instructions for masks that match their pattern.
9512   if (SDValue V =
9513           lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9514     return V;
9515
9516   // Try to use byte rotation instructions.
9517   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9518           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9519     return Rotate;
9520
9521   if (SDValue BitBlend =
9522           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9523     return BitBlend;
9524
9525   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9526                                                             V2, Mask, DAG))
9527     return Unpack;
9528
9529   // If we can't directly blend but can use PSHUFB, that will be better as it
9530   // can both shuffle and set up the inefficient blend.
9531   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9532     bool V1InUse, V2InUse;
9533     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9534                                       V1InUse, V2InUse);
9535   }
9536
9537   // We can always bit-blend if we have to so the fallback strategy is to
9538   // decompose into single-input permutes and blends.
9539   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9540                                                       Mask, DAG);
9541 }
9542
9543 /// \brief Check whether a compaction lowering can be done by dropping even
9544 /// elements and compute how many times even elements must be dropped.
9545 ///
9546 /// This handles shuffles which take every Nth element where N is a power of
9547 /// two. Example shuffle masks:
9548 ///
9549 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9550 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9551 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9552 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9553 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9554 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9555 ///
9556 /// Any of these lanes can of course be undef.
9557 ///
9558 /// This routine only supports N <= 3.
9559 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9560 /// for larger N.
9561 ///
9562 /// \returns N above, or the number of times even elements must be dropped if
9563 /// there is such a number. Otherwise returns zero.
9564 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9565   // Figure out whether we're looping over two inputs or just one.
9566   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9567
9568   // The modulus for the shuffle vector entries is based on whether this is
9569   // a single input or not.
9570   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9571   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9572          "We should only be called with masks with a power-of-2 size!");
9573
9574   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9575
9576   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9577   // and 2^3 simultaneously. This is because we may have ambiguity with
9578   // partially undef inputs.
9579   bool ViableForN[3] = {true, true, true};
9580
9581   for (int i = 0, e = Mask.size(); i < e; ++i) {
9582     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9583     // want.
9584     if (Mask[i] == -1)
9585       continue;
9586
9587     bool IsAnyViable = false;
9588     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9589       if (ViableForN[j]) {
9590         uint64_t N = j + 1;
9591
9592         // The shuffle mask must be equal to (i * 2^N) % M.
9593         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9594           IsAnyViable = true;
9595         else
9596           ViableForN[j] = false;
9597       }
9598     // Early exit if we exhaust the possible powers of two.
9599     if (!IsAnyViable)
9600       break;
9601   }
9602
9603   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9604     if (ViableForN[j])
9605       return j + 1;
9606
9607   // Return 0 as there is no viable power of two.
9608   return 0;
9609 }
9610
9611 /// \brief Generic lowering of v16i8 shuffles.
9612 ///
9613 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9614 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9615 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9616 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9617 /// back together.
9618 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9619                                        const X86Subtarget *Subtarget,
9620                                        SelectionDAG &DAG) {
9621   SDLoc DL(Op);
9622   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9623   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9624   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9625   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9626   ArrayRef<int> Mask = SVOp->getMask();
9627   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9628
9629   // Try to use shift instructions.
9630   if (SDValue Shift =
9631           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9632     return Shift;
9633
9634   // Try to use byte rotation instructions.
9635   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9636           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9637     return Rotate;
9638
9639   // Try to use a zext lowering.
9640   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9641           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9642     return ZExt;
9643
9644   // See if we can use SSE4A Extraction / Insertion.
9645   if (Subtarget->hasSSE4A())
9646     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9647       return V;
9648
9649   int NumV2Elements =
9650       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9651
9652   // For single-input shuffles, there are some nicer lowering tricks we can use.
9653   if (NumV2Elements == 0) {
9654     // Check for being able to broadcast a single element.
9655     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9656                                                           Mask, Subtarget, DAG))
9657       return Broadcast;
9658
9659     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9660     // Notably, this handles splat and partial-splat shuffles more efficiently.
9661     // However, it only makes sense if the pre-duplication shuffle simplifies
9662     // things significantly. Currently, this means we need to be able to
9663     // express the pre-duplication shuffle as an i16 shuffle.
9664     //
9665     // FIXME: We should check for other patterns which can be widened into an
9666     // i16 shuffle as well.
9667     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9668       for (int i = 0; i < 16; i += 2)
9669         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9670           return false;
9671
9672       return true;
9673     };
9674     auto tryToWidenViaDuplication = [&]() -> SDValue {
9675       if (!canWidenViaDuplication(Mask))
9676         return SDValue();
9677       SmallVector<int, 4> LoInputs;
9678       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9679                    [](int M) { return M >= 0 && M < 8; });
9680       std::sort(LoInputs.begin(), LoInputs.end());
9681       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9682                      LoInputs.end());
9683       SmallVector<int, 4> HiInputs;
9684       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9685                    [](int M) { return M >= 8; });
9686       std::sort(HiInputs.begin(), HiInputs.end());
9687       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9688                      HiInputs.end());
9689
9690       bool TargetLo = LoInputs.size() >= HiInputs.size();
9691       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9692       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9693
9694       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9695       SmallDenseMap<int, int, 8> LaneMap;
9696       for (int I : InPlaceInputs) {
9697         PreDupI16Shuffle[I/2] = I/2;
9698         LaneMap[I] = I;
9699       }
9700       int j = TargetLo ? 0 : 4, je = j + 4;
9701       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9702         // Check if j is already a shuffle of this input. This happens when
9703         // there are two adjacent bytes after we move the low one.
9704         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9705           // If we haven't yet mapped the input, search for a slot into which
9706           // we can map it.
9707           while (j < je && PreDupI16Shuffle[j] != -1)
9708             ++j;
9709
9710           if (j == je)
9711             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9712             return SDValue();
9713
9714           // Map this input with the i16 shuffle.
9715           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9716         }
9717
9718         // Update the lane map based on the mapping we ended up with.
9719         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9720       }
9721       V1 = DAG.getBitcast(
9722           MVT::v16i8,
9723           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9724                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9725
9726       // Unpack the bytes to form the i16s that will be shuffled into place.
9727       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9728                        MVT::v16i8, V1, V1);
9729
9730       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9731       for (int i = 0; i < 16; ++i)
9732         if (Mask[i] != -1) {
9733           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9734           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9735           if (PostDupI16Shuffle[i / 2] == -1)
9736             PostDupI16Shuffle[i / 2] = MappedMask;
9737           else
9738             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9739                    "Conflicting entrties in the original shuffle!");
9740         }
9741       return DAG.getBitcast(
9742           MVT::v16i8,
9743           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9744                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9745     };
9746     if (SDValue V = tryToWidenViaDuplication())
9747       return V;
9748   }
9749
9750   if (SDValue Masked =
9751           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9752     return Masked;
9753
9754   // Use dedicated unpack instructions for masks that match their pattern.
9755   if (SDValue V =
9756           lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9757     return V;
9758
9759   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9760   // with PSHUFB. It is important to do this before we attempt to generate any
9761   // blends but after all of the single-input lowerings. If the single input
9762   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9763   // want to preserve that and we can DAG combine any longer sequences into
9764   // a PSHUFB in the end. But once we start blending from multiple inputs,
9765   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9766   // and there are *very* few patterns that would actually be faster than the
9767   // PSHUFB approach because of its ability to zero lanes.
9768   //
9769   // FIXME: The only exceptions to the above are blends which are exact
9770   // interleavings with direct instructions supporting them. We currently don't
9771   // handle those well here.
9772   if (Subtarget->hasSSSE3()) {
9773     bool V1InUse = false;
9774     bool V2InUse = false;
9775
9776     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9777                                                 DAG, V1InUse, V2InUse);
9778
9779     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9780     // do so. This avoids using them to handle blends-with-zero which is
9781     // important as a single pshufb is significantly faster for that.
9782     if (V1InUse && V2InUse) {
9783       if (Subtarget->hasSSE41())
9784         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9785                                                       Mask, Subtarget, DAG))
9786           return Blend;
9787
9788       // We can use an unpack to do the blending rather than an or in some
9789       // cases. Even though the or may be (very minorly) more efficient, we
9790       // preference this lowering because there are common cases where part of
9791       // the complexity of the shuffles goes away when we do the final blend as
9792       // an unpack.
9793       // FIXME: It might be worth trying to detect if the unpack-feeding
9794       // shuffles will both be pshufb, in which case we shouldn't bother with
9795       // this.
9796       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9797               DL, MVT::v16i8, V1, V2, Mask, DAG))
9798         return Unpack;
9799     }
9800
9801     return PSHUFB;
9802   }
9803
9804   // There are special ways we can lower some single-element blends.
9805   if (NumV2Elements == 1)
9806     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9807                                                          Mask, Subtarget, DAG))
9808       return V;
9809
9810   if (SDValue BitBlend =
9811           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9812     return BitBlend;
9813
9814   // Check whether a compaction lowering can be done. This handles shuffles
9815   // which take every Nth element for some even N. See the helper function for
9816   // details.
9817   //
9818   // We special case these as they can be particularly efficiently handled with
9819   // the PACKUSB instruction on x86 and they show up in common patterns of
9820   // rearranging bytes to truncate wide elements.
9821   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9822     // NumEvenDrops is the power of two stride of the elements. Another way of
9823     // thinking about it is that we need to drop the even elements this many
9824     // times to get the original input.
9825     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9826
9827     // First we need to zero all the dropped bytes.
9828     assert(NumEvenDrops <= 3 &&
9829            "No support for dropping even elements more than 3 times.");
9830     // We use the mask type to pick which bytes are preserved based on how many
9831     // elements are dropped.
9832     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9833     SDValue ByteClearMask = DAG.getBitcast(
9834         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9835     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9836     if (!IsSingleInput)
9837       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9838
9839     // Now pack things back together.
9840     V1 = DAG.getBitcast(MVT::v8i16, V1);
9841     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9842     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9843     for (int i = 1; i < NumEvenDrops; ++i) {
9844       Result = DAG.getBitcast(MVT::v8i16, Result);
9845       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9846     }
9847
9848     return Result;
9849   }
9850
9851   // Handle multi-input cases by blending single-input shuffles.
9852   if (NumV2Elements > 0)
9853     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9854                                                       Mask, DAG);
9855
9856   // The fallback path for single-input shuffles widens this into two v8i16
9857   // vectors with unpacks, shuffles those, and then pulls them back together
9858   // with a pack.
9859   SDValue V = V1;
9860
9861   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9862   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9863   for (int i = 0; i < 16; ++i)
9864     if (Mask[i] >= 0)
9865       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9866
9867   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9868
9869   SDValue VLoHalf, VHiHalf;
9870   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9871   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9872   // i16s.
9873   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9874                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9875       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9876                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9877     // Use a mask to drop the high bytes.
9878     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9879     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9880                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9881
9882     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9883     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9884
9885     // Squash the masks to point directly into VLoHalf.
9886     for (int &M : LoBlendMask)
9887       if (M >= 0)
9888         M /= 2;
9889     for (int &M : HiBlendMask)
9890       if (M >= 0)
9891         M /= 2;
9892   } else {
9893     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9894     // VHiHalf so that we can blend them as i16s.
9895     VLoHalf = DAG.getBitcast(
9896         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9897     VHiHalf = DAG.getBitcast(
9898         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9899   }
9900
9901   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9902   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9903
9904   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9905 }
9906
9907 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9908 ///
9909 /// This routine breaks down the specific type of 128-bit shuffle and
9910 /// dispatches to the lowering routines accordingly.
9911 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9912                                         MVT VT, const X86Subtarget *Subtarget,
9913                                         SelectionDAG &DAG) {
9914   switch (VT.SimpleTy) {
9915   case MVT::v2i64:
9916     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9917   case MVT::v2f64:
9918     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9919   case MVT::v4i32:
9920     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9921   case MVT::v4f32:
9922     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9923   case MVT::v8i16:
9924     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9925   case MVT::v16i8:
9926     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9927
9928   default:
9929     llvm_unreachable("Unimplemented!");
9930   }
9931 }
9932
9933 /// \brief Helper function to test whether a shuffle mask could be
9934 /// simplified by widening the elements being shuffled.
9935 ///
9936 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9937 /// leaves it in an unspecified state.
9938 ///
9939 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9940 /// shuffle masks. The latter have the special property of a '-2' representing
9941 /// a zero-ed lane of a vector.
9942 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9943                                     SmallVectorImpl<int> &WidenedMask) {
9944   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9945     // If both elements are undef, its trivial.
9946     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9947       WidenedMask.push_back(SM_SentinelUndef);
9948       continue;
9949     }
9950
9951     // Check for an undef mask and a mask value properly aligned to fit with
9952     // a pair of values. If we find such a case, use the non-undef mask's value.
9953     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9954       WidenedMask.push_back(Mask[i + 1] / 2);
9955       continue;
9956     }
9957     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9958       WidenedMask.push_back(Mask[i] / 2);
9959       continue;
9960     }
9961
9962     // When zeroing, we need to spread the zeroing across both lanes to widen.
9963     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9964       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9965           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9966         WidenedMask.push_back(SM_SentinelZero);
9967         continue;
9968       }
9969       return false;
9970     }
9971
9972     // Finally check if the two mask values are adjacent and aligned with
9973     // a pair.
9974     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9975       WidenedMask.push_back(Mask[i] / 2);
9976       continue;
9977     }
9978
9979     // Otherwise we can't safely widen the elements used in this shuffle.
9980     return false;
9981   }
9982   assert(WidenedMask.size() == Mask.size() / 2 &&
9983          "Incorrect size of mask after widening the elements!");
9984
9985   return true;
9986 }
9987
9988 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9989 ///
9990 /// This routine just extracts two subvectors, shuffles them independently, and
9991 /// then concatenates them back together. This should work effectively with all
9992 /// AVX vector shuffle types.
9993 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9994                                           SDValue V2, ArrayRef<int> Mask,
9995                                           SelectionDAG &DAG) {
9996   assert(VT.getSizeInBits() >= 256 &&
9997          "Only for 256-bit or wider vector shuffles!");
9998   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9999   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
10000
10001   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
10002   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
10003
10004   int NumElements = VT.getVectorNumElements();
10005   int SplitNumElements = NumElements / 2;
10006   MVT ScalarVT = VT.getVectorElementType();
10007   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
10008
10009   // Rather than splitting build-vectors, just build two narrower build
10010   // vectors. This helps shuffling with splats and zeros.
10011   auto SplitVector = [&](SDValue V) {
10012     while (V.getOpcode() == ISD::BITCAST)
10013       V = V->getOperand(0);
10014
10015     MVT OrigVT = V.getSimpleValueType();
10016     int OrigNumElements = OrigVT.getVectorNumElements();
10017     int OrigSplitNumElements = OrigNumElements / 2;
10018     MVT OrigScalarVT = OrigVT.getVectorElementType();
10019     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
10020
10021     SDValue LoV, HiV;
10022
10023     auto *BV = dyn_cast<BuildVectorSDNode>(V);
10024     if (!BV) {
10025       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
10026                         DAG.getIntPtrConstant(0, DL));
10027       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
10028                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
10029     } else {
10030
10031       SmallVector<SDValue, 16> LoOps, HiOps;
10032       for (int i = 0; i < OrigSplitNumElements; ++i) {
10033         LoOps.push_back(BV->getOperand(i));
10034         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
10035       }
10036       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
10037       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
10038     }
10039     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
10040                           DAG.getBitcast(SplitVT, HiV));
10041   };
10042
10043   SDValue LoV1, HiV1, LoV2, HiV2;
10044   std::tie(LoV1, HiV1) = SplitVector(V1);
10045   std::tie(LoV2, HiV2) = SplitVector(V2);
10046
10047   // Now create two 4-way blends of these half-width vectors.
10048   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
10049     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
10050     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
10051     for (int i = 0; i < SplitNumElements; ++i) {
10052       int M = HalfMask[i];
10053       if (M >= NumElements) {
10054         if (M >= NumElements + SplitNumElements)
10055           UseHiV2 = true;
10056         else
10057           UseLoV2 = true;
10058         V2BlendMask.push_back(M - NumElements);
10059         V1BlendMask.push_back(-1);
10060         BlendMask.push_back(SplitNumElements + i);
10061       } else if (M >= 0) {
10062         if (M >= SplitNumElements)
10063           UseHiV1 = true;
10064         else
10065           UseLoV1 = true;
10066         V2BlendMask.push_back(-1);
10067         V1BlendMask.push_back(M);
10068         BlendMask.push_back(i);
10069       } else {
10070         V2BlendMask.push_back(-1);
10071         V1BlendMask.push_back(-1);
10072         BlendMask.push_back(-1);
10073       }
10074     }
10075
10076     // Because the lowering happens after all combining takes place, we need to
10077     // manually combine these blend masks as much as possible so that we create
10078     // a minimal number of high-level vector shuffle nodes.
10079
10080     // First try just blending the halves of V1 or V2.
10081     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
10082       return DAG.getUNDEF(SplitVT);
10083     if (!UseLoV2 && !UseHiV2)
10084       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10085     if (!UseLoV1 && !UseHiV1)
10086       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10087
10088     SDValue V1Blend, V2Blend;
10089     if (UseLoV1 && UseHiV1) {
10090       V1Blend =
10091         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10092     } else {
10093       // We only use half of V1 so map the usage down into the final blend mask.
10094       V1Blend = UseLoV1 ? LoV1 : HiV1;
10095       for (int i = 0; i < SplitNumElements; ++i)
10096         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
10097           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
10098     }
10099     if (UseLoV2 && UseHiV2) {
10100       V2Blend =
10101         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10102     } else {
10103       // We only use half of V2 so map the usage down into the final blend mask.
10104       V2Blend = UseLoV2 ? LoV2 : HiV2;
10105       for (int i = 0; i < SplitNumElements; ++i)
10106         if (BlendMask[i] >= SplitNumElements)
10107           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
10108     }
10109     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
10110   };
10111   SDValue Lo = HalfBlend(LoMask);
10112   SDValue Hi = HalfBlend(HiMask);
10113   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
10114 }
10115
10116 /// \brief Either split a vector in halves or decompose the shuffles and the
10117 /// blend.
10118 ///
10119 /// This is provided as a good fallback for many lowerings of non-single-input
10120 /// shuffles with more than one 128-bit lane. In those cases, we want to select
10121 /// between splitting the shuffle into 128-bit components and stitching those
10122 /// back together vs. extracting the single-input shuffles and blending those
10123 /// results.
10124 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
10125                                                 SDValue V2, ArrayRef<int> Mask,
10126                                                 SelectionDAG &DAG) {
10127   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
10128                                             "lower single-input shuffles as it "
10129                                             "could then recurse on itself.");
10130   int Size = Mask.size();
10131
10132   // If this can be modeled as a broadcast of two elements followed by a blend,
10133   // prefer that lowering. This is especially important because broadcasts can
10134   // often fold with memory operands.
10135   auto DoBothBroadcast = [&] {
10136     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
10137     for (int M : Mask)
10138       if (M >= Size) {
10139         if (V2BroadcastIdx == -1)
10140           V2BroadcastIdx = M - Size;
10141         else if (M - Size != V2BroadcastIdx)
10142           return false;
10143       } else if (M >= 0) {
10144         if (V1BroadcastIdx == -1)
10145           V1BroadcastIdx = M;
10146         else if (M != V1BroadcastIdx)
10147           return false;
10148       }
10149     return true;
10150   };
10151   if (DoBothBroadcast())
10152     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
10153                                                       DAG);
10154
10155   // If the inputs all stem from a single 128-bit lane of each input, then we
10156   // split them rather than blending because the split will decompose to
10157   // unusually few instructions.
10158   int LaneCount = VT.getSizeInBits() / 128;
10159   int LaneSize = Size / LaneCount;
10160   SmallBitVector LaneInputs[2];
10161   LaneInputs[0].resize(LaneCount, false);
10162   LaneInputs[1].resize(LaneCount, false);
10163   for (int i = 0; i < Size; ++i)
10164     if (Mask[i] >= 0)
10165       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
10166   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
10167     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10168
10169   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
10170   // that the decomposed single-input shuffles don't end up here.
10171   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10172 }
10173
10174 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
10175 /// a permutation and blend of those lanes.
10176 ///
10177 /// This essentially blends the out-of-lane inputs to each lane into the lane
10178 /// from a permuted copy of the vector. This lowering strategy results in four
10179 /// instructions in the worst case for a single-input cross lane shuffle which
10180 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
10181 /// of. Special cases for each particular shuffle pattern should be handled
10182 /// prior to trying this lowering.
10183 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
10184                                                        SDValue V1, SDValue V2,
10185                                                        ArrayRef<int> Mask,
10186                                                        SelectionDAG &DAG) {
10187   // FIXME: This should probably be generalized for 512-bit vectors as well.
10188   assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
10189   int LaneSize = Mask.size() / 2;
10190
10191   // If there are only inputs from one 128-bit lane, splitting will in fact be
10192   // less expensive. The flags track whether the given lane contains an element
10193   // that crosses to another lane.
10194   bool LaneCrossing[2] = {false, false};
10195   for (int i = 0, Size = Mask.size(); i < Size; ++i)
10196     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10197       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
10198   if (!LaneCrossing[0] || !LaneCrossing[1])
10199     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10200
10201   if (isSingleInputShuffleMask(Mask)) {
10202     SmallVector<int, 32> FlippedBlendMask;
10203     for (int i = 0, Size = Mask.size(); i < Size; ++i)
10204       FlippedBlendMask.push_back(
10205           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
10206                                   ? Mask[i]
10207                                   : Mask[i] % LaneSize +
10208                                         (i / LaneSize) * LaneSize + Size));
10209
10210     // Flip the vector, and blend the results which should now be in-lane. The
10211     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
10212     // 5 for the high source. The value 3 selects the high half of source 2 and
10213     // the value 2 selects the low half of source 2. We only use source 2 to
10214     // allow folding it into a memory operand.
10215     unsigned PERMMask = 3 | 2 << 4;
10216     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
10217                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
10218     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
10219   }
10220
10221   // This now reduces to two single-input shuffles of V1 and V2 which at worst
10222   // will be handled by the above logic and a blend of the results, much like
10223   // other patterns in AVX.
10224   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10225 }
10226
10227 /// \brief Handle lowering 2-lane 128-bit shuffles.
10228 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10229                                         SDValue V2, ArrayRef<int> Mask,
10230                                         const X86Subtarget *Subtarget,
10231                                         SelectionDAG &DAG) {
10232   // TODO: If minimizing size and one of the inputs is a zero vector and the
10233   // the zero vector has only one use, we could use a VPERM2X128 to save the
10234   // instruction bytes needed to explicitly generate the zero vector.
10235
10236   // Blends are faster and handle all the non-lane-crossing cases.
10237   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10238                                                 Subtarget, DAG))
10239     return Blend;
10240
10241   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
10242   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
10243
10244   // If either input operand is a zero vector, use VPERM2X128 because its mask
10245   // allows us to replace the zero input with an implicit zero.
10246   if (!IsV1Zero && !IsV2Zero) {
10247     // Check for patterns which can be matched with a single insert of a 128-bit
10248     // subvector.
10249     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
10250     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
10251       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10252                                    VT.getVectorNumElements() / 2);
10253       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10254                                 DAG.getIntPtrConstant(0, DL));
10255       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10256                                 OnlyUsesV1 ? V1 : V2,
10257                                 DAG.getIntPtrConstant(0, DL));
10258       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10259     }
10260   }
10261
10262   // Otherwise form a 128-bit permutation. After accounting for undefs,
10263   // convert the 64-bit shuffle mask selection values into 128-bit
10264   // selection bits by dividing the indexes by 2 and shifting into positions
10265   // defined by a vperm2*128 instruction's immediate control byte.
10266
10267   // The immediate permute control byte looks like this:
10268   //    [1:0] - select 128 bits from sources for low half of destination
10269   //    [2]   - ignore
10270   //    [3]   - zero low half of destination
10271   //    [5:4] - select 128 bits from sources for high half of destination
10272   //    [6]   - ignore
10273   //    [7]   - zero high half of destination
10274
10275   int MaskLO = Mask[0];
10276   if (MaskLO == SM_SentinelUndef)
10277     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10278
10279   int MaskHI = Mask[2];
10280   if (MaskHI == SM_SentinelUndef)
10281     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10282
10283   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10284
10285   // If either input is a zero vector, replace it with an undef input.
10286   // Shuffle mask values <  4 are selecting elements of V1.
10287   // Shuffle mask values >= 4 are selecting elements of V2.
10288   // Adjust each half of the permute mask by clearing the half that was
10289   // selecting the zero vector and setting the zero mask bit.
10290   if (IsV1Zero) {
10291     V1 = DAG.getUNDEF(VT);
10292     if (MaskLO < 4)
10293       PermMask = (PermMask & 0xf0) | 0x08;
10294     if (MaskHI < 4)
10295       PermMask = (PermMask & 0x0f) | 0x80;
10296   }
10297   if (IsV2Zero) {
10298     V2 = DAG.getUNDEF(VT);
10299     if (MaskLO >= 4)
10300       PermMask = (PermMask & 0xf0) | 0x08;
10301     if (MaskHI >= 4)
10302       PermMask = (PermMask & 0x0f) | 0x80;
10303   }
10304
10305   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10306                      DAG.getConstant(PermMask, DL, MVT::i8));
10307 }
10308
10309 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10310 /// shuffling each lane.
10311 ///
10312 /// This will only succeed when the result of fixing the 128-bit lanes results
10313 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10314 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10315 /// the lane crosses early and then use simpler shuffles within each lane.
10316 ///
10317 /// FIXME: It might be worthwhile at some point to support this without
10318 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10319 /// in x86 only floating point has interesting non-repeating shuffles, and even
10320 /// those are still *marginally* more expensive.
10321 static SDValue lowerVectorShuffleByMerging128BitLanes(
10322     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10323     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10324   assert(!isSingleInputShuffleMask(Mask) &&
10325          "This is only useful with multiple inputs.");
10326
10327   int Size = Mask.size();
10328   int LaneSize = 128 / VT.getScalarSizeInBits();
10329   int NumLanes = Size / LaneSize;
10330   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10331
10332   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10333   // check whether the in-128-bit lane shuffles share a repeating pattern.
10334   SmallVector<int, 4> Lanes;
10335   Lanes.resize(NumLanes, -1);
10336   SmallVector<int, 4> InLaneMask;
10337   InLaneMask.resize(LaneSize, -1);
10338   for (int i = 0; i < Size; ++i) {
10339     if (Mask[i] < 0)
10340       continue;
10341
10342     int j = i / LaneSize;
10343
10344     if (Lanes[j] < 0) {
10345       // First entry we've seen for this lane.
10346       Lanes[j] = Mask[i] / LaneSize;
10347     } else if (Lanes[j] != Mask[i] / LaneSize) {
10348       // This doesn't match the lane selected previously!
10349       return SDValue();
10350     }
10351
10352     // Check that within each lane we have a consistent shuffle mask.
10353     int k = i % LaneSize;
10354     if (InLaneMask[k] < 0) {
10355       InLaneMask[k] = Mask[i] % LaneSize;
10356     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10357       // This doesn't fit a repeating in-lane mask.
10358       return SDValue();
10359     }
10360   }
10361
10362   // First shuffle the lanes into place.
10363   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10364                                 VT.getSizeInBits() / 64);
10365   SmallVector<int, 8> LaneMask;
10366   LaneMask.resize(NumLanes * 2, -1);
10367   for (int i = 0; i < NumLanes; ++i)
10368     if (Lanes[i] >= 0) {
10369       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10370       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10371     }
10372
10373   V1 = DAG.getBitcast(LaneVT, V1);
10374   V2 = DAG.getBitcast(LaneVT, V2);
10375   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10376
10377   // Cast it back to the type we actually want.
10378   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10379
10380   // Now do a simple shuffle that isn't lane crossing.
10381   SmallVector<int, 8> NewMask;
10382   NewMask.resize(Size, -1);
10383   for (int i = 0; i < Size; ++i)
10384     if (Mask[i] >= 0)
10385       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10386   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10387          "Must not introduce lane crosses at this point!");
10388
10389   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10390 }
10391
10392 /// Lower shuffles where an entire half of a 256-bit vector is UNDEF.
10393 /// This allows for fast cases such as subvector extraction/insertion
10394 /// or shuffling smaller vector types which can lower more efficiently.
10395 static SDValue lowerVectorShuffleWithUndefHalf(SDLoc DL, MVT VT, SDValue V1,
10396                                                SDValue V2, ArrayRef<int> Mask,
10397                                                const X86Subtarget *Subtarget,
10398                                                SelectionDAG &DAG) {
10399   assert(VT.getSizeInBits() == 256 && "Expected 256-bit vector");
10400
10401   unsigned NumElts = VT.getVectorNumElements();
10402   unsigned HalfNumElts = NumElts / 2;
10403   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(), HalfNumElts);
10404
10405   bool UndefLower = isUndefInRange(Mask, 0, HalfNumElts);
10406   bool UndefUpper = isUndefInRange(Mask, HalfNumElts, HalfNumElts);
10407   if (!UndefLower && !UndefUpper)
10408     return SDValue();
10409
10410   // Upper half is undef and lower half is whole upper subvector.
10411   // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
10412   if (UndefUpper &&
10413       isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
10414     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10415                              DAG.getIntPtrConstant(HalfNumElts, DL));
10416     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10417                        DAG.getIntPtrConstant(0, DL));
10418   }
10419
10420   // Lower half is undef and upper half is whole lower subvector.
10421   // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
10422   if (UndefLower &&
10423       isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
10424     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10425                              DAG.getIntPtrConstant(0, DL));
10426     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10427                        DAG.getIntPtrConstant(HalfNumElts, DL));
10428   }
10429
10430   // AVX2 supports efficient immediate 64-bit element cross-lane shuffles.
10431   if (UndefLower && Subtarget->hasAVX2() &&
10432       (VT == MVT::v4f64 || VT == MVT::v4i64))
10433     return SDValue();
10434
10435   // If the shuffle only uses the lower halves of the input operands,
10436   // then extract them and perform the 'half' shuffle at half width.
10437   // e.g. vector_shuffle <X, X, X, X, u, u, u, u> or <X, X, u, u>
10438   int HalfIdx1 = -1, HalfIdx2 = -1;
10439   SmallVector<int, 8> HalfMask;
10440   unsigned Offset = UndefLower ? HalfNumElts : 0;
10441   for (unsigned i = 0; i != HalfNumElts; ++i) {
10442     int M = Mask[i + Offset];
10443     if (M < 0) {
10444       HalfMask.push_back(M);
10445       continue;
10446     }
10447
10448     // Determine which of the 4 half vectors this element is from.
10449     // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
10450     int HalfIdx = M / HalfNumElts;
10451
10452     // Only shuffle using the lower halves of the inputs.
10453     // TODO: Investigate usefulness of shuffling with upper halves.
10454     if (HalfIdx != 0 && HalfIdx != 2)
10455       return SDValue();
10456
10457     // Determine the element index into its half vector source.
10458     int HalfElt = M % HalfNumElts;
10459
10460     // We can shuffle with up to 2 half vectors, set the new 'half'
10461     // shuffle mask accordingly.
10462     if (-1 == HalfIdx1 || HalfIdx1 == HalfIdx) {
10463       HalfMask.push_back(HalfElt);
10464       HalfIdx1 = HalfIdx;
10465       continue;
10466     }
10467     if (-1 == HalfIdx2 || HalfIdx2 == HalfIdx) {
10468       HalfMask.push_back(HalfElt + HalfNumElts);
10469       HalfIdx2 = HalfIdx;
10470       continue;
10471     }
10472
10473     // Too many half vectors referenced.
10474     return SDValue();
10475   }
10476   assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
10477
10478   auto GetHalfVector = [&](int HalfIdx) {
10479     if (HalfIdx < 0)
10480       return DAG.getUNDEF(HalfVT);
10481     SDValue V = (HalfIdx < 2 ? V1 : V2);
10482     HalfIdx = (HalfIdx % 2) * HalfNumElts;
10483     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
10484                        DAG.getIntPtrConstant(HalfIdx, DL));
10485   };
10486
10487   SDValue Half1 = GetHalfVector(HalfIdx1);
10488   SDValue Half2 = GetHalfVector(HalfIdx2);
10489   SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
10490   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
10491                      DAG.getIntPtrConstant(Offset, DL));
10492 }
10493
10494 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10495 /// given mask.
10496 ///
10497 /// This returns true if the elements from a particular input are already in the
10498 /// slot required by the given mask and require no permutation.
10499 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10500   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10501   int Size = Mask.size();
10502   for (int i = 0; i < Size; ++i)
10503     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10504       return false;
10505
10506   return true;
10507 }
10508
10509 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10510                                             ArrayRef<int> Mask, SDValue V1,
10511                                             SDValue V2, SelectionDAG &DAG) {
10512
10513   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
10514   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
10515   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10516   int NumElts = VT.getVectorNumElements();
10517   bool ShufpdMask = true;
10518   bool CommutableMask = true;
10519   unsigned Immediate = 0;
10520   for (int i = 0; i < NumElts; ++i) {
10521     if (Mask[i] < 0)
10522       continue;
10523     int Val = (i & 6) + NumElts * (i & 1);
10524     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10525     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10526       ShufpdMask = false;
10527     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10528       CommutableMask = false;
10529     Immediate |= (Mask[i] % 2) << i;
10530   }
10531   if (ShufpdMask)
10532     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10533                        DAG.getConstant(Immediate, DL, MVT::i8));
10534   if (CommutableMask)
10535     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10536                        DAG.getConstant(Immediate, DL, MVT::i8));
10537   return SDValue();
10538 }
10539
10540 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10541 ///
10542 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10543 /// isn't available.
10544 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10545                                        const X86Subtarget *Subtarget,
10546                                        SelectionDAG &DAG) {
10547   SDLoc DL(Op);
10548   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10549   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10550   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10551   ArrayRef<int> Mask = SVOp->getMask();
10552   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10553
10554   SmallVector<int, 4> WidenedMask;
10555   if (canWidenShuffleElements(Mask, WidenedMask))
10556     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10557                                     DAG);
10558
10559   if (isSingleInputShuffleMask(Mask)) {
10560     // Check for being able to broadcast a single element.
10561     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10562                                                           Mask, Subtarget, DAG))
10563       return Broadcast;
10564
10565     // Use low duplicate instructions for masks that match their pattern.
10566     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10567       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10568
10569     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10570       // Non-half-crossing single input shuffles can be lowerid with an
10571       // interleaved permutation.
10572       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10573                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10574       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10575                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10576     }
10577
10578     // With AVX2 we have direct support for this permutation.
10579     if (Subtarget->hasAVX2())
10580       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10581                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10582
10583     // Otherwise, fall back.
10584     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10585                                                    DAG);
10586   }
10587
10588   // Use dedicated unpack instructions for masks that match their pattern.
10589   if (SDValue V =
10590           lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10591     return V;
10592
10593   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10594                                                 Subtarget, DAG))
10595     return Blend;
10596
10597   // Check if the blend happens to exactly fit that of SHUFPD.
10598   if (SDValue Op =
10599       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10600     return Op;
10601
10602   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10603   // shuffle. However, if we have AVX2 and either inputs are already in place,
10604   // we will be able to shuffle even across lanes the other input in a single
10605   // instruction so skip this pattern.
10606   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10607                                  isShuffleMaskInputInPlace(1, Mask))))
10608     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10609             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10610       return Result;
10611
10612   // If we have AVX2 then we always want to lower with a blend because an v4 we
10613   // can fully permute the elements.
10614   if (Subtarget->hasAVX2())
10615     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10616                                                       Mask, DAG);
10617
10618   // Otherwise fall back on generic lowering.
10619   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10620 }
10621
10622 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10623 ///
10624 /// This routine is only called when we have AVX2 and thus a reasonable
10625 /// instruction set for v4i64 shuffling..
10626 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10627                                        const X86Subtarget *Subtarget,
10628                                        SelectionDAG &DAG) {
10629   SDLoc DL(Op);
10630   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10631   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10632   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10633   ArrayRef<int> Mask = SVOp->getMask();
10634   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10635   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10636
10637   SmallVector<int, 4> WidenedMask;
10638   if (canWidenShuffleElements(Mask, WidenedMask))
10639     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10640                                     DAG);
10641
10642   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10643                                                 Subtarget, DAG))
10644     return Blend;
10645
10646   // Check for being able to broadcast a single element.
10647   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10648                                                         Mask, Subtarget, DAG))
10649     return Broadcast;
10650
10651   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10652   // use lower latency instructions that will operate on both 128-bit lanes.
10653   SmallVector<int, 2> RepeatedMask;
10654   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10655     if (isSingleInputShuffleMask(Mask)) {
10656       int PSHUFDMask[] = {-1, -1, -1, -1};
10657       for (int i = 0; i < 2; ++i)
10658         if (RepeatedMask[i] >= 0) {
10659           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10660           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10661         }
10662       return DAG.getBitcast(
10663           MVT::v4i64,
10664           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10665                       DAG.getBitcast(MVT::v8i32, V1),
10666                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10667     }
10668   }
10669
10670   // AVX2 provides a direct instruction for permuting a single input across
10671   // lanes.
10672   if (isSingleInputShuffleMask(Mask))
10673     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10674                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10675
10676   // Try to use shift instructions.
10677   if (SDValue Shift =
10678           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10679     return Shift;
10680
10681   // Use dedicated unpack instructions for masks that match their pattern.
10682   if (SDValue V =
10683           lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10684     return V;
10685
10686   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10687   // shuffle. However, if we have AVX2 and either inputs are already in place,
10688   // we will be able to shuffle even across lanes the other input in a single
10689   // instruction so skip this pattern.
10690   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10691                                  isShuffleMaskInputInPlace(1, Mask))))
10692     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10693             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10694       return Result;
10695
10696   // Otherwise fall back on generic blend lowering.
10697   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10698                                                     Mask, DAG);
10699 }
10700
10701 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10702 ///
10703 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10704 /// isn't available.
10705 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10706                                        const X86Subtarget *Subtarget,
10707                                        SelectionDAG &DAG) {
10708   SDLoc DL(Op);
10709   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10710   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10711   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10712   ArrayRef<int> Mask = SVOp->getMask();
10713   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10714
10715   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10716                                                 Subtarget, DAG))
10717     return Blend;
10718
10719   // Check for being able to broadcast a single element.
10720   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10721                                                         Mask, Subtarget, DAG))
10722     return Broadcast;
10723
10724   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10725   // options to efficiently lower the shuffle.
10726   SmallVector<int, 4> RepeatedMask;
10727   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10728     assert(RepeatedMask.size() == 4 &&
10729            "Repeated masks must be half the mask width!");
10730
10731     // Use even/odd duplicate instructions for masks that match their pattern.
10732     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10733       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10734     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10735       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10736
10737     if (isSingleInputShuffleMask(Mask))
10738       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10739                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10740
10741     // Use dedicated unpack instructions for masks that match their pattern.
10742     if (SDValue V =
10743             lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10744       return V;
10745
10746     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10747     // have already handled any direct blends. We also need to squash the
10748     // repeated mask into a simulated v4f32 mask.
10749     for (int i = 0; i < 4; ++i)
10750       if (RepeatedMask[i] >= 8)
10751         RepeatedMask[i] -= 4;
10752     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10753   }
10754
10755   // If we have a single input shuffle with different shuffle patterns in the
10756   // two 128-bit lanes use the variable mask to VPERMILPS.
10757   if (isSingleInputShuffleMask(Mask)) {
10758     SDValue VPermMask[8];
10759     for (int i = 0; i < 8; ++i)
10760       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10761                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10762     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10763       return DAG.getNode(
10764           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10765           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10766
10767     if (Subtarget->hasAVX2())
10768       return DAG.getNode(
10769           X86ISD::VPERMV, DL, MVT::v8f32,
10770           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10771
10772     // Otherwise, fall back.
10773     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10774                                                    DAG);
10775   }
10776
10777   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10778   // shuffle.
10779   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10780           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10781     return Result;
10782
10783   // If we have AVX2 then we always want to lower with a blend because at v8 we
10784   // can fully permute the elements.
10785   if (Subtarget->hasAVX2())
10786     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10787                                                       Mask, DAG);
10788
10789   // Otherwise fall back on generic lowering.
10790   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10791 }
10792
10793 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10794 ///
10795 /// This routine is only called when we have AVX2 and thus a reasonable
10796 /// instruction set for v8i32 shuffling..
10797 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10798                                        const X86Subtarget *Subtarget,
10799                                        SelectionDAG &DAG) {
10800   SDLoc DL(Op);
10801   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10802   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10803   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10804   ArrayRef<int> Mask = SVOp->getMask();
10805   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10806   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10807
10808   // Whenever we can lower this as a zext, that instruction is strictly faster
10809   // than any alternative. It also allows us to fold memory operands into the
10810   // shuffle in many cases.
10811   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10812                                                          Mask, Subtarget, DAG))
10813     return ZExt;
10814
10815   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10816                                                 Subtarget, DAG))
10817     return Blend;
10818
10819   // Check for being able to broadcast a single element.
10820   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10821                                                         Mask, Subtarget, DAG))
10822     return Broadcast;
10823
10824   // If the shuffle mask is repeated in each 128-bit lane we can use more
10825   // efficient instructions that mirror the shuffles across the two 128-bit
10826   // lanes.
10827   SmallVector<int, 4> RepeatedMask;
10828   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10829     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10830     if (isSingleInputShuffleMask(Mask))
10831       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10832                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10833
10834     // Use dedicated unpack instructions for masks that match their pattern.
10835     if (SDValue V =
10836             lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10837       return V;
10838   }
10839
10840   // Try to use shift instructions.
10841   if (SDValue Shift =
10842           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10843     return Shift;
10844
10845   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10846           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10847     return Rotate;
10848
10849   // If the shuffle patterns aren't repeated but it is a single input, directly
10850   // generate a cross-lane VPERMD instruction.
10851   if (isSingleInputShuffleMask(Mask)) {
10852     SDValue VPermMask[8];
10853     for (int i = 0; i < 8; ++i)
10854       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10855                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10856     return DAG.getNode(
10857         X86ISD::VPERMV, DL, MVT::v8i32,
10858         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10859   }
10860
10861   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10862   // shuffle.
10863   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10864           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10865     return Result;
10866
10867   // Otherwise fall back on generic blend lowering.
10868   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10869                                                     Mask, DAG);
10870 }
10871
10872 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10873 ///
10874 /// This routine is only called when we have AVX2 and thus a reasonable
10875 /// instruction set for v16i16 shuffling..
10876 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10877                                         const X86Subtarget *Subtarget,
10878                                         SelectionDAG &DAG) {
10879   SDLoc DL(Op);
10880   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10881   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10882   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10883   ArrayRef<int> Mask = SVOp->getMask();
10884   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10885   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10886
10887   // Whenever we can lower this as a zext, that instruction is strictly faster
10888   // than any alternative. It also allows us to fold memory operands into the
10889   // shuffle in many cases.
10890   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10891                                                          Mask, Subtarget, DAG))
10892     return ZExt;
10893
10894   // Check for being able to broadcast a single element.
10895   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10896                                                         Mask, Subtarget, DAG))
10897     return Broadcast;
10898
10899   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10900                                                 Subtarget, DAG))
10901     return Blend;
10902
10903   // Use dedicated unpack instructions for masks that match their pattern.
10904   if (SDValue V =
10905           lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10906     return V;
10907
10908   // Try to use shift instructions.
10909   if (SDValue Shift =
10910           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10911     return Shift;
10912
10913   // Try to use byte rotation instructions.
10914   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10915           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10916     return Rotate;
10917
10918   if (isSingleInputShuffleMask(Mask)) {
10919     // There are no generalized cross-lane shuffle operations available on i16
10920     // element types.
10921     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10922       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10923                                                      Mask, DAG);
10924
10925     SmallVector<int, 8> RepeatedMask;
10926     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10927       // As this is a single-input shuffle, the repeated mask should be
10928       // a strictly valid v8i16 mask that we can pass through to the v8i16
10929       // lowering to handle even the v16 case.
10930       return lowerV8I16GeneralSingleInputVectorShuffle(
10931           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10932     }
10933
10934     SDValue PSHUFBMask[32];
10935     for (int i = 0; i < 16; ++i) {
10936       if (Mask[i] == -1) {
10937         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10938         continue;
10939       }
10940
10941       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10942       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10943       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10944       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10945     }
10946     return DAG.getBitcast(MVT::v16i16,
10947                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10948                                       DAG.getBitcast(MVT::v32i8, V1),
10949                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10950                                                   MVT::v32i8, PSHUFBMask)));
10951   }
10952
10953   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10954   // shuffle.
10955   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10956           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10957     return Result;
10958
10959   // Otherwise fall back on generic lowering.
10960   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10961 }
10962
10963 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10964 ///
10965 /// This routine is only called when we have AVX2 and thus a reasonable
10966 /// instruction set for v32i8 shuffling..
10967 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10968                                        const X86Subtarget *Subtarget,
10969                                        SelectionDAG &DAG) {
10970   SDLoc DL(Op);
10971   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10972   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10973   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10974   ArrayRef<int> Mask = SVOp->getMask();
10975   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10976   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10977
10978   // Whenever we can lower this as a zext, that instruction is strictly faster
10979   // than any alternative. It also allows us to fold memory operands into the
10980   // shuffle in many cases.
10981   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10982                                                          Mask, Subtarget, DAG))
10983     return ZExt;
10984
10985   // Check for being able to broadcast a single element.
10986   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10987                                                         Mask, Subtarget, DAG))
10988     return Broadcast;
10989
10990   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10991                                                 Subtarget, DAG))
10992     return Blend;
10993
10994   // Use dedicated unpack instructions for masks that match their pattern.
10995   if (SDValue V =
10996           lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
10997     return V;
10998
10999   // Try to use shift instructions.
11000   if (SDValue Shift =
11001           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
11002     return Shift;
11003
11004   // Try to use byte rotation instructions.
11005   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
11006           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11007     return Rotate;
11008
11009   if (isSingleInputShuffleMask(Mask)) {
11010     // There are no generalized cross-lane shuffle operations available on i8
11011     // element types.
11012     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
11013       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
11014                                                      Mask, DAG);
11015
11016     SDValue PSHUFBMask[32];
11017     for (int i = 0; i < 32; ++i)
11018       PSHUFBMask[i] =
11019           Mask[i] < 0
11020               ? DAG.getUNDEF(MVT::i8)
11021               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
11022                                 MVT::i8);
11023
11024     return DAG.getNode(
11025         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
11026         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
11027   }
11028
11029   // Try to simplify this by merging 128-bit lanes to enable a lane-based
11030   // shuffle.
11031   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
11032           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11033     return Result;
11034
11035   // Otherwise fall back on generic lowering.
11036   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
11037 }
11038
11039 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
11040 ///
11041 /// This routine either breaks down the specific type of a 256-bit x86 vector
11042 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
11043 /// together based on the available instructions.
11044 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11045                                         MVT VT, const X86Subtarget *Subtarget,
11046                                         SelectionDAG &DAG) {
11047   SDLoc DL(Op);
11048   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11049   ArrayRef<int> Mask = SVOp->getMask();
11050
11051   // If we have a single input to the zero element, insert that into V1 if we
11052   // can do so cheaply.
11053   int NumElts = VT.getVectorNumElements();
11054   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
11055     return M >= NumElts;
11056   });
11057
11058   if (NumV2Elements == 1 && Mask[0] >= NumElts)
11059     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
11060                               DL, VT, V1, V2, Mask, Subtarget, DAG))
11061       return Insertion;
11062
11063   // Handle special cases where the lower or upper half is UNDEF.
11064   if (SDValue V =
11065           lowerVectorShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
11066     return V;
11067
11068   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
11069   // can check for those subtargets here and avoid much of the subtarget
11070   // querying in the per-vector-type lowering routines. With AVX1 we have
11071   // essentially *zero* ability to manipulate a 256-bit vector with integer
11072   // types. Since we'll use floating point types there eventually, just
11073   // immediately cast everything to a float and operate entirely in that domain.
11074   if (VT.isInteger() && !Subtarget->hasAVX2()) {
11075     int ElementBits = VT.getScalarSizeInBits();
11076     if (ElementBits < 32)
11077       // No floating point type available, decompose into 128-bit vectors.
11078       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11079
11080     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
11081                                 VT.getVectorNumElements());
11082     V1 = DAG.getBitcast(FpVT, V1);
11083     V2 = DAG.getBitcast(FpVT, V2);
11084     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
11085   }
11086
11087   switch (VT.SimpleTy) {
11088   case MVT::v4f64:
11089     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11090   case MVT::v4i64:
11091     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11092   case MVT::v8f32:
11093     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11094   case MVT::v8i32:
11095     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11096   case MVT::v16i16:
11097     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11098   case MVT::v32i8:
11099     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11100
11101   default:
11102     llvm_unreachable("Not a valid 256-bit x86 vector type!");
11103   }
11104 }
11105
11106 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
11107 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
11108                                         ArrayRef<int> Mask,
11109                                         SDValue V1, SDValue V2,
11110                                         SelectionDAG &DAG) {
11111   assert(VT.getScalarSizeInBits() == 64 &&
11112          "Unexpected element type size for 128bit shuffle.");
11113
11114   // To handle 256 bit vector requires VLX and most probably
11115   // function lowerV2X128VectorShuffle() is better solution.
11116   assert(VT.is512BitVector() && "Unexpected vector size for 128bit shuffle.");
11117
11118   SmallVector<int, 4> WidenedMask;
11119   if (!canWidenShuffleElements(Mask, WidenedMask))
11120     return SDValue();
11121
11122   // Form a 128-bit permutation.
11123   // Convert the 64-bit shuffle mask selection values into 128-bit selection
11124   // bits defined by a vshuf64x2 instruction's immediate control byte.
11125   unsigned PermMask = 0, Imm = 0;
11126   unsigned ControlBitsNum = WidenedMask.size() / 2;
11127
11128   for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
11129     if (WidenedMask[i] == SM_SentinelZero)
11130       return SDValue();
11131
11132     // Use first element in place of undef mask.
11133     Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
11134     PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
11135   }
11136
11137   return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
11138                      DAG.getConstant(PermMask, DL, MVT::i8));
11139 }
11140
11141 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
11142                                            ArrayRef<int> Mask, SDValue V1,
11143                                            SDValue V2, SelectionDAG &DAG) {
11144
11145   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
11146
11147   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
11148   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
11149
11150   SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
11151   if (isSingleInputShuffleMask(Mask))
11152     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
11153
11154   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
11155 }
11156
11157 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
11158 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11159                                        const X86Subtarget *Subtarget,
11160                                        SelectionDAG &DAG) {
11161   SDLoc DL(Op);
11162   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11163   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11164   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11165   ArrayRef<int> Mask = SVOp->getMask();
11166   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11167
11168   if (SDValue Shuf128 =
11169           lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
11170     return Shuf128;
11171
11172   if (SDValue Unpck =
11173           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
11174     return Unpck;
11175
11176   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
11177 }
11178
11179 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
11180 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11181                                         const X86Subtarget *Subtarget,
11182                                         SelectionDAG &DAG) {
11183   SDLoc DL(Op);
11184   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11185   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11186   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11187   ArrayRef<int> Mask = SVOp->getMask();
11188   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11189
11190   if (SDValue Unpck =
11191           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
11192     return Unpck;
11193
11194   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
11195 }
11196
11197 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
11198 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11199                                        const X86Subtarget *Subtarget,
11200                                        SelectionDAG &DAG) {
11201   SDLoc DL(Op);
11202   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11203   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11204   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11205   ArrayRef<int> Mask = SVOp->getMask();
11206   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11207
11208   if (SDValue Shuf128 =
11209           lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
11210     return Shuf128;
11211
11212   if (SDValue Unpck =
11213           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
11214     return Unpck;
11215
11216   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
11217 }
11218
11219 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
11220 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11221                                         const X86Subtarget *Subtarget,
11222                                         SelectionDAG &DAG) {
11223   SDLoc DL(Op);
11224   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11225   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11226   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11227   ArrayRef<int> Mask = SVOp->getMask();
11228   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11229
11230   if (SDValue Unpck =
11231           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
11232     return Unpck;
11233
11234   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
11235 }
11236
11237 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
11238 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11239                                         const X86Subtarget *Subtarget,
11240                                         SelectionDAG &DAG) {
11241   SDLoc DL(Op);
11242   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11243   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11244   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11245   ArrayRef<int> Mask = SVOp->getMask();
11246   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11247   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
11248
11249   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
11250 }
11251
11252 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
11253 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11254                                        const X86Subtarget *Subtarget,
11255                                        SelectionDAG &DAG) {
11256   SDLoc DL(Op);
11257   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11258   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11259   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11260   ArrayRef<int> Mask = SVOp->getMask();
11261   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
11262   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
11263
11264   // FIXME: Implement direct support for this type!
11265   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
11266 }
11267
11268 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
11269 ///
11270 /// This routine either breaks down the specific type of a 512-bit x86 vector
11271 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
11272 /// together based on the available instructions.
11273 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11274                                         MVT VT, const X86Subtarget *Subtarget,
11275                                         SelectionDAG &DAG) {
11276   SDLoc DL(Op);
11277   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11278   ArrayRef<int> Mask = SVOp->getMask();
11279   assert(Subtarget->hasAVX512() &&
11280          "Cannot lower 512-bit vectors w/ basic ISA!");
11281
11282   // Check for being able to broadcast a single element.
11283   if (SDValue Broadcast =
11284           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
11285     return Broadcast;
11286
11287   // Dispatch to each element type for lowering. If we don't have supprot for
11288   // specific element type shuffles at 512 bits, immediately split them and
11289   // lower them. Each lowering routine of a given type is allowed to assume that
11290   // the requisite ISA extensions for that element type are available.
11291   switch (VT.SimpleTy) {
11292   case MVT::v8f64:
11293     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11294   case MVT::v16f32:
11295     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11296   case MVT::v8i64:
11297     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11298   case MVT::v16i32:
11299     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11300   case MVT::v32i16:
11301     if (Subtarget->hasBWI())
11302       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11303     break;
11304   case MVT::v64i8:
11305     if (Subtarget->hasBWI())
11306       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11307     break;
11308
11309   default:
11310     llvm_unreachable("Not a valid 512-bit x86 vector type!");
11311   }
11312
11313   // Otherwise fall back on splitting.
11314   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11315 }
11316
11317 // Lower vXi1 vector shuffles.
11318 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
11319 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
11320 // vector, shuffle and then truncate it back.
11321 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11322                                       MVT VT, const X86Subtarget *Subtarget,
11323                                       SelectionDAG &DAG) {
11324   SDLoc DL(Op);
11325   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11326   ArrayRef<int> Mask = SVOp->getMask();
11327   assert(Subtarget->hasAVX512() &&
11328          "Cannot lower 512-bit vectors w/o basic ISA!");
11329   MVT ExtVT;
11330   switch (VT.SimpleTy) {
11331   default:
11332     llvm_unreachable("Expected a vector of i1 elements");
11333   case MVT::v2i1:
11334     ExtVT = MVT::v2i64;
11335     break;
11336   case MVT::v4i1:
11337     ExtVT = MVT::v4i32;
11338     break;
11339   case MVT::v8i1:
11340     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
11341     break;
11342   case MVT::v16i1:
11343     ExtVT = MVT::v16i32;
11344     break;
11345   case MVT::v32i1:
11346     ExtVT = MVT::v32i16;
11347     break;
11348   case MVT::v64i1:
11349     ExtVT = MVT::v64i8;
11350     break;
11351   }
11352
11353   if (ISD::isBuildVectorAllZeros(V1.getNode()))
11354     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11355   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
11356     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11357   else
11358     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
11359
11360   if (V2.isUndef())
11361     V2 = DAG.getUNDEF(ExtVT);
11362   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
11363     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11364   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
11365     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11366   else
11367     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11368   return DAG.getNode(ISD::TRUNCATE, DL, VT,
11369                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11370 }
11371 /// \brief Top-level lowering for x86 vector shuffles.
11372 ///
11373 /// This handles decomposition, canonicalization, and lowering of all x86
11374 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11375 /// above in helper routines. The canonicalization attempts to widen shuffles
11376 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11377 /// s.t. only one of the two inputs needs to be tested, etc.
11378 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11379                                   SelectionDAG &DAG) {
11380   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11381   ArrayRef<int> Mask = SVOp->getMask();
11382   SDValue V1 = Op.getOperand(0);
11383   SDValue V2 = Op.getOperand(1);
11384   MVT VT = Op.getSimpleValueType();
11385   int NumElements = VT.getVectorNumElements();
11386   SDLoc dl(Op);
11387   bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
11388
11389   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11390          "Can't lower MMX shuffles");
11391
11392   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11393   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11394   if (V1IsUndef && V2IsUndef)
11395     return DAG.getUNDEF(VT);
11396
11397   // When we create a shuffle node we put the UNDEF node to second operand,
11398   // but in some cases the first operand may be transformed to UNDEF.
11399   // In this case we should just commute the node.
11400   if (V1IsUndef)
11401     return DAG.getCommutedVectorShuffle(*SVOp);
11402
11403   // Check for non-undef masks pointing at an undef vector and make the masks
11404   // undef as well. This makes it easier to match the shuffle based solely on
11405   // the mask.
11406   if (V2IsUndef)
11407     for (int M : Mask)
11408       if (M >= NumElements) {
11409         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11410         for (int &M : NewMask)
11411           if (M >= NumElements)
11412             M = -1;
11413         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11414       }
11415
11416   // We actually see shuffles that are entirely re-arrangements of a set of
11417   // zero inputs. This mostly happens while decomposing complex shuffles into
11418   // simple ones. Directly lower these as a buildvector of zeros.
11419   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11420   if (Zeroable.all())
11421     return getZeroVector(VT, Subtarget, DAG, dl);
11422
11423   // Try to collapse shuffles into using a vector type with fewer elements but
11424   // wider element types. We cap this to not form integers or floating point
11425   // elements wider than 64 bits, but it might be interesting to form i128
11426   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11427   SmallVector<int, 16> WidenedMask;
11428   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11429       canWidenShuffleElements(Mask, WidenedMask)) {
11430     MVT NewEltVT = VT.isFloatingPoint()
11431                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11432                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11433     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11434     // Make sure that the new vector type is legal. For example, v2f64 isn't
11435     // legal on SSE1.
11436     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11437       V1 = DAG.getBitcast(NewVT, V1);
11438       V2 = DAG.getBitcast(NewVT, V2);
11439       return DAG.getBitcast(
11440           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11441     }
11442   }
11443
11444   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11445   for (int M : SVOp->getMask())
11446     if (M < 0)
11447       ++NumUndefElements;
11448     else if (M < NumElements)
11449       ++NumV1Elements;
11450     else
11451       ++NumV2Elements;
11452
11453   // Commute the shuffle as needed such that more elements come from V1 than
11454   // V2. This allows us to match the shuffle pattern strictly on how many
11455   // elements come from V1 without handling the symmetric cases.
11456   if (NumV2Elements > NumV1Elements)
11457     return DAG.getCommutedVectorShuffle(*SVOp);
11458
11459   // When the number of V1 and V2 elements are the same, try to minimize the
11460   // number of uses of V2 in the low half of the vector. When that is tied,
11461   // ensure that the sum of indices for V1 is equal to or lower than the sum
11462   // indices for V2. When those are equal, try to ensure that the number of odd
11463   // indices for V1 is lower than the number of odd indices for V2.
11464   if (NumV1Elements == NumV2Elements) {
11465     int LowV1Elements = 0, LowV2Elements = 0;
11466     for (int M : SVOp->getMask().slice(0, NumElements / 2))
11467       if (M >= NumElements)
11468         ++LowV2Elements;
11469       else if (M >= 0)
11470         ++LowV1Elements;
11471     if (LowV2Elements > LowV1Elements) {
11472       return DAG.getCommutedVectorShuffle(*SVOp);
11473     } else if (LowV2Elements == LowV1Elements) {
11474       int SumV1Indices = 0, SumV2Indices = 0;
11475       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11476         if (SVOp->getMask()[i] >= NumElements)
11477           SumV2Indices += i;
11478         else if (SVOp->getMask()[i] >= 0)
11479           SumV1Indices += i;
11480       if (SumV2Indices < SumV1Indices) {
11481         return DAG.getCommutedVectorShuffle(*SVOp);
11482       } else if (SumV2Indices == SumV1Indices) {
11483         int NumV1OddIndices = 0, NumV2OddIndices = 0;
11484         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11485           if (SVOp->getMask()[i] >= NumElements)
11486             NumV2OddIndices += i % 2;
11487           else if (SVOp->getMask()[i] >= 0)
11488             NumV1OddIndices += i % 2;
11489         if (NumV2OddIndices < NumV1OddIndices)
11490           return DAG.getCommutedVectorShuffle(*SVOp);
11491       }
11492     }
11493   }
11494
11495   // For each vector width, delegate to a specialized lowering routine.
11496   if (VT.is128BitVector())
11497     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11498
11499   if (VT.is256BitVector())
11500     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11501
11502   if (VT.is512BitVector())
11503     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11504
11505   if (Is1BitVector)
11506     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11507   llvm_unreachable("Unimplemented!");
11508 }
11509
11510 // This function assumes its argument is a BUILD_VECTOR of constants or
11511 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11512 // true.
11513 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11514                                     unsigned &MaskValue) {
11515   MaskValue = 0;
11516   unsigned NumElems = BuildVector->getNumOperands();
11517
11518   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11519   // We don't handle the >2 lanes case right now.
11520   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11521   if (NumLanes > 2)
11522     return false;
11523
11524   unsigned NumElemsInLane = NumElems / NumLanes;
11525
11526   // Blend for v16i16 should be symmetric for the both lanes.
11527   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11528     SDValue EltCond = BuildVector->getOperand(i);
11529     SDValue SndLaneEltCond =
11530         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11531
11532     int Lane1Cond = -1, Lane2Cond = -1;
11533     if (isa<ConstantSDNode>(EltCond))
11534       Lane1Cond = !isNullConstant(EltCond);
11535     if (isa<ConstantSDNode>(SndLaneEltCond))
11536       Lane2Cond = !isNullConstant(SndLaneEltCond);
11537
11538     unsigned LaneMask = 0;
11539     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11540       // Lane1Cond != 0, means we want the first argument.
11541       // Lane1Cond == 0, means we want the second argument.
11542       // The encoding of this argument is 0 for the first argument, 1
11543       // for the second. Therefore, invert the condition.
11544       LaneMask = !Lane1Cond << i;
11545     else if (Lane1Cond < 0)
11546       LaneMask = !Lane2Cond << i;
11547     else
11548       return false;
11549
11550     MaskValue |= LaneMask;
11551     if (NumLanes == 2)
11552       MaskValue |= LaneMask << NumElemsInLane;
11553   }
11554   return true;
11555 }
11556
11557 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11558 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11559                                            const X86Subtarget *Subtarget,
11560                                            SelectionDAG &DAG) {
11561   SDValue Cond = Op.getOperand(0);
11562   SDValue LHS = Op.getOperand(1);
11563   SDValue RHS = Op.getOperand(2);
11564   SDLoc dl(Op);
11565   MVT VT = Op.getSimpleValueType();
11566
11567   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11568     return SDValue();
11569   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11570
11571   // Only non-legal VSELECTs reach this lowering, convert those into generic
11572   // shuffles and re-use the shuffle lowering path for blends.
11573   SmallVector<int, 32> Mask;
11574   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11575     SDValue CondElt = CondBV->getOperand(i);
11576     Mask.push_back(
11577         isa<ConstantSDNode>(CondElt) ? i + (isNullConstant(CondElt) ? Size : 0)
11578                                      : -1);
11579   }
11580   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11581 }
11582
11583 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11584   // A vselect where all conditions and data are constants can be optimized into
11585   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11586   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11587       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11588       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11589     return SDValue();
11590
11591   // Try to lower this to a blend-style vector shuffle. This can handle all
11592   // constant condition cases.
11593   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11594     return BlendOp;
11595
11596   // Variable blends are only legal from SSE4.1 onward.
11597   if (!Subtarget->hasSSE41())
11598     return SDValue();
11599
11600   // Only some types will be legal on some subtargets. If we can emit a legal
11601   // VSELECT-matching blend, return Op, and but if we need to expand, return
11602   // a null value.
11603   switch (Op.getSimpleValueType().SimpleTy) {
11604   default:
11605     // Most of the vector types have blends past SSE4.1.
11606     return Op;
11607
11608   case MVT::v32i8:
11609     // The byte blends for AVX vectors were introduced only in AVX2.
11610     if (Subtarget->hasAVX2())
11611       return Op;
11612
11613     return SDValue();
11614
11615   case MVT::v8i16:
11616   case MVT::v16i16:
11617     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11618     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11619       return Op;
11620
11621     // FIXME: We should custom lower this by fixing the condition and using i8
11622     // blends.
11623     return SDValue();
11624   }
11625 }
11626
11627 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11628   MVT VT = Op.getSimpleValueType();
11629   SDLoc dl(Op);
11630
11631   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11632     return SDValue();
11633
11634   if (VT.getSizeInBits() == 8) {
11635     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11636                                   Op.getOperand(0), Op.getOperand(1));
11637     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11638                                   DAG.getValueType(VT));
11639     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11640   }
11641
11642   if (VT.getSizeInBits() == 16) {
11643     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11644     if (isNullConstant(Op.getOperand(1)))
11645       return DAG.getNode(
11646           ISD::TRUNCATE, dl, MVT::i16,
11647           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11648                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11649                       Op.getOperand(1)));
11650     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11651                                   Op.getOperand(0), Op.getOperand(1));
11652     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11653                                   DAG.getValueType(VT));
11654     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11655   }
11656
11657   if (VT == MVT::f32) {
11658     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11659     // the result back to FR32 register. It's only worth matching if the
11660     // result has a single use which is a store or a bitcast to i32.  And in
11661     // the case of a store, it's not worth it if the index is a constant 0,
11662     // because a MOVSSmr can be used instead, which is smaller and faster.
11663     if (!Op.hasOneUse())
11664       return SDValue();
11665     SDNode *User = *Op.getNode()->use_begin();
11666     if ((User->getOpcode() != ISD::STORE ||
11667          isNullConstant(Op.getOperand(1))) &&
11668         (User->getOpcode() != ISD::BITCAST ||
11669          User->getValueType(0) != MVT::i32))
11670       return SDValue();
11671     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11672                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11673                                   Op.getOperand(1));
11674     return DAG.getBitcast(MVT::f32, Extract);
11675   }
11676
11677   if (VT == MVT::i32 || VT == MVT::i64) {
11678     // ExtractPS/pextrq works with constant index.
11679     if (isa<ConstantSDNode>(Op.getOperand(1)))
11680       return Op;
11681   }
11682   return SDValue();
11683 }
11684
11685 /// Extract one bit from mask vector, like v16i1 or v8i1.
11686 /// AVX-512 feature.
11687 SDValue
11688 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11689   SDValue Vec = Op.getOperand(0);
11690   SDLoc dl(Vec);
11691   MVT VecVT = Vec.getSimpleValueType();
11692   SDValue Idx = Op.getOperand(1);
11693   MVT EltVT = Op.getSimpleValueType();
11694
11695   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11696   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11697          "Unexpected vector type in ExtractBitFromMaskVector");
11698
11699   // variable index can't be handled in mask registers,
11700   // extend vector to VR512
11701   if (!isa<ConstantSDNode>(Idx)) {
11702     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11703     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11704     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11705                               ExtVT.getVectorElementType(), Ext, Idx);
11706     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11707   }
11708
11709   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11710   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11711   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11712     rc = getRegClassFor(MVT::v16i1);
11713   unsigned MaxSift = rc->getSize()*8 - 1;
11714   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11715                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11716   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11717                     DAG.getConstant(MaxSift, dl, MVT::i8));
11718   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11719                        DAG.getIntPtrConstant(0, dl));
11720 }
11721
11722 SDValue
11723 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11724                                            SelectionDAG &DAG) const {
11725   SDLoc dl(Op);
11726   SDValue Vec = Op.getOperand(0);
11727   MVT VecVT = Vec.getSimpleValueType();
11728   SDValue Idx = Op.getOperand(1);
11729
11730   if (Op.getSimpleValueType() == MVT::i1)
11731     return ExtractBitFromMaskVector(Op, DAG);
11732
11733   if (!isa<ConstantSDNode>(Idx)) {
11734     if (VecVT.is512BitVector() ||
11735         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11736          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11737
11738       MVT MaskEltVT =
11739         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11740       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11741                                     MaskEltVT.getSizeInBits());
11742
11743       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11744       auto PtrVT = getPointerTy(DAG.getDataLayout());
11745       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11746                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11747                                  DAG.getConstant(0, dl, PtrVT));
11748       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11749       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11750                          DAG.getConstant(0, dl, PtrVT));
11751     }
11752     return SDValue();
11753   }
11754
11755   // If this is a 256-bit vector result, first extract the 128-bit vector and
11756   // then extract the element from the 128-bit vector.
11757   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11758
11759     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11760     // Get the 128-bit vector.
11761     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11762     MVT EltVT = VecVT.getVectorElementType();
11763
11764     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11765     assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
11766
11767     // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
11768     // this can be done with a mask.
11769     IdxVal &= ElemsPerChunk - 1;
11770     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11771                        DAG.getConstant(IdxVal, dl, MVT::i32));
11772   }
11773
11774   assert(VecVT.is128BitVector() && "Unexpected vector length");
11775
11776   if (Subtarget->hasSSE41())
11777     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11778       return Res;
11779
11780   MVT VT = Op.getSimpleValueType();
11781   // TODO: handle v16i8.
11782   if (VT.getSizeInBits() == 16) {
11783     SDValue Vec = Op.getOperand(0);
11784     if (isNullConstant(Op.getOperand(1)))
11785       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11786                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11787                                      DAG.getBitcast(MVT::v4i32, Vec),
11788                                      Op.getOperand(1)));
11789     // Transform it so it match pextrw which produces a 32-bit result.
11790     MVT EltVT = MVT::i32;
11791     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11792                                   Op.getOperand(0), Op.getOperand(1));
11793     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11794                                   DAG.getValueType(VT));
11795     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11796   }
11797
11798   if (VT.getSizeInBits() == 32) {
11799     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11800     if (Idx == 0)
11801       return Op;
11802
11803     // SHUFPS the element to the lowest double word, then movss.
11804     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11805     MVT VVT = Op.getOperand(0).getSimpleValueType();
11806     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11807                                        DAG.getUNDEF(VVT), Mask);
11808     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11809                        DAG.getIntPtrConstant(0, dl));
11810   }
11811
11812   if (VT.getSizeInBits() == 64) {
11813     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11814     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11815     //        to match extract_elt for f64.
11816     if (isNullConstant(Op.getOperand(1)))
11817       return Op;
11818
11819     // UNPCKHPD the element to the lowest double word, then movsd.
11820     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11821     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11822     int Mask[2] = { 1, -1 };
11823     MVT VVT = Op.getOperand(0).getSimpleValueType();
11824     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11825                                        DAG.getUNDEF(VVT), Mask);
11826     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11827                        DAG.getIntPtrConstant(0, dl));
11828   }
11829
11830   return SDValue();
11831 }
11832
11833 /// Insert one bit to mask vector, like v16i1 or v8i1.
11834 /// AVX-512 feature.
11835 SDValue
11836 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11837   SDLoc dl(Op);
11838   SDValue Vec = Op.getOperand(0);
11839   SDValue Elt = Op.getOperand(1);
11840   SDValue Idx = Op.getOperand(2);
11841   MVT VecVT = Vec.getSimpleValueType();
11842
11843   if (!isa<ConstantSDNode>(Idx)) {
11844     // Non constant index. Extend source and destination,
11845     // insert element and then truncate the result.
11846     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11847     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11848     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11849       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11850       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11851     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11852   }
11853
11854   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11855   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11856   if (IdxVal)
11857     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11858                            DAG.getConstant(IdxVal, dl, MVT::i8));
11859   if (Vec.getOpcode() == ISD::UNDEF)
11860     return EltInVec;
11861   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11862 }
11863
11864 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11865                                                   SelectionDAG &DAG) const {
11866   MVT VT = Op.getSimpleValueType();
11867   MVT EltVT = VT.getVectorElementType();
11868
11869   if (EltVT == MVT::i1)
11870     return InsertBitToMaskVector(Op, DAG);
11871
11872   SDLoc dl(Op);
11873   SDValue N0 = Op.getOperand(0);
11874   SDValue N1 = Op.getOperand(1);
11875   SDValue N2 = Op.getOperand(2);
11876   if (!isa<ConstantSDNode>(N2))
11877     return SDValue();
11878   auto *N2C = cast<ConstantSDNode>(N2);
11879   unsigned IdxVal = N2C->getZExtValue();
11880
11881   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11882   // into that, and then insert the subvector back into the result.
11883   if (VT.is256BitVector() || VT.is512BitVector()) {
11884     // With a 256-bit vector, we can insert into the zero element efficiently
11885     // using a blend if we have AVX or AVX2 and the right data type.
11886     if (VT.is256BitVector() && IdxVal == 0) {
11887       // TODO: It is worthwhile to cast integer to floating point and back
11888       // and incur a domain crossing penalty if that's what we'll end up
11889       // doing anyway after extracting to a 128-bit vector.
11890       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11891           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11892         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11893         N2 = DAG.getIntPtrConstant(1, dl);
11894         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11895       }
11896     }
11897
11898     // Get the desired 128-bit vector chunk.
11899     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11900
11901     // Insert the element into the desired chunk.
11902     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11903     assert(isPowerOf2_32(NumEltsIn128));
11904     // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
11905     unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
11906
11907     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11908                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11909
11910     // Insert the changed part back into the bigger vector
11911     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11912   }
11913   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11914
11915   if (Subtarget->hasSSE41()) {
11916     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11917       unsigned Opc;
11918       if (VT == MVT::v8i16) {
11919         Opc = X86ISD::PINSRW;
11920       } else {
11921         assert(VT == MVT::v16i8);
11922         Opc = X86ISD::PINSRB;
11923       }
11924
11925       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11926       // argument.
11927       if (N1.getValueType() != MVT::i32)
11928         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11929       if (N2.getValueType() != MVT::i32)
11930         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11931       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11932     }
11933
11934     if (EltVT == MVT::f32) {
11935       // Bits [7:6] of the constant are the source select. This will always be
11936       //   zero here. The DAG Combiner may combine an extract_elt index into
11937       //   these bits. For example (insert (extract, 3), 2) could be matched by
11938       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11939       // Bits [5:4] of the constant are the destination select. This is the
11940       //   value of the incoming immediate.
11941       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11942       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11943
11944       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11945       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11946         // If this is an insertion of 32-bits into the low 32-bits of
11947         // a vector, we prefer to generate a blend with immediate rather
11948         // than an insertps. Blends are simpler operations in hardware and so
11949         // will always have equal or better performance than insertps.
11950         // But if optimizing for size and there's a load folding opportunity,
11951         // generate insertps because blendps does not have a 32-bit memory
11952         // operand form.
11953         N2 = DAG.getIntPtrConstant(1, dl);
11954         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11955         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11956       }
11957       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11958       // Create this as a scalar to vector..
11959       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11960       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11961     }
11962
11963     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11964       // PINSR* works with constant index.
11965       return Op;
11966     }
11967   }
11968
11969   if (EltVT == MVT::i8)
11970     return SDValue();
11971
11972   if (EltVT.getSizeInBits() == 16) {
11973     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11974     // as its second argument.
11975     if (N1.getValueType() != MVT::i32)
11976       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11977     if (N2.getValueType() != MVT::i32)
11978       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11979     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11980   }
11981   return SDValue();
11982 }
11983
11984 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11985   SDLoc dl(Op);
11986   MVT OpVT = Op.getSimpleValueType();
11987
11988   // If this is a 256-bit vector result, first insert into a 128-bit
11989   // vector and then insert into the 256-bit vector.
11990   if (!OpVT.is128BitVector()) {
11991     // Insert into a 128-bit vector.
11992     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11993     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11994                                  OpVT.getVectorNumElements() / SizeFactor);
11995
11996     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11997
11998     // Insert the 128-bit vector.
11999     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
12000   }
12001
12002   if (OpVT == MVT::v1i64 &&
12003       Op.getOperand(0).getValueType() == MVT::i64)
12004     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
12005
12006   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
12007   assert(OpVT.is128BitVector() && "Expected an SSE type!");
12008   return DAG.getBitcast(
12009       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
12010 }
12011
12012 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
12013 // a simple subregister reference or explicit instructions to grab
12014 // upper bits of a vector.
12015 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12016                                       SelectionDAG &DAG) {
12017   SDLoc dl(Op);
12018   SDValue In =  Op.getOperand(0);
12019   SDValue Idx = Op.getOperand(1);
12020   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12021   MVT ResVT   = Op.getSimpleValueType();
12022   MVT InVT    = In.getSimpleValueType();
12023
12024   if (Subtarget->hasFp256()) {
12025     if (ResVT.is128BitVector() &&
12026         (InVT.is256BitVector() || InVT.is512BitVector()) &&
12027         isa<ConstantSDNode>(Idx)) {
12028       return Extract128BitVector(In, IdxVal, DAG, dl);
12029     }
12030     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
12031         isa<ConstantSDNode>(Idx)) {
12032       return Extract256BitVector(In, IdxVal, DAG, dl);
12033     }
12034   }
12035   return SDValue();
12036 }
12037
12038 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
12039 // simple superregister reference or explicit instructions to insert
12040 // the upper bits of a vector.
12041 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12042                                      SelectionDAG &DAG) {
12043   if (!Subtarget->hasAVX())
12044     return SDValue();
12045
12046   SDLoc dl(Op);
12047   SDValue Vec = Op.getOperand(0);
12048   SDValue SubVec = Op.getOperand(1);
12049   SDValue Idx = Op.getOperand(2);
12050
12051   if (!isa<ConstantSDNode>(Idx))
12052     return SDValue();
12053
12054   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12055   MVT OpVT = Op.getSimpleValueType();
12056   MVT SubVecVT = SubVec.getSimpleValueType();
12057
12058   // Fold two 16-byte subvector loads into one 32-byte load:
12059   // (insert_subvector (insert_subvector undef, (load addr), 0),
12060   //                   (load addr + 16), Elts/2)
12061   // --> load32 addr
12062   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
12063       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
12064       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
12065     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
12066     if (Idx2 && Idx2->getZExtValue() == 0) {
12067       SDValue SubVec2 = Vec.getOperand(1);
12068       // If needed, look through a bitcast to get to the load.
12069       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
12070         SubVec2 = SubVec2.getOperand(0);
12071
12072       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
12073         bool Fast;
12074         unsigned Alignment = FirstLd->getAlignment();
12075         unsigned AS = FirstLd->getAddressSpace();
12076         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
12077         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
12078                                     OpVT, AS, Alignment, &Fast) && Fast) {
12079           SDValue Ops[] = { SubVec2, SubVec };
12080           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
12081             return Ld;
12082         }
12083       }
12084     }
12085   }
12086
12087   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
12088       SubVecVT.is128BitVector())
12089     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
12090
12091   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
12092     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
12093
12094   if (OpVT.getVectorElementType() == MVT::i1)
12095     return Insert1BitVector(Op, DAG);
12096
12097   return SDValue();
12098 }
12099
12100 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
12101 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
12102 // one of the above mentioned nodes. It has to be wrapped because otherwise
12103 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
12104 // be used to form addressing mode. These wrapped nodes will be selected
12105 // into MOV32ri.
12106 SDValue
12107 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
12108   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
12109
12110   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12111   // global base reg.
12112   unsigned char OpFlag = 0;
12113   unsigned WrapperKind = X86ISD::Wrapper;
12114   CodeModel::Model M = DAG.getTarget().getCodeModel();
12115
12116   if (Subtarget->isPICStyleRIPRel() &&
12117       (M == CodeModel::Small || M == CodeModel::Kernel))
12118     WrapperKind = X86ISD::WrapperRIP;
12119   else if (Subtarget->isPICStyleGOT())
12120     OpFlag = X86II::MO_GOTOFF;
12121   else if (Subtarget->isPICStyleStubPIC())
12122     OpFlag = X86II::MO_PIC_BASE_OFFSET;
12123
12124   auto PtrVT = getPointerTy(DAG.getDataLayout());
12125   SDValue Result = DAG.getTargetConstantPool(
12126       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
12127   SDLoc DL(CP);
12128   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12129   // With PIC, the address is actually $g + Offset.
12130   if (OpFlag) {
12131     Result =
12132         DAG.getNode(ISD::ADD, DL, PtrVT,
12133                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12134   }
12135
12136   return Result;
12137 }
12138
12139 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
12140   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
12141
12142   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12143   // global base reg.
12144   unsigned char OpFlag = 0;
12145   unsigned WrapperKind = X86ISD::Wrapper;
12146   CodeModel::Model M = DAG.getTarget().getCodeModel();
12147
12148   if (Subtarget->isPICStyleRIPRel() &&
12149       (M == CodeModel::Small || M == CodeModel::Kernel))
12150     WrapperKind = X86ISD::WrapperRIP;
12151   else if (Subtarget->isPICStyleGOT())
12152     OpFlag = X86II::MO_GOTOFF;
12153   else if (Subtarget->isPICStyleStubPIC())
12154     OpFlag = X86II::MO_PIC_BASE_OFFSET;
12155
12156   auto PtrVT = getPointerTy(DAG.getDataLayout());
12157   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
12158   SDLoc DL(JT);
12159   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12160
12161   // With PIC, the address is actually $g + Offset.
12162   if (OpFlag)
12163     Result =
12164         DAG.getNode(ISD::ADD, DL, PtrVT,
12165                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12166
12167   return Result;
12168 }
12169
12170 SDValue
12171 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
12172   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
12173
12174   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12175   // global base reg.
12176   unsigned char OpFlag = 0;
12177   unsigned WrapperKind = X86ISD::Wrapper;
12178   CodeModel::Model M = DAG.getTarget().getCodeModel();
12179
12180   if (Subtarget->isPICStyleRIPRel() &&
12181       (M == CodeModel::Small || M == CodeModel::Kernel)) {
12182     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
12183       OpFlag = X86II::MO_GOTPCREL;
12184     WrapperKind = X86ISD::WrapperRIP;
12185   } else if (Subtarget->isPICStyleGOT()) {
12186     OpFlag = X86II::MO_GOT;
12187   } else if (Subtarget->isPICStyleStubPIC()) {
12188     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
12189   } else if (Subtarget->isPICStyleStubNoDynamic()) {
12190     OpFlag = X86II::MO_DARWIN_NONLAZY;
12191   }
12192
12193   auto PtrVT = getPointerTy(DAG.getDataLayout());
12194   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
12195
12196   SDLoc DL(Op);
12197   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12198
12199   // With PIC, the address is actually $g + Offset.
12200   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
12201       !Subtarget->is64Bit()) {
12202     Result =
12203         DAG.getNode(ISD::ADD, DL, PtrVT,
12204                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12205   }
12206
12207   // For symbols that require a load from a stub to get the address, emit the
12208   // load.
12209   if (isGlobalStubReference(OpFlag))
12210     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
12211                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12212                          false, false, false, 0);
12213
12214   return Result;
12215 }
12216
12217 SDValue
12218 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
12219   // Create the TargetBlockAddressAddress node.
12220   unsigned char OpFlags =
12221     Subtarget->ClassifyBlockAddressReference();
12222   CodeModel::Model M = DAG.getTarget().getCodeModel();
12223   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
12224   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
12225   SDLoc dl(Op);
12226   auto PtrVT = getPointerTy(DAG.getDataLayout());
12227   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
12228
12229   if (Subtarget->isPICStyleRIPRel() &&
12230       (M == CodeModel::Small || M == CodeModel::Kernel))
12231     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12232   else
12233     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12234
12235   // With PIC, the address is actually $g + Offset.
12236   if (isGlobalRelativeToPICBase(OpFlags)) {
12237     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12238                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12239   }
12240
12241   return Result;
12242 }
12243
12244 SDValue
12245 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
12246                                       int64_t Offset, SelectionDAG &DAG) const {
12247   // Create the TargetGlobalAddress node, folding in the constant
12248   // offset if it is legal.
12249   unsigned char OpFlags =
12250       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
12251   CodeModel::Model M = DAG.getTarget().getCodeModel();
12252   auto PtrVT = getPointerTy(DAG.getDataLayout());
12253   SDValue Result;
12254   if (OpFlags == X86II::MO_NO_FLAG &&
12255       X86::isOffsetSuitableForCodeModel(Offset, M)) {
12256     // A direct static reference to a global.
12257     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
12258     Offset = 0;
12259   } else {
12260     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
12261   }
12262
12263   if (Subtarget->isPICStyleRIPRel() &&
12264       (M == CodeModel::Small || M == CodeModel::Kernel))
12265     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12266   else
12267     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12268
12269   // With PIC, the address is actually $g + Offset.
12270   if (isGlobalRelativeToPICBase(OpFlags)) {
12271     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12272                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12273   }
12274
12275   // For globals that require a load from a stub to get the address, emit the
12276   // load.
12277   if (isGlobalStubReference(OpFlags))
12278     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
12279                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12280                          false, false, false, 0);
12281
12282   // If there was a non-zero offset that we didn't fold, create an explicit
12283   // addition for it.
12284   if (Offset != 0)
12285     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
12286                          DAG.getConstant(Offset, dl, PtrVT));
12287
12288   return Result;
12289 }
12290
12291 SDValue
12292 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
12293   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
12294   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
12295   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
12296 }
12297
12298 static SDValue
12299 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
12300            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
12301            unsigned char OperandFlags, bool LocalDynamic = false) {
12302   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12303   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12304   SDLoc dl(GA);
12305   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12306                                            GA->getValueType(0),
12307                                            GA->getOffset(),
12308                                            OperandFlags);
12309
12310   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12311                                            : X86ISD::TLSADDR;
12312
12313   if (InFlag) {
12314     SDValue Ops[] = { Chain,  TGA, *InFlag };
12315     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12316   } else {
12317     SDValue Ops[]  = { Chain, TGA };
12318     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12319   }
12320
12321   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12322   MFI->setAdjustsStack(true);
12323   MFI->setHasCalls(true);
12324
12325   SDValue Flag = Chain.getValue(1);
12326   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12327 }
12328
12329 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12330 static SDValue
12331 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12332                                 const EVT PtrVT) {
12333   SDValue InFlag;
12334   SDLoc dl(GA);  // ? function entry point might be better
12335   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12336                                    DAG.getNode(X86ISD::GlobalBaseReg,
12337                                                SDLoc(), PtrVT), InFlag);
12338   InFlag = Chain.getValue(1);
12339
12340   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12341 }
12342
12343 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12344 static SDValue
12345 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12346                                 const EVT PtrVT) {
12347   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12348                     X86::RAX, X86II::MO_TLSGD);
12349 }
12350
12351 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12352                                            SelectionDAG &DAG,
12353                                            const EVT PtrVT,
12354                                            bool is64Bit) {
12355   SDLoc dl(GA);
12356
12357   // Get the start address of the TLS block for this module.
12358   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12359       .getInfo<X86MachineFunctionInfo>();
12360   MFI->incNumLocalDynamicTLSAccesses();
12361
12362   SDValue Base;
12363   if (is64Bit) {
12364     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12365                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
12366   } else {
12367     SDValue InFlag;
12368     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12369         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12370     InFlag = Chain.getValue(1);
12371     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12372                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12373   }
12374
12375   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12376   // of Base.
12377
12378   // Build x@dtpoff.
12379   unsigned char OperandFlags = X86II::MO_DTPOFF;
12380   unsigned WrapperKind = X86ISD::Wrapper;
12381   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12382                                            GA->getValueType(0),
12383                                            GA->getOffset(), OperandFlags);
12384   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12385
12386   // Add x@dtpoff with the base.
12387   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12388 }
12389
12390 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12391 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12392                                    const EVT PtrVT, TLSModel::Model model,
12393                                    bool is64Bit, bool isPIC) {
12394   SDLoc dl(GA);
12395
12396   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12397   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12398                                                          is64Bit ? 257 : 256));
12399
12400   SDValue ThreadPointer =
12401       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12402                   MachinePointerInfo(Ptr), false, false, false, 0);
12403
12404   unsigned char OperandFlags = 0;
12405   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
12406   // initialexec.
12407   unsigned WrapperKind = X86ISD::Wrapper;
12408   if (model == TLSModel::LocalExec) {
12409     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12410   } else if (model == TLSModel::InitialExec) {
12411     if (is64Bit) {
12412       OperandFlags = X86II::MO_GOTTPOFF;
12413       WrapperKind = X86ISD::WrapperRIP;
12414     } else {
12415       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12416     }
12417   } else {
12418     llvm_unreachable("Unexpected model");
12419   }
12420
12421   // emit "addl x@ntpoff,%eax" (local exec)
12422   // or "addl x@indntpoff,%eax" (initial exec)
12423   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12424   SDValue TGA =
12425       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12426                                  GA->getOffset(), OperandFlags);
12427   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12428
12429   if (model == TLSModel::InitialExec) {
12430     if (isPIC && !is64Bit) {
12431       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12432                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12433                            Offset);
12434     }
12435
12436     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12437                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12438                          false, false, false, 0);
12439   }
12440
12441   // The address of the thread local variable is the add of the thread
12442   // pointer with the offset of the variable.
12443   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12444 }
12445
12446 SDValue
12447 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12448
12449   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12450
12451   // Cygwin uses emutls.
12452   // FIXME: It may be EmulatedTLS-generic also for X86-Android.
12453   if (Subtarget->isTargetWindowsCygwin())
12454     return LowerToTLSEmulatedModel(GA, DAG);
12455
12456   const GlobalValue *GV = GA->getGlobal();
12457   auto PtrVT = getPointerTy(DAG.getDataLayout());
12458
12459   if (Subtarget->isTargetELF()) {
12460     if (DAG.getTarget().Options.EmulatedTLS)
12461       return LowerToTLSEmulatedModel(GA, DAG);
12462     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12463     switch (model) {
12464       case TLSModel::GeneralDynamic:
12465         if (Subtarget->is64Bit())
12466           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12467         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12468       case TLSModel::LocalDynamic:
12469         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12470                                            Subtarget->is64Bit());
12471       case TLSModel::InitialExec:
12472       case TLSModel::LocalExec:
12473         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12474                                    DAG.getTarget().getRelocationModel() ==
12475                                        Reloc::PIC_);
12476     }
12477     llvm_unreachable("Unknown TLS model.");
12478   }
12479
12480   if (Subtarget->isTargetDarwin()) {
12481     // Darwin only has one model of TLS.  Lower to that.
12482     unsigned char OpFlag = 0;
12483     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12484                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12485
12486     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12487     // global base reg.
12488     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12489                  !Subtarget->is64Bit();
12490     if (PIC32)
12491       OpFlag = X86II::MO_TLVP_PIC_BASE;
12492     else
12493       OpFlag = X86II::MO_TLVP;
12494     SDLoc DL(Op);
12495     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12496                                                 GA->getValueType(0),
12497                                                 GA->getOffset(), OpFlag);
12498     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12499
12500     // With PIC32, the address is actually $g + Offset.
12501     if (PIC32)
12502       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12503                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12504                            Offset);
12505
12506     // Lowering the machine isd will make sure everything is in the right
12507     // location.
12508     SDValue Chain = DAG.getEntryNode();
12509     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12510     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, DL, true), DL);
12511     SDValue Args[] = { Chain, Offset };
12512     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12513     Chain =
12514         DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
12515                            DAG.getIntPtrConstant(0, DL, true), SDValue(), DL);
12516
12517     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12518     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12519     MFI->setAdjustsStack(true);
12520
12521     // And our return value (tls address) is in the standard call return value
12522     // location.
12523     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12524     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12525   }
12526
12527   if (Subtarget->isTargetKnownWindowsMSVC() ||
12528       Subtarget->isTargetWindowsGNU()) {
12529     // Just use the implicit TLS architecture
12530     // Need to generate someting similar to:
12531     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12532     //                                  ; from TEB
12533     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12534     //   mov     rcx, qword [rdx+rcx*8]
12535     //   mov     eax, .tls$:tlsvar
12536     //   [rax+rcx] contains the address
12537     // Windows 64bit: gs:0x58
12538     // Windows 32bit: fs:__tls_array
12539
12540     SDLoc dl(GA);
12541     SDValue Chain = DAG.getEntryNode();
12542
12543     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12544     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12545     // use its literal value of 0x2C.
12546     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12547                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12548                                                              256)
12549                                         : Type::getInt32PtrTy(*DAG.getContext(),
12550                                                               257));
12551
12552     SDValue TlsArray = Subtarget->is64Bit()
12553                            ? DAG.getIntPtrConstant(0x58, dl)
12554                            : (Subtarget->isTargetWindowsGNU()
12555                                   ? DAG.getIntPtrConstant(0x2C, dl)
12556                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12557
12558     SDValue ThreadPointer =
12559         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12560                     false, false, 0);
12561
12562     SDValue res;
12563     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12564       res = ThreadPointer;
12565     } else {
12566       // Load the _tls_index variable
12567       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12568       if (Subtarget->is64Bit())
12569         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12570                              MachinePointerInfo(), MVT::i32, false, false,
12571                              false, 0);
12572       else
12573         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12574                           false, false, 0);
12575
12576       auto &DL = DAG.getDataLayout();
12577       SDValue Scale =
12578           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12579       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12580
12581       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12582     }
12583
12584     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12585                       false, 0);
12586
12587     // Get the offset of start of .tls section
12588     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12589                                              GA->getValueType(0),
12590                                              GA->getOffset(), X86II::MO_SECREL);
12591     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12592
12593     // The address of the thread local variable is the add of the thread
12594     // pointer with the offset of the variable.
12595     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12596   }
12597
12598   llvm_unreachable("TLS not implemented for this target.");
12599 }
12600
12601 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12602 /// and take a 2 x i32 value to shift plus a shift amount.
12603 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12604   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12605   MVT VT = Op.getSimpleValueType();
12606   unsigned VTBits = VT.getSizeInBits();
12607   SDLoc dl(Op);
12608   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12609   SDValue ShOpLo = Op.getOperand(0);
12610   SDValue ShOpHi = Op.getOperand(1);
12611   SDValue ShAmt  = Op.getOperand(2);
12612   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12613   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12614   // during isel.
12615   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12616                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12617   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12618                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12619                        : DAG.getConstant(0, dl, VT);
12620
12621   SDValue Tmp2, Tmp3;
12622   if (Op.getOpcode() == ISD::SHL_PARTS) {
12623     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12624     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12625   } else {
12626     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12627     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12628   }
12629
12630   // If the shift amount is larger or equal than the width of a part we can't
12631   // rely on the results of shld/shrd. Insert a test and select the appropriate
12632   // values for large shift amounts.
12633   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12634                                 DAG.getConstant(VTBits, dl, MVT::i8));
12635   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12636                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12637
12638   SDValue Hi, Lo;
12639   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12640   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12641   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12642
12643   if (Op.getOpcode() == ISD::SHL_PARTS) {
12644     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12645     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12646   } else {
12647     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12648     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12649   }
12650
12651   SDValue Ops[2] = { Lo, Hi };
12652   return DAG.getMergeValues(Ops, dl);
12653 }
12654
12655 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12656                                            SelectionDAG &DAG) const {
12657   SDValue Src = Op.getOperand(0);
12658   MVT SrcVT = Src.getSimpleValueType();
12659   MVT VT = Op.getSimpleValueType();
12660   SDLoc dl(Op);
12661
12662   if (SrcVT.isVector()) {
12663     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12664       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12665                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12666                          DAG.getUNDEF(SrcVT)));
12667     }
12668     if (SrcVT.getVectorElementType() == MVT::i1) {
12669       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12670       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12671                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12672     }
12673     return SDValue();
12674   }
12675
12676   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12677          "Unknown SINT_TO_FP to lower!");
12678
12679   // These are really Legal; return the operand so the caller accepts it as
12680   // Legal.
12681   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12682     return Op;
12683   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12684       Subtarget->is64Bit()) {
12685     return Op;
12686   }
12687
12688   SDValue ValueToStore = Op.getOperand(0);
12689   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12690       !Subtarget->is64Bit())
12691     // Bitcasting to f64 here allows us to do a single 64-bit store from
12692     // an SSE register, avoiding the store forwarding penalty that would come
12693     // with two 32-bit stores.
12694     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
12695
12696   unsigned Size = SrcVT.getSizeInBits()/8;
12697   MachineFunction &MF = DAG.getMachineFunction();
12698   auto PtrVT = getPointerTy(MF.getDataLayout());
12699   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12700   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12701   SDValue Chain = DAG.getStore(
12702       DAG.getEntryNode(), dl, ValueToStore, StackSlot,
12703       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12704       false, 0);
12705   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12706 }
12707
12708 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12709                                      SDValue StackSlot,
12710                                      SelectionDAG &DAG) const {
12711   // Build the FILD
12712   SDLoc DL(Op);
12713   SDVTList Tys;
12714   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12715   if (useSSE)
12716     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12717   else
12718     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12719
12720   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12721
12722   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12723   MachineMemOperand *MMO;
12724   if (FI) {
12725     int SSFI = FI->getIndex();
12726     MMO = DAG.getMachineFunction().getMachineMemOperand(
12727         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12728         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12729   } else {
12730     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12731     StackSlot = StackSlot.getOperand(1);
12732   }
12733   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12734   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12735                                            X86ISD::FILD, DL,
12736                                            Tys, Ops, SrcVT, MMO);
12737
12738   if (useSSE) {
12739     Chain = Result.getValue(1);
12740     SDValue InFlag = Result.getValue(2);
12741
12742     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12743     // shouldn't be necessary except that RFP cannot be live across
12744     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12745     MachineFunction &MF = DAG.getMachineFunction();
12746     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12747     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12748     auto PtrVT = getPointerTy(MF.getDataLayout());
12749     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12750     Tys = DAG.getVTList(MVT::Other);
12751     SDValue Ops[] = {
12752       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12753     };
12754     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12755         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12756         MachineMemOperand::MOStore, SSFISize, SSFISize);
12757
12758     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12759                                     Ops, Op.getValueType(), MMO);
12760     Result = DAG.getLoad(
12761         Op.getValueType(), DL, Chain, StackSlot,
12762         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12763         false, false, false, 0);
12764   }
12765
12766   return Result;
12767 }
12768
12769 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12770 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12771                                                SelectionDAG &DAG) const {
12772   // This algorithm is not obvious. Here it is what we're trying to output:
12773   /*
12774      movq       %rax,  %xmm0
12775      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12776      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12777      #ifdef __SSE3__
12778        haddpd   %xmm0, %xmm0
12779      #else
12780        pshufd   $0x4e, %xmm0, %xmm1
12781        addpd    %xmm1, %xmm0
12782      #endif
12783   */
12784
12785   SDLoc dl(Op);
12786   LLVMContext *Context = DAG.getContext();
12787
12788   // Build some magic constants.
12789   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12790   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12791   auto PtrVT = getPointerTy(DAG.getDataLayout());
12792   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12793
12794   SmallVector<Constant*,2> CV1;
12795   CV1.push_back(
12796     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12797                                       APInt(64, 0x4330000000000000ULL))));
12798   CV1.push_back(
12799     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12800                                       APInt(64, 0x4530000000000000ULL))));
12801   Constant *C1 = ConstantVector::get(CV1);
12802   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12803
12804   // Load the 64-bit value into an XMM register.
12805   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12806                             Op.getOperand(0));
12807   SDValue CLod0 =
12808       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12809                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12810                   false, false, false, 16);
12811   SDValue Unpck1 =
12812       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12813
12814   SDValue CLod1 =
12815       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12816                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12817                   false, false, false, 16);
12818   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12819   // TODO: Are there any fast-math-flags to propagate here?
12820   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12821   SDValue Result;
12822
12823   if (Subtarget->hasSSE3()) {
12824     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12825     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12826   } else {
12827     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12828     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12829                                            S2F, 0x4E, DAG);
12830     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12831                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12832   }
12833
12834   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12835                      DAG.getIntPtrConstant(0, dl));
12836 }
12837
12838 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12839 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12840                                                SelectionDAG &DAG) const {
12841   SDLoc dl(Op);
12842   // FP constant to bias correct the final result.
12843   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12844                                    MVT::f64);
12845
12846   // Load the 32-bit value into an XMM register.
12847   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12848                              Op.getOperand(0));
12849
12850   // Zero out the upper parts of the register.
12851   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12852
12853   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12854                      DAG.getBitcast(MVT::v2f64, Load),
12855                      DAG.getIntPtrConstant(0, dl));
12856
12857   // Or the load with the bias.
12858   SDValue Or = DAG.getNode(
12859       ISD::OR, dl, MVT::v2i64,
12860       DAG.getBitcast(MVT::v2i64,
12861                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12862       DAG.getBitcast(MVT::v2i64,
12863                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12864   Or =
12865       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12866                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12867
12868   // Subtract the bias.
12869   // TODO: Are there any fast-math-flags to propagate here?
12870   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12871
12872   // Handle final rounding.
12873   MVT DestVT = Op.getSimpleValueType();
12874
12875   if (DestVT.bitsLT(MVT::f64))
12876     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12877                        DAG.getIntPtrConstant(0, dl));
12878   if (DestVT.bitsGT(MVT::f64))
12879     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12880
12881   // Handle final rounding.
12882   return Sub;
12883 }
12884
12885 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12886                                      const X86Subtarget &Subtarget) {
12887   // The algorithm is the following:
12888   // #ifdef __SSE4_1__
12889   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12890   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12891   //                                 (uint4) 0x53000000, 0xaa);
12892   // #else
12893   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12894   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12895   // #endif
12896   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12897   //     return (float4) lo + fhi;
12898
12899   // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12900   // reassociate the two FADDs, and if we do that, the algorithm fails
12901   // spectacularly (PR24512).
12902   // FIXME: If we ever have some kind of Machine FMF, this should be marked
12903   // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12904   // there's also the MachineCombiner reassociations happening on Machine IR.
12905   if (DAG.getTarget().Options.UnsafeFPMath)
12906     return SDValue();
12907
12908   SDLoc DL(Op);
12909   SDValue V = Op->getOperand(0);
12910   MVT VecIntVT = V.getSimpleValueType();
12911   bool Is128 = VecIntVT == MVT::v4i32;
12912   MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12913   // If we convert to something else than the supported type, e.g., to v4f64,
12914   // abort early.
12915   if (VecFloatVT != Op->getSimpleValueType(0))
12916     return SDValue();
12917
12918   unsigned NumElts = VecIntVT.getVectorNumElements();
12919   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12920          "Unsupported custom type");
12921   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12922
12923   // In the #idef/#else code, we have in common:
12924   // - The vector of constants:
12925   // -- 0x4b000000
12926   // -- 0x53000000
12927   // - A shift:
12928   // -- v >> 16
12929
12930   // Create the splat vector for 0x4b000000.
12931   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12932   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12933                            CstLow, CstLow, CstLow, CstLow};
12934   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12935                                   makeArrayRef(&CstLowArray[0], NumElts));
12936   // Create the splat vector for 0x53000000.
12937   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12938   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12939                             CstHigh, CstHigh, CstHigh, CstHigh};
12940   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12941                                    makeArrayRef(&CstHighArray[0], NumElts));
12942
12943   // Create the right shift.
12944   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12945   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12946                              CstShift, CstShift, CstShift, CstShift};
12947   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12948                                     makeArrayRef(&CstShiftArray[0], NumElts));
12949   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12950
12951   SDValue Low, High;
12952   if (Subtarget.hasSSE41()) {
12953     MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12954     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12955     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12956     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12957     // Low will be bitcasted right away, so do not bother bitcasting back to its
12958     // original type.
12959     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12960                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12961     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12962     //                                 (uint4) 0x53000000, 0xaa);
12963     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12964     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12965     // High will be bitcasted right away, so do not bother bitcasting back to
12966     // its original type.
12967     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12968                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12969   } else {
12970     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12971     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12972                                      CstMask, CstMask, CstMask);
12973     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12974     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12975     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12976
12977     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12978     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12979   }
12980
12981   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12982   SDValue CstFAdd = DAG.getConstantFP(
12983       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12984   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12985                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12986   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12987                                    makeArrayRef(&CstFAddArray[0], NumElts));
12988
12989   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12990   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12991   // TODO: Are there any fast-math-flags to propagate here?
12992   SDValue FHigh =
12993       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12994   //     return (float4) lo + fhi;
12995   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12996   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12997 }
12998
12999 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
13000                                                SelectionDAG &DAG) const {
13001   SDValue N0 = Op.getOperand(0);
13002   MVT SVT = N0.getSimpleValueType();
13003   SDLoc dl(Op);
13004
13005   switch (SVT.SimpleTy) {
13006   default:
13007     llvm_unreachable("Custom UINT_TO_FP is not supported!");
13008   case MVT::v4i8:
13009   case MVT::v4i16:
13010   case MVT::v8i8:
13011   case MVT::v8i16: {
13012     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
13013     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13014                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
13015   }
13016   case MVT::v4i32:
13017   case MVT::v8i32:
13018     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
13019   case MVT::v16i8:
13020   case MVT::v16i16:
13021     assert(Subtarget->hasAVX512());
13022     return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
13023                        DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
13024   }
13025 }
13026
13027 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
13028                                            SelectionDAG &DAG) const {
13029   SDValue N0 = Op.getOperand(0);
13030   SDLoc dl(Op);
13031   auto PtrVT = getPointerTy(DAG.getDataLayout());
13032
13033   if (Op.getSimpleValueType().isVector())
13034     return lowerUINT_TO_FP_vec(Op, DAG);
13035
13036   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
13037   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
13038   // the optimization here.
13039   if (DAG.SignBitIsZero(N0))
13040     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
13041
13042   MVT SrcVT = N0.getSimpleValueType();
13043   MVT DstVT = Op.getSimpleValueType();
13044
13045   if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
13046       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
13047     // Conversions from unsigned i32 to f32/f64 are legal,
13048     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
13049     return Op;
13050   }
13051
13052   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
13053     return LowerUINT_TO_FP_i64(Op, DAG);
13054   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
13055     return LowerUINT_TO_FP_i32(Op, DAG);
13056   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
13057     return SDValue();
13058
13059   // Make a 64-bit buffer, and use it to build an FILD.
13060   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
13061   if (SrcVT == MVT::i32) {
13062     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
13063     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
13064     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13065                                   StackSlot, MachinePointerInfo(),
13066                                   false, false, 0);
13067     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
13068                                   OffsetSlot, MachinePointerInfo(),
13069                                   false, false, 0);
13070     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
13071     return Fild;
13072   }
13073
13074   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
13075   SDValue ValueToStore = Op.getOperand(0);
13076   if (isScalarFPTypeInSSEReg(Op.getValueType()) && !Subtarget->is64Bit())
13077     // Bitcasting to f64 here allows us to do a single 64-bit store from
13078     // an SSE register, avoiding the store forwarding penalty that would come
13079     // with two 32-bit stores.
13080     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
13081   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, ValueToStore,
13082                                StackSlot, MachinePointerInfo(),
13083                                false, false, 0);
13084   // For i64 source, we need to add the appropriate power of 2 if the input
13085   // was negative.  This is the same as the optimization in
13086   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
13087   // we must be careful to do the computation in x87 extended precision, not
13088   // in SSE. (The generic code can't know it's OK to do this, or how to.)
13089   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
13090   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
13091       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
13092       MachineMemOperand::MOLoad, 8, 8);
13093
13094   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
13095   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
13096   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
13097                                          MVT::i64, MMO);
13098
13099   APInt FF(32, 0x5F800000ULL);
13100
13101   // Check whether the sign bit is set.
13102   SDValue SignSet = DAG.getSetCC(
13103       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
13104       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
13105
13106   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
13107   SDValue FudgePtr = DAG.getConstantPool(
13108       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
13109
13110   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
13111   SDValue Zero = DAG.getIntPtrConstant(0, dl);
13112   SDValue Four = DAG.getIntPtrConstant(4, dl);
13113   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
13114                                Zero, Four);
13115   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
13116
13117   // Load the value out, extending it from f32 to f80.
13118   // FIXME: Avoid the extend by constructing the right constant pool?
13119   SDValue Fudge = DAG.getExtLoad(
13120       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
13121       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
13122       false, false, false, 4);
13123   // Extend everything to 80 bits to force it to be done on x87.
13124   // TODO: Are there any fast-math-flags to propagate here?
13125   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
13126   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
13127                      DAG.getIntPtrConstant(0, dl));
13128 }
13129
13130 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
13131 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
13132 // just return an <SDValue(), SDValue()> pair.
13133 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
13134 // to i16, i32 or i64, and we lower it to a legal sequence.
13135 // If lowered to the final integer result we return a <result, SDValue()> pair.
13136 // Otherwise we lower it to a sequence ending with a FIST, return a
13137 // <FIST, StackSlot> pair, and the caller is responsible for loading
13138 // the final integer result from StackSlot.
13139 std::pair<SDValue,SDValue>
13140 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
13141                                    bool IsSigned, bool IsReplace) const {
13142   SDLoc DL(Op);
13143
13144   EVT DstTy = Op.getValueType();
13145   EVT TheVT = Op.getOperand(0).getValueType();
13146   auto PtrVT = getPointerTy(DAG.getDataLayout());
13147
13148   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
13149     // f16 must be promoted before using the lowering in this routine.
13150     // fp128 does not use this lowering.
13151     return std::make_pair(SDValue(), SDValue());
13152   }
13153
13154   // If using FIST to compute an unsigned i64, we'll need some fixup
13155   // to handle values above the maximum signed i64.  A FIST is always
13156   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
13157   bool UnsignedFixup = !IsSigned &&
13158                        DstTy == MVT::i64 &&
13159                        (!Subtarget->is64Bit() ||
13160                         !isScalarFPTypeInSSEReg(TheVT));
13161
13162   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
13163     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
13164     // The low 32 bits of the fist result will have the correct uint32 result.
13165     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
13166     DstTy = MVT::i64;
13167   }
13168
13169   assert(DstTy.getSimpleVT() <= MVT::i64 &&
13170          DstTy.getSimpleVT() >= MVT::i16 &&
13171          "Unknown FP_TO_INT to lower!");
13172
13173   // These are really Legal.
13174   if (DstTy == MVT::i32 &&
13175       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13176     return std::make_pair(SDValue(), SDValue());
13177   if (Subtarget->is64Bit() &&
13178       DstTy == MVT::i64 &&
13179       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13180     return std::make_pair(SDValue(), SDValue());
13181
13182   // We lower FP->int64 into FISTP64 followed by a load from a temporary
13183   // stack slot.
13184   MachineFunction &MF = DAG.getMachineFunction();
13185   unsigned MemSize = DstTy.getSizeInBits()/8;
13186   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13187   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13188
13189   unsigned Opc;
13190   switch (DstTy.getSimpleVT().SimpleTy) {
13191   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
13192   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
13193   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
13194   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
13195   }
13196
13197   SDValue Chain = DAG.getEntryNode();
13198   SDValue Value = Op.getOperand(0);
13199   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
13200
13201   if (UnsignedFixup) {
13202     //
13203     // Conversion to unsigned i64 is implemented with a select,
13204     // depending on whether the source value fits in the range
13205     // of a signed i64.  Let Thresh be the FP equivalent of
13206     // 0x8000000000000000ULL.
13207     //
13208     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
13209     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
13210     //  Fist-to-mem64 FistSrc
13211     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
13212     //  to XOR'ing the high 32 bits with Adjust.
13213     //
13214     // Being a power of 2, Thresh is exactly representable in all FP formats.
13215     // For X87 we'd like to use the smallest FP type for this constant, but
13216     // for DAG type consistency we have to match the FP operand type.
13217
13218     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
13219     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
13220     bool LosesInfo = false;
13221     if (TheVT == MVT::f64)
13222       // The rounding mode is irrelevant as the conversion should be exact.
13223       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
13224                               &LosesInfo);
13225     else if (TheVT == MVT::f80)
13226       Status = Thresh.convert(APFloat::x87DoubleExtended,
13227                               APFloat::rmNearestTiesToEven, &LosesInfo);
13228
13229     assert(Status == APFloat::opOK && !LosesInfo &&
13230            "FP conversion should have been exact");
13231
13232     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
13233
13234     SDValue Cmp = DAG.getSetCC(DL,
13235                                getSetCCResultType(DAG.getDataLayout(),
13236                                                   *DAG.getContext(), TheVT),
13237                                Value, ThreshVal, ISD::SETLT);
13238     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
13239                            DAG.getConstant(0, DL, MVT::i32),
13240                            DAG.getConstant(0x80000000, DL, MVT::i32));
13241     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
13242     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
13243                                               *DAG.getContext(), TheVT),
13244                        Value, ThreshVal, ISD::SETLT);
13245     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
13246   }
13247
13248   // FIXME This causes a redundant load/store if the SSE-class value is already
13249   // in memory, such as if it is on the callstack.
13250   if (isScalarFPTypeInSSEReg(TheVT)) {
13251     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
13252     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
13253                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
13254                          false, 0);
13255     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
13256     SDValue Ops[] = {
13257       Chain, StackSlot, DAG.getValueType(TheVT)
13258     };
13259
13260     MachineMemOperand *MMO =
13261         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13262                                 MachineMemOperand::MOLoad, MemSize, MemSize);
13263     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
13264     Chain = Value.getValue(1);
13265     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13266     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13267   }
13268
13269   MachineMemOperand *MMO =
13270       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13271                               MachineMemOperand::MOStore, MemSize, MemSize);
13272
13273   if (UnsignedFixup) {
13274
13275     // Insert the FIST, load its result as two i32's,
13276     // and XOR the high i32 with Adjust.
13277
13278     SDValue FistOps[] = { Chain, Value, StackSlot };
13279     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13280                                            FistOps, DstTy, MMO);
13281
13282     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
13283                                 MachinePointerInfo(),
13284                                 false, false, false, 0);
13285     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
13286                                    DAG.getConstant(4, DL, PtrVT));
13287
13288     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
13289                                  MachinePointerInfo(),
13290                                  false, false, false, 0);
13291     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
13292
13293     if (Subtarget->is64Bit()) {
13294       // Join High32 and Low32 into a 64-bit result.
13295       // (High32 << 32) | Low32
13296       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
13297       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
13298       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
13299                            DAG.getConstant(32, DL, MVT::i8));
13300       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
13301       return std::make_pair(Result, SDValue());
13302     }
13303
13304     SDValue ResultOps[] = { Low32, High32 };
13305
13306     SDValue pair = IsReplace
13307       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
13308       : DAG.getMergeValues(ResultOps, DL);
13309     return std::make_pair(pair, SDValue());
13310   } else {
13311     // Build the FP_TO_INT*_IN_MEM
13312     SDValue Ops[] = { Chain, Value, StackSlot };
13313     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13314                                            Ops, DstTy, MMO);
13315     return std::make_pair(FIST, StackSlot);
13316   }
13317 }
13318
13319 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
13320                               const X86Subtarget *Subtarget) {
13321   MVT VT = Op->getSimpleValueType(0);
13322   SDValue In = Op->getOperand(0);
13323   MVT InVT = In.getSimpleValueType();
13324   SDLoc dl(Op);
13325
13326   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13327     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
13328
13329   // Optimize vectors in AVX mode:
13330   //
13331   //   v8i16 -> v8i32
13332   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
13333   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
13334   //   Concat upper and lower parts.
13335   //
13336   //   v4i32 -> v4i64
13337   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
13338   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
13339   //   Concat upper and lower parts.
13340   //
13341
13342   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13343       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13344       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13345     return SDValue();
13346
13347   if (Subtarget->hasInt256())
13348     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13349
13350   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13351   SDValue Undef = DAG.getUNDEF(InVT);
13352   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13353   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13354   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13355
13356   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13357                              VT.getVectorNumElements()/2);
13358
13359   OpLo = DAG.getBitcast(HVT, OpLo);
13360   OpHi = DAG.getBitcast(HVT, OpHi);
13361
13362   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13363 }
13364
13365 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13366                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13367   MVT VT = Op->getSimpleValueType(0);
13368   SDValue In = Op->getOperand(0);
13369   MVT InVT = In.getSimpleValueType();
13370   SDLoc DL(Op);
13371   unsigned int NumElts = VT.getVectorNumElements();
13372   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13373     return SDValue();
13374
13375   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13376     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13377
13378   assert(InVT.getVectorElementType() == MVT::i1);
13379   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13380   SDValue One =
13381    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13382   SDValue Zero =
13383    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13384
13385   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13386   if (VT.is512BitVector())
13387     return V;
13388   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13389 }
13390
13391 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13392                                SelectionDAG &DAG) {
13393   if (Subtarget->hasFp256())
13394     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13395       return Res;
13396
13397   return SDValue();
13398 }
13399
13400 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13401                                 SelectionDAG &DAG) {
13402   SDLoc DL(Op);
13403   MVT VT = Op.getSimpleValueType();
13404   SDValue In = Op.getOperand(0);
13405   MVT SVT = In.getSimpleValueType();
13406
13407   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13408     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13409
13410   if (Subtarget->hasFp256())
13411     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13412       return Res;
13413
13414   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13415          VT.getVectorNumElements() != SVT.getVectorNumElements());
13416   return SDValue();
13417 }
13418
13419 static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
13420                                   const X86Subtarget *Subtarget) {
13421
13422   SDLoc DL(Op);
13423   MVT VT = Op.getSimpleValueType();
13424   SDValue In = Op.getOperand(0);
13425   MVT InVT = In.getSimpleValueType();
13426
13427   assert(VT.getVectorElementType() == MVT::i1 && "Unexected vector type.");
13428
13429   // Shift LSB to MSB and use VPMOVB2M - SKX.
13430   unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
13431   if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13432          Subtarget->hasBWI()) ||     // legal, will go to VPMOVB2M, VPMOVW2M
13433       ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13434              InVT.getScalarSizeInBits() <= 16 && Subtarget->hasBWI() &&
13435              Subtarget->hasVLX())) { // legal, will go to VPMOVB2M, VPMOVW2M
13436     // Shift packed bytes not supported natively, bitcast to dword
13437     MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
13438     SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, ExtVT,
13439                                      DAG.getBitcast(ExtVT, In),
13440                                      DAG.getConstant(ShiftInx, DL, ExtVT));
13441     ShiftNode = DAG.getBitcast(InVT, ShiftNode);
13442     return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13443   }
13444   if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13445          Subtarget->hasDQI()) ||  // legal, will go to VPMOVD2M, VPMOVQ2M
13446       ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13447          InVT.getScalarSizeInBits() >= 32 && Subtarget->hasDQI() &&
13448          Subtarget->hasVLX())) {  // legal, will go to VPMOVD2M, VPMOVQ2M
13449
13450     SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13451                                      DAG.getConstant(ShiftInx, DL, InVT));
13452     return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13453   }
13454
13455   // Shift LSB to MSB, extend if necessary and use TESTM.
13456   unsigned NumElts = InVT.getVectorNumElements();
13457   if (InVT.getSizeInBits() < 512 &&
13458       (InVT.getScalarType() == MVT::i8 || InVT.getScalarType() == MVT::i16 ||
13459        !Subtarget->hasVLX())) {
13460     assert((NumElts == 8 || NumElts == 16) && "Unexected vector type.");
13461
13462     // TESTD/Q should be used (if BW supported we use CVT2MASK above),
13463     // so vector should be extended to packed dword/qword.
13464     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(512/NumElts), NumElts);
13465     In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13466     InVT = ExtVT;
13467     ShiftInx = InVT.getScalarSizeInBits() - 1;
13468   }
13469
13470   SDValue  ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13471                                    DAG.getConstant(ShiftInx, DL, InVT));
13472   return DAG.getNode(X86ISD::TESTM, DL, VT, ShiftNode, ShiftNode);
13473 }
13474
13475 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13476   SDLoc DL(Op);
13477   MVT VT = Op.getSimpleValueType();
13478   SDValue In = Op.getOperand(0);
13479   MVT InVT = In.getSimpleValueType();
13480
13481   if (VT == MVT::i1) {
13482     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13483            "Invalid scalar TRUNCATE operation");
13484     if (InVT.getSizeInBits() >= 32)
13485       return SDValue();
13486     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13487     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13488   }
13489   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13490          "Invalid TRUNCATE operation");
13491
13492   if (VT.getVectorElementType() == MVT::i1)
13493     return LowerTruncateVecI1(Op, DAG, Subtarget);
13494
13495   // vpmovqb/w/d, vpmovdb/w, vpmovwb
13496   if (Subtarget->hasAVX512()) {
13497     // word to byte only under BWI
13498     if (InVT == MVT::v16i16 && !Subtarget->hasBWI()) // v16i16 -> v16i8
13499       return DAG.getNode(X86ISD::VTRUNC, DL, VT,
13500                          DAG.getNode(X86ISD::VSEXT, DL, MVT::v16i32, In));
13501     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13502   }
13503   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13504     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13505     if (Subtarget->hasInt256()) {
13506       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13507       In = DAG.getBitcast(MVT::v8i32, In);
13508       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13509                                 ShufMask);
13510       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13511                          DAG.getIntPtrConstant(0, DL));
13512     }
13513
13514     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13515                                DAG.getIntPtrConstant(0, DL));
13516     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13517                                DAG.getIntPtrConstant(2, DL));
13518     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13519     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13520     static const int ShufMask[] = {0, 2, 4, 6};
13521     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13522   }
13523
13524   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13525     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13526     if (Subtarget->hasInt256()) {
13527       In = DAG.getBitcast(MVT::v32i8, In);
13528
13529       SmallVector<SDValue,32> pshufbMask;
13530       for (unsigned i = 0; i < 2; ++i) {
13531         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13532         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13533         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13534         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13535         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13536         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13537         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13538         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13539         for (unsigned j = 0; j < 8; ++j)
13540           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13541       }
13542       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13543       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13544       In = DAG.getBitcast(MVT::v4i64, In);
13545
13546       static const int ShufMask[] = {0,  2,  -1,  -1};
13547       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13548                                 &ShufMask[0]);
13549       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13550                        DAG.getIntPtrConstant(0, DL));
13551       return DAG.getBitcast(VT, In);
13552     }
13553
13554     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13555                                DAG.getIntPtrConstant(0, DL));
13556
13557     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13558                                DAG.getIntPtrConstant(4, DL));
13559
13560     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13561     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13562
13563     // The PSHUFB mask:
13564     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13565                                    -1, -1, -1, -1, -1, -1, -1, -1};
13566
13567     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13568     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13569     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13570
13571     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13572     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13573
13574     // The MOVLHPS Mask:
13575     static const int ShufMask2[] = {0, 1, 4, 5};
13576     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13577     return DAG.getBitcast(MVT::v8i16, res);
13578   }
13579
13580   // Handle truncation of V256 to V128 using shuffles.
13581   if (!VT.is128BitVector() || !InVT.is256BitVector())
13582     return SDValue();
13583
13584   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13585
13586   unsigned NumElems = VT.getVectorNumElements();
13587   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13588
13589   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13590   // Prepare truncation shuffle mask
13591   for (unsigned i = 0; i != NumElems; ++i)
13592     MaskVec[i] = i * 2;
13593   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13594                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13595   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13596                      DAG.getIntPtrConstant(0, DL));
13597 }
13598
13599 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13600                                            SelectionDAG &DAG) const {
13601   assert(!Op.getSimpleValueType().isVector());
13602
13603   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13604     /*IsSigned=*/ true, /*IsReplace=*/ false);
13605   SDValue FIST = Vals.first, StackSlot = Vals.second;
13606   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13607   if (!FIST.getNode())
13608     return Op;
13609
13610   if (StackSlot.getNode())
13611     // Load the result.
13612     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13613                        FIST, StackSlot, MachinePointerInfo(),
13614                        false, false, false, 0);
13615
13616   // The node is the result.
13617   return FIST;
13618 }
13619
13620 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13621                                            SelectionDAG &DAG) const {
13622   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13623     /*IsSigned=*/ false, /*IsReplace=*/ false);
13624   SDValue FIST = Vals.first, StackSlot = Vals.second;
13625   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13626   if (!FIST.getNode())
13627     return Op;
13628
13629   if (StackSlot.getNode())
13630     // Load the result.
13631     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13632                        FIST, StackSlot, MachinePointerInfo(),
13633                        false, false, false, 0);
13634
13635   // The node is the result.
13636   return FIST;
13637 }
13638
13639 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13640   SDLoc DL(Op);
13641   MVT VT = Op.getSimpleValueType();
13642   SDValue In = Op.getOperand(0);
13643   MVT SVT = In.getSimpleValueType();
13644
13645   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13646
13647   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13648                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13649                                  In, DAG.getUNDEF(SVT)));
13650 }
13651
13652 /// The only differences between FABS and FNEG are the mask and the logic op.
13653 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13654 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13655   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13656          "Wrong opcode for lowering FABS or FNEG.");
13657
13658   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13659
13660   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13661   // into an FNABS. We'll lower the FABS after that if it is still in use.
13662   if (IsFABS)
13663     for (SDNode *User : Op->uses())
13664       if (User->getOpcode() == ISD::FNEG)
13665         return Op;
13666
13667   SDLoc dl(Op);
13668   MVT VT = Op.getSimpleValueType();
13669
13670   bool IsF128 = (VT == MVT::f128);
13671
13672   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13673   // decide if we should generate a 16-byte constant mask when we only need 4 or
13674   // 8 bytes for the scalar case.
13675
13676   MVT LogicVT;
13677   MVT EltVT;
13678   unsigned NumElts;
13679
13680   if (VT.isVector()) {
13681     LogicVT = VT;
13682     EltVT = VT.getVectorElementType();
13683     NumElts = VT.getVectorNumElements();
13684   } else if (IsF128) {
13685     // SSE instructions are used for optimized f128 logical operations.
13686     LogicVT = MVT::f128;
13687     EltVT = VT;
13688     NumElts = 1;
13689   } else {
13690     // There are no scalar bitwise logical SSE/AVX instructions, so we
13691     // generate a 16-byte vector constant and logic op even for the scalar case.
13692     // Using a 16-byte mask allows folding the load of the mask with
13693     // the logic op, so it can save (~4 bytes) on code size.
13694     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13695     EltVT = VT;
13696     NumElts = (VT == MVT::f64) ? 2 : 4;
13697   }
13698
13699   unsigned EltBits = EltVT.getSizeInBits();
13700   LLVMContext *Context = DAG.getContext();
13701   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13702   APInt MaskElt =
13703     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13704   Constant *C = ConstantInt::get(*Context, MaskElt);
13705   C = ConstantVector::getSplat(NumElts, C);
13706   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13707   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13708   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13709   SDValue Mask =
13710       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13711                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13712                   false, false, false, Alignment);
13713
13714   SDValue Op0 = Op.getOperand(0);
13715   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13716   unsigned LogicOp =
13717     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13718   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13719
13720   if (VT.isVector() || IsF128)
13721     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13722
13723   // For the scalar case extend to a 128-bit vector, perform the logic op,
13724   // and extract the scalar result back out.
13725   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13726   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13727   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13728                      DAG.getIntPtrConstant(0, dl));
13729 }
13730
13731 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13732   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13733   LLVMContext *Context = DAG.getContext();
13734   SDValue Op0 = Op.getOperand(0);
13735   SDValue Op1 = Op.getOperand(1);
13736   SDLoc dl(Op);
13737   MVT VT = Op.getSimpleValueType();
13738   MVT SrcVT = Op1.getSimpleValueType();
13739   bool IsF128 = (VT == MVT::f128);
13740
13741   // If second operand is smaller, extend it first.
13742   if (SrcVT.bitsLT(VT)) {
13743     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13744     SrcVT = VT;
13745   }
13746   // And if it is bigger, shrink it first.
13747   if (SrcVT.bitsGT(VT)) {
13748     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13749     SrcVT = VT;
13750   }
13751
13752   // At this point the operands and the result should have the same
13753   // type, and that won't be f80 since that is not custom lowered.
13754   assert((VT == MVT::f64 || VT == MVT::f32 || IsF128) &&
13755          "Unexpected type in LowerFCOPYSIGN");
13756
13757   const fltSemantics &Sem =
13758       VT == MVT::f64 ? APFloat::IEEEdouble :
13759           (IsF128 ? APFloat::IEEEquad : APFloat::IEEEsingle);
13760   const unsigned SizeInBits = VT.getSizeInBits();
13761
13762   SmallVector<Constant *, 4> CV(
13763       VT == MVT::f64 ? 2 : (IsF128 ? 1 : 4),
13764       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13765
13766   // First, clear all bits but the sign bit from the second operand (sign).
13767   CV[0] = ConstantFP::get(*Context,
13768                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13769   Constant *C = ConstantVector::get(CV);
13770   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13771   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13772
13773   // Perform all logic operations as 16-byte vectors because there are no
13774   // scalar FP logic instructions in SSE. This allows load folding of the
13775   // constants into the logic instructions.
13776   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : (IsF128 ? MVT::f128 : MVT::v4f32);
13777   SDValue Mask1 =
13778       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13779                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13780                   false, false, false, 16);
13781   if (!IsF128)
13782     Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13783   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13784
13785   // Next, clear the sign bit from the first operand (magnitude).
13786   // If it's a constant, we can clear it here.
13787   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13788     APFloat APF = Op0CN->getValueAPF();
13789     // If the magnitude is a positive zero, the sign bit alone is enough.
13790     if (APF.isPosZero())
13791       return IsF128 ? SignBit :
13792           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13793                       DAG.getIntPtrConstant(0, dl));
13794     APF.clearSign();
13795     CV[0] = ConstantFP::get(*Context, APF);
13796   } else {
13797     CV[0] = ConstantFP::get(
13798         *Context,
13799         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13800   }
13801   C = ConstantVector::get(CV);
13802   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13803   SDValue Val =
13804       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13805                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13806                   false, false, false, 16);
13807   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13808   if (!isa<ConstantFPSDNode>(Op0)) {
13809     if (!IsF128)
13810       Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13811     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13812   }
13813   // OR the magnitude value with the sign bit.
13814   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13815   return IsF128 ? Val :
13816       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13817                   DAG.getIntPtrConstant(0, dl));
13818 }
13819
13820 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13821   SDValue N0 = Op.getOperand(0);
13822   SDLoc dl(Op);
13823   MVT VT = Op.getSimpleValueType();
13824
13825   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13826   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13827                                   DAG.getConstant(1, dl, VT));
13828   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13829 }
13830
13831 // Check whether an OR'd tree is PTEST-able.
13832 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13833                                       SelectionDAG &DAG) {
13834   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13835
13836   if (!Subtarget->hasSSE41())
13837     return SDValue();
13838
13839   if (!Op->hasOneUse())
13840     return SDValue();
13841
13842   SDNode *N = Op.getNode();
13843   SDLoc DL(N);
13844
13845   SmallVector<SDValue, 8> Opnds;
13846   DenseMap<SDValue, unsigned> VecInMap;
13847   SmallVector<SDValue, 8> VecIns;
13848   EVT VT = MVT::Other;
13849
13850   // Recognize a special case where a vector is casted into wide integer to
13851   // test all 0s.
13852   Opnds.push_back(N->getOperand(0));
13853   Opnds.push_back(N->getOperand(1));
13854
13855   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13856     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13857     // BFS traverse all OR'd operands.
13858     if (I->getOpcode() == ISD::OR) {
13859       Opnds.push_back(I->getOperand(0));
13860       Opnds.push_back(I->getOperand(1));
13861       // Re-evaluate the number of nodes to be traversed.
13862       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13863       continue;
13864     }
13865
13866     // Quit if a non-EXTRACT_VECTOR_ELT
13867     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13868       return SDValue();
13869
13870     // Quit if without a constant index.
13871     SDValue Idx = I->getOperand(1);
13872     if (!isa<ConstantSDNode>(Idx))
13873       return SDValue();
13874
13875     SDValue ExtractedFromVec = I->getOperand(0);
13876     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13877     if (M == VecInMap.end()) {
13878       VT = ExtractedFromVec.getValueType();
13879       // Quit if not 128/256-bit vector.
13880       if (!VT.is128BitVector() && !VT.is256BitVector())
13881         return SDValue();
13882       // Quit if not the same type.
13883       if (VecInMap.begin() != VecInMap.end() &&
13884           VT != VecInMap.begin()->first.getValueType())
13885         return SDValue();
13886       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13887       VecIns.push_back(ExtractedFromVec);
13888     }
13889     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13890   }
13891
13892   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13893          "Not extracted from 128-/256-bit vector.");
13894
13895   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13896
13897   for (DenseMap<SDValue, unsigned>::const_iterator
13898         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13899     // Quit if not all elements are used.
13900     if (I->second != FullMask)
13901       return SDValue();
13902   }
13903
13904   MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13905
13906   // Cast all vectors into TestVT for PTEST.
13907   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13908     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13909
13910   // If more than one full vectors are evaluated, OR them first before PTEST.
13911   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13912     // Each iteration will OR 2 nodes and append the result until there is only
13913     // 1 node left, i.e. the final OR'd value of all vectors.
13914     SDValue LHS = VecIns[Slot];
13915     SDValue RHS = VecIns[Slot + 1];
13916     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13917   }
13918
13919   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13920                      VecIns.back(), VecIns.back());
13921 }
13922
13923 /// \brief return true if \c Op has a use that doesn't just read flags.
13924 static bool hasNonFlagsUse(SDValue Op) {
13925   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13926        ++UI) {
13927     SDNode *User = *UI;
13928     unsigned UOpNo = UI.getOperandNo();
13929     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13930       // Look pass truncate.
13931       UOpNo = User->use_begin().getOperandNo();
13932       User = *User->use_begin();
13933     }
13934
13935     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13936         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13937       return true;
13938   }
13939   return false;
13940 }
13941
13942 /// Emit nodes that will be selected as "test Op0,Op0", or something
13943 /// equivalent.
13944 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13945                                     SelectionDAG &DAG) const {
13946   if (Op.getValueType() == MVT::i1) {
13947     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13948     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13949                        DAG.getConstant(0, dl, MVT::i8));
13950   }
13951   // CF and OF aren't always set the way we want. Determine which
13952   // of these we need.
13953   bool NeedCF = false;
13954   bool NeedOF = false;
13955   switch (X86CC) {
13956   default: break;
13957   case X86::COND_A: case X86::COND_AE:
13958   case X86::COND_B: case X86::COND_BE:
13959     NeedCF = true;
13960     break;
13961   case X86::COND_G: case X86::COND_GE:
13962   case X86::COND_L: case X86::COND_LE:
13963   case X86::COND_O: case X86::COND_NO: {
13964     // Check if we really need to set the
13965     // Overflow flag. If NoSignedWrap is present
13966     // that is not actually needed.
13967     switch (Op->getOpcode()) {
13968     case ISD::ADD:
13969     case ISD::SUB:
13970     case ISD::MUL:
13971     case ISD::SHL: {
13972       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13973       if (BinNode->Flags.hasNoSignedWrap())
13974         break;
13975     }
13976     default:
13977       NeedOF = true;
13978       break;
13979     }
13980     break;
13981   }
13982   }
13983   // See if we can use the EFLAGS value from the operand instead of
13984   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13985   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13986   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13987     // Emit a CMP with 0, which is the TEST pattern.
13988     //if (Op.getValueType() == MVT::i1)
13989     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13990     //                     DAG.getConstant(0, MVT::i1));
13991     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13992                        DAG.getConstant(0, dl, Op.getValueType()));
13993   }
13994   unsigned Opcode = 0;
13995   unsigned NumOperands = 0;
13996
13997   // Truncate operations may prevent the merge of the SETCC instruction
13998   // and the arithmetic instruction before it. Attempt to truncate the operands
13999   // of the arithmetic instruction and use a reduced bit-width instruction.
14000   bool NeedTruncation = false;
14001   SDValue ArithOp = Op;
14002   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
14003     SDValue Arith = Op->getOperand(0);
14004     // Both the trunc and the arithmetic op need to have one user each.
14005     if (Arith->hasOneUse())
14006       switch (Arith.getOpcode()) {
14007         default: break;
14008         case ISD::ADD:
14009         case ISD::SUB:
14010         case ISD::AND:
14011         case ISD::OR:
14012         case ISD::XOR: {
14013           NeedTruncation = true;
14014           ArithOp = Arith;
14015         }
14016       }
14017   }
14018
14019   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
14020   // which may be the result of a CAST.  We use the variable 'Op', which is the
14021   // non-casted variable when we check for possible users.
14022   switch (ArithOp.getOpcode()) {
14023   case ISD::ADD:
14024     // Due to an isel shortcoming, be conservative if this add is likely to be
14025     // selected as part of a load-modify-store instruction. When the root node
14026     // in a match is a store, isel doesn't know how to remap non-chain non-flag
14027     // uses of other nodes in the match, such as the ADD in this case. This
14028     // leads to the ADD being left around and reselected, with the result being
14029     // two adds in the output.  Alas, even if none our users are stores, that
14030     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
14031     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
14032     // climbing the DAG back to the root, and it doesn't seem to be worth the
14033     // effort.
14034     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14035          UE = Op.getNode()->use_end(); UI != UE; ++UI)
14036       if (UI->getOpcode() != ISD::CopyToReg &&
14037           UI->getOpcode() != ISD::SETCC &&
14038           UI->getOpcode() != ISD::STORE)
14039         goto default_case;
14040
14041     if (ConstantSDNode *C =
14042         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
14043       // An add of one will be selected as an INC.
14044       if (C->isOne() && !Subtarget->slowIncDec()) {
14045         Opcode = X86ISD::INC;
14046         NumOperands = 1;
14047         break;
14048       }
14049
14050       // An add of negative one (subtract of one) will be selected as a DEC.
14051       if (C->isAllOnesValue() && !Subtarget->slowIncDec()) {
14052         Opcode = X86ISD::DEC;
14053         NumOperands = 1;
14054         break;
14055       }
14056     }
14057
14058     // Otherwise use a regular EFLAGS-setting add.
14059     Opcode = X86ISD::ADD;
14060     NumOperands = 2;
14061     break;
14062   case ISD::SHL:
14063   case ISD::SRL:
14064     // If we have a constant logical shift that's only used in a comparison
14065     // against zero turn it into an equivalent AND. This allows turning it into
14066     // a TEST instruction later.
14067     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
14068         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
14069       EVT VT = Op.getValueType();
14070       unsigned BitWidth = VT.getSizeInBits();
14071       unsigned ShAmt = Op->getConstantOperandVal(1);
14072       if (ShAmt >= BitWidth) // Avoid undefined shifts.
14073         break;
14074       APInt Mask = ArithOp.getOpcode() == ISD::SRL
14075                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
14076                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
14077       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
14078         break;
14079       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
14080                                 DAG.getConstant(Mask, dl, VT));
14081       DAG.ReplaceAllUsesWith(Op, New);
14082       Op = New;
14083     }
14084     break;
14085
14086   case ISD::AND:
14087     // If the primary and result isn't used, don't bother using X86ISD::AND,
14088     // because a TEST instruction will be better.
14089     if (!hasNonFlagsUse(Op))
14090       break;
14091     // FALL THROUGH
14092   case ISD::SUB:
14093   case ISD::OR:
14094   case ISD::XOR:
14095     // Due to the ISEL shortcoming noted above, be conservative if this op is
14096     // likely to be selected as part of a load-modify-store instruction.
14097     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14098            UE = Op.getNode()->use_end(); UI != UE; ++UI)
14099       if (UI->getOpcode() == ISD::STORE)
14100         goto default_case;
14101
14102     // Otherwise use a regular EFLAGS-setting instruction.
14103     switch (ArithOp.getOpcode()) {
14104     default: llvm_unreachable("unexpected operator!");
14105     case ISD::SUB: Opcode = X86ISD::SUB; break;
14106     case ISD::XOR: Opcode = X86ISD::XOR; break;
14107     case ISD::AND: Opcode = X86ISD::AND; break;
14108     case ISD::OR: {
14109       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
14110         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
14111         if (EFLAGS.getNode())
14112           return EFLAGS;
14113       }
14114       Opcode = X86ISD::OR;
14115       break;
14116     }
14117     }
14118
14119     NumOperands = 2;
14120     break;
14121   case X86ISD::ADD:
14122   case X86ISD::SUB:
14123   case X86ISD::INC:
14124   case X86ISD::DEC:
14125   case X86ISD::OR:
14126   case X86ISD::XOR:
14127   case X86ISD::AND:
14128     return SDValue(Op.getNode(), 1);
14129   default:
14130   default_case:
14131     break;
14132   }
14133
14134   // If we found that truncation is beneficial, perform the truncation and
14135   // update 'Op'.
14136   if (NeedTruncation) {
14137     EVT VT = Op.getValueType();
14138     SDValue WideVal = Op->getOperand(0);
14139     EVT WideVT = WideVal.getValueType();
14140     unsigned ConvertedOp = 0;
14141     // Use a target machine opcode to prevent further DAGCombine
14142     // optimizations that may separate the arithmetic operations
14143     // from the setcc node.
14144     switch (WideVal.getOpcode()) {
14145       default: break;
14146       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
14147       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
14148       case ISD::AND: ConvertedOp = X86ISD::AND; break;
14149       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
14150       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
14151     }
14152
14153     if (ConvertedOp) {
14154       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14155       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
14156         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
14157         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
14158         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
14159       }
14160     }
14161   }
14162
14163   if (Opcode == 0)
14164     // Emit a CMP with 0, which is the TEST pattern.
14165     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14166                        DAG.getConstant(0, dl, Op.getValueType()));
14167
14168   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14169   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
14170
14171   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
14172   DAG.ReplaceAllUsesWith(Op, New);
14173   return SDValue(New.getNode(), 1);
14174 }
14175
14176 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
14177 /// equivalent.
14178 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
14179                                    SDLoc dl, SelectionDAG &DAG) const {
14180   if (isNullConstant(Op1))
14181     return EmitTest(Op0, X86CC, dl, DAG);
14182
14183   assert(!(isa<ConstantSDNode>(Op1) && Op0.getValueType() == MVT::i1) &&
14184          "Unexpected comparison operation for MVT::i1 operands");
14185
14186   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14187        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14188     // Do the comparison at i32 if it's smaller, besides the Atom case.
14189     // This avoids subregister aliasing issues. Keep the smaller reference
14190     // if we're optimizing for size, however, as that'll allow better folding
14191     // of memory operations.
14192     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
14193         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
14194         !Subtarget->isAtom()) {
14195       unsigned ExtendOp =
14196           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14197       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14198       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14199     }
14200     // Use SUB instead of CMP to enable CSE between SUB and CMP.
14201     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14202     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14203                               Op0, Op1);
14204     return SDValue(Sub.getNode(), 1);
14205   }
14206   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14207 }
14208
14209 /// Convert a comparison if required by the subtarget.
14210 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14211                                                  SelectionDAG &DAG) const {
14212   // If the subtarget does not support the FUCOMI instruction, floating-point
14213   // comparisons have to be converted.
14214   if (Subtarget->hasCMov() ||
14215       Cmp.getOpcode() != X86ISD::CMP ||
14216       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14217       !Cmp.getOperand(1).getValueType().isFloatingPoint())
14218     return Cmp;
14219
14220   // The instruction selector will select an FUCOM instruction instead of
14221   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14222   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14223   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14224   SDLoc dl(Cmp);
14225   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14226   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14227   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14228                             DAG.getConstant(8, dl, MVT::i8));
14229   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14230
14231   // Some 64-bit targets lack SAHF support, but they do support FCOMI.
14232   assert(Subtarget->hasLAHFSAHF() && "Target doesn't support SAHF or FCOMI?");
14233   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14234 }
14235
14236 /// The minimum architected relative accuracy is 2^-12. We need one
14237 /// Newton-Raphson step to have a good float result (24 bits of precision).
14238 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14239                                             DAGCombinerInfo &DCI,
14240                                             unsigned &RefinementSteps,
14241                                             bool &UseOneConstNR) const {
14242   EVT VT = Op.getValueType();
14243   const char *RecipOp;
14244
14245   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
14246   // TODO: Add support for AVX512 (v16f32).
14247   // It is likely not profitable to do this for f64 because a double-precision
14248   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14249   // instructions: convert to single, rsqrtss, convert back to double, refine
14250   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14251   // along with FMA, this could be a throughput win.
14252   if (VT == MVT::f32 && Subtarget->hasSSE1())
14253     RecipOp = "sqrtf";
14254   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14255            (VT == MVT::v8f32 && Subtarget->hasAVX()))
14256     RecipOp = "vec-sqrtf";
14257   else
14258     return SDValue();
14259
14260   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14261   if (!Recips.isEnabled(RecipOp))
14262     return SDValue();
14263
14264   RefinementSteps = Recips.getRefinementSteps(RecipOp);
14265   UseOneConstNR = false;
14266   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14267 }
14268
14269 /// The minimum architected relative accuracy is 2^-12. We need one
14270 /// Newton-Raphson step to have a good float result (24 bits of precision).
14271 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14272                                             DAGCombinerInfo &DCI,
14273                                             unsigned &RefinementSteps) const {
14274   EVT VT = Op.getValueType();
14275   const char *RecipOp;
14276
14277   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
14278   // TODO: Add support for AVX512 (v16f32).
14279   // It is likely not profitable to do this for f64 because a double-precision
14280   // reciprocal estimate with refinement on x86 prior to FMA requires
14281   // 15 instructions: convert to single, rcpss, convert back to double, refine
14282   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
14283   // along with FMA, this could be a throughput win.
14284   if (VT == MVT::f32 && Subtarget->hasSSE1())
14285     RecipOp = "divf";
14286   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14287            (VT == MVT::v8f32 && Subtarget->hasAVX()))
14288     RecipOp = "vec-divf";
14289   else
14290     return SDValue();
14291
14292   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14293   if (!Recips.isEnabled(RecipOp))
14294     return SDValue();
14295
14296   RefinementSteps = Recips.getRefinementSteps(RecipOp);
14297   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
14298 }
14299
14300 /// If we have at least two divisions that use the same divisor, convert to
14301 /// multplication by a reciprocal. This may need to be adjusted for a given
14302 /// CPU if a division's cost is not at least twice the cost of a multiplication.
14303 /// This is because we still need one division to calculate the reciprocal and
14304 /// then we need two multiplies by that reciprocal as replacements for the
14305 /// original divisions.
14306 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
14307   return 2;
14308 }
14309
14310 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
14311 /// if it's possible.
14312 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
14313                                      SDLoc dl, SelectionDAG &DAG) const {
14314   SDValue Op0 = And.getOperand(0);
14315   SDValue Op1 = And.getOperand(1);
14316   if (Op0.getOpcode() == ISD::TRUNCATE)
14317     Op0 = Op0.getOperand(0);
14318   if (Op1.getOpcode() == ISD::TRUNCATE)
14319     Op1 = Op1.getOperand(0);
14320
14321   SDValue LHS, RHS;
14322   if (Op1.getOpcode() == ISD::SHL)
14323     std::swap(Op0, Op1);
14324   if (Op0.getOpcode() == ISD::SHL) {
14325     if (isOneConstant(Op0.getOperand(0))) {
14326         // If we looked past a truncate, check that it's only truncating away
14327         // known zeros.
14328         unsigned BitWidth = Op0.getValueSizeInBits();
14329         unsigned AndBitWidth = And.getValueSizeInBits();
14330         if (BitWidth > AndBitWidth) {
14331           APInt Zeros, Ones;
14332           DAG.computeKnownBits(Op0, Zeros, Ones);
14333           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
14334             return SDValue();
14335         }
14336         LHS = Op1;
14337         RHS = Op0.getOperand(1);
14338       }
14339   } else if (Op1.getOpcode() == ISD::Constant) {
14340     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
14341     uint64_t AndRHSVal = AndRHS->getZExtValue();
14342     SDValue AndLHS = Op0;
14343
14344     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
14345       LHS = AndLHS.getOperand(0);
14346       RHS = AndLHS.getOperand(1);
14347     }
14348
14349     // Use BT if the immediate can't be encoded in a TEST instruction.
14350     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
14351       LHS = AndLHS;
14352       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
14353     }
14354   }
14355
14356   if (LHS.getNode()) {
14357     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
14358     // instruction.  Since the shift amount is in-range-or-undefined, we know
14359     // that doing a bittest on the i32 value is ok.  We extend to i32 because
14360     // the encoding for the i16 version is larger than the i32 version.
14361     // Also promote i16 to i32 for performance / code size reason.
14362     if (LHS.getValueType() == MVT::i8 ||
14363         LHS.getValueType() == MVT::i16)
14364       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
14365
14366     // If the operand types disagree, extend the shift amount to match.  Since
14367     // BT ignores high bits (like shifts) we can use anyextend.
14368     if (LHS.getValueType() != RHS.getValueType())
14369       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
14370
14371     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
14372     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
14373     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14374                        DAG.getConstant(Cond, dl, MVT::i8), BT);
14375   }
14376
14377   return SDValue();
14378 }
14379
14380 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14381 /// mask CMPs.
14382 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14383                               SDValue &Op1) {
14384   unsigned SSECC;
14385   bool Swap = false;
14386
14387   // SSE Condition code mapping:
14388   //  0 - EQ
14389   //  1 - LT
14390   //  2 - LE
14391   //  3 - UNORD
14392   //  4 - NEQ
14393   //  5 - NLT
14394   //  6 - NLE
14395   //  7 - ORD
14396   switch (SetCCOpcode) {
14397   default: llvm_unreachable("Unexpected SETCC condition");
14398   case ISD::SETOEQ:
14399   case ISD::SETEQ:  SSECC = 0; break;
14400   case ISD::SETOGT:
14401   case ISD::SETGT:  Swap = true; // Fallthrough
14402   case ISD::SETLT:
14403   case ISD::SETOLT: SSECC = 1; break;
14404   case ISD::SETOGE:
14405   case ISD::SETGE:  Swap = true; // Fallthrough
14406   case ISD::SETLE:
14407   case ISD::SETOLE: SSECC = 2; break;
14408   case ISD::SETUO:  SSECC = 3; break;
14409   case ISD::SETUNE:
14410   case ISD::SETNE:  SSECC = 4; break;
14411   case ISD::SETULE: Swap = true; // Fallthrough
14412   case ISD::SETUGE: SSECC = 5; break;
14413   case ISD::SETULT: Swap = true; // Fallthrough
14414   case ISD::SETUGT: SSECC = 6; break;
14415   case ISD::SETO:   SSECC = 7; break;
14416   case ISD::SETUEQ:
14417   case ISD::SETONE: SSECC = 8; break;
14418   }
14419   if (Swap)
14420     std::swap(Op0, Op1);
14421
14422   return SSECC;
14423 }
14424
14425 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14426 // ones, and then concatenate the result back.
14427 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14428   MVT VT = Op.getSimpleValueType();
14429
14430   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14431          "Unsupported value type for operation");
14432
14433   unsigned NumElems = VT.getVectorNumElements();
14434   SDLoc dl(Op);
14435   SDValue CC = Op.getOperand(2);
14436
14437   // Extract the LHS vectors
14438   SDValue LHS = Op.getOperand(0);
14439   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14440   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14441
14442   // Extract the RHS vectors
14443   SDValue RHS = Op.getOperand(1);
14444   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14445   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14446
14447   // Issue the operation on the smaller types and concatenate the result back
14448   MVT EltVT = VT.getVectorElementType();
14449   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14450   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14451                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14452                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14453 }
14454
14455 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14456   SDValue Op0 = Op.getOperand(0);
14457   SDValue Op1 = Op.getOperand(1);
14458   SDValue CC = Op.getOperand(2);
14459   MVT VT = Op.getSimpleValueType();
14460   SDLoc dl(Op);
14461
14462   assert(Op0.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14463          "Unexpected type for boolean compare operation");
14464   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14465   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14466                                DAG.getConstant(-1, dl, VT));
14467   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14468                                DAG.getConstant(-1, dl, VT));
14469   switch (SetCCOpcode) {
14470   default: llvm_unreachable("Unexpected SETCC condition");
14471   case ISD::SETEQ:
14472     // (x == y) -> ~(x ^ y)
14473     return DAG.getNode(ISD::XOR, dl, VT,
14474                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14475                        DAG.getConstant(-1, dl, VT));
14476   case ISD::SETNE:
14477     // (x != y) -> (x ^ y)
14478     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14479   case ISD::SETUGT:
14480   case ISD::SETGT:
14481     // (x > y) -> (x & ~y)
14482     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14483   case ISD::SETULT:
14484   case ISD::SETLT:
14485     // (x < y) -> (~x & y)
14486     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14487   case ISD::SETULE:
14488   case ISD::SETLE:
14489     // (x <= y) -> (~x | y)
14490     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14491   case ISD::SETUGE:
14492   case ISD::SETGE:
14493     // (x >=y) -> (x | ~y)
14494     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14495   }
14496 }
14497
14498 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14499                                      const X86Subtarget *Subtarget) {
14500   SDValue Op0 = Op.getOperand(0);
14501   SDValue Op1 = Op.getOperand(1);
14502   SDValue CC = Op.getOperand(2);
14503   MVT VT = Op.getSimpleValueType();
14504   SDLoc dl(Op);
14505
14506   assert(Op0.getSimpleValueType().getVectorElementType().getSizeInBits() >= 8 &&
14507          Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14508          "Cannot set masked compare for this operation");
14509
14510   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14511   unsigned  Opc = 0;
14512   bool Unsigned = false;
14513   bool Swap = false;
14514   unsigned SSECC;
14515   switch (SetCCOpcode) {
14516   default: llvm_unreachable("Unexpected SETCC condition");
14517   case ISD::SETNE:  SSECC = 4; break;
14518   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14519   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14520   case ISD::SETLT:  Swap = true; //fall-through
14521   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14522   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14523   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14524   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14525   case ISD::SETULE: Unsigned = true; //fall-through
14526   case ISD::SETLE:  SSECC = 2; break;
14527   }
14528
14529   if (Swap)
14530     std::swap(Op0, Op1);
14531   if (Opc)
14532     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14533   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14534   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14535                      DAG.getConstant(SSECC, dl, MVT::i8));
14536 }
14537
14538 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14539 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14540 /// return an empty value.
14541 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14542 {
14543   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14544   if (!BV)
14545     return SDValue();
14546
14547   MVT VT = Op1.getSimpleValueType();
14548   MVT EVT = VT.getVectorElementType();
14549   unsigned n = VT.getVectorNumElements();
14550   SmallVector<SDValue, 8> ULTOp1;
14551
14552   for (unsigned i = 0; i < n; ++i) {
14553     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14554     if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EVT)
14555       return SDValue();
14556
14557     // Avoid underflow.
14558     APInt Val = Elt->getAPIntValue();
14559     if (Val == 0)
14560       return SDValue();
14561
14562     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14563   }
14564
14565   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14566 }
14567
14568 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14569                            SelectionDAG &DAG) {
14570   SDValue Op0 = Op.getOperand(0);
14571   SDValue Op1 = Op.getOperand(1);
14572   SDValue CC = Op.getOperand(2);
14573   MVT VT = Op.getSimpleValueType();
14574   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14575   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14576   SDLoc dl(Op);
14577
14578   if (isFP) {
14579 #ifndef NDEBUG
14580     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14581     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14582 #endif
14583
14584     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14585     unsigned Opc = X86ISD::CMPP;
14586     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14587       assert(VT.getVectorNumElements() <= 16);
14588       Opc = X86ISD::CMPM;
14589     }
14590     // In the two special cases we can't handle, emit two comparisons.
14591     if (SSECC == 8) {
14592       unsigned CC0, CC1;
14593       unsigned CombineOpc;
14594       if (SetCCOpcode == ISD::SETUEQ) {
14595         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14596       } else {
14597         assert(SetCCOpcode == ISD::SETONE);
14598         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14599       }
14600
14601       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14602                                  DAG.getConstant(CC0, dl, MVT::i8));
14603       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14604                                  DAG.getConstant(CC1, dl, MVT::i8));
14605       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14606     }
14607     // Handle all other FP comparisons here.
14608     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14609                        DAG.getConstant(SSECC, dl, MVT::i8));
14610   }
14611
14612   MVT VTOp0 = Op0.getSimpleValueType();
14613   assert(VTOp0 == Op1.getSimpleValueType() &&
14614          "Expected operands with same type!");
14615   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14616          "Invalid number of packed elements for source and destination!");
14617
14618   if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14619     // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14620     // legalizer to a wider vector type.  In the case of 'vsetcc' nodes, the
14621     // legalizer firstly checks if the first operand in input to the setcc has
14622     // a legal type. If so, then it promotes the return type to that same type.
14623     // Otherwise, the return type is promoted to the 'next legal type' which,
14624     // for a vector of MVT::i1 is always a 128-bit integer vector type.
14625     //
14626     // We reach this code only if the following two conditions are met:
14627     // 1. Both return type and operand type have been promoted to wider types
14628     //    by the type legalizer.
14629     // 2. The original operand type has been promoted to a 256-bit vector.
14630     //
14631     // Note that condition 2. only applies for AVX targets.
14632     SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14633     return DAG.getZExtOrTrunc(NewOp, dl, VT);
14634   }
14635
14636   // The non-AVX512 code below works under the assumption that source and
14637   // destination types are the same.
14638   assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14639          "Value types for source and destination must be the same!");
14640
14641   // Break 256-bit integer vector compare into smaller ones.
14642   if (VT.is256BitVector() && !Subtarget->hasInt256())
14643     return Lower256IntVSETCC(Op, DAG);
14644
14645   MVT OpVT = Op1.getSimpleValueType();
14646   if (OpVT.getVectorElementType() == MVT::i1)
14647     return LowerBoolVSETCC_AVX512(Op, DAG);
14648
14649   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14650   if (Subtarget->hasAVX512()) {
14651     if (Op1.getSimpleValueType().is512BitVector() ||
14652         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14653         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14654       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14655
14656     // In AVX-512 architecture setcc returns mask with i1 elements,
14657     // But there is no compare instruction for i8 and i16 elements in KNL.
14658     // We are not talking about 512-bit operands in this case, these
14659     // types are illegal.
14660     if (MaskResult &&
14661         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14662          OpVT.getVectorElementType().getSizeInBits() >= 8))
14663       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14664                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14665   }
14666
14667   // Lower using XOP integer comparisons.
14668   if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14669        VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14670     // Translate compare code to XOP PCOM compare mode.
14671     unsigned CmpMode = 0;
14672     switch (SetCCOpcode) {
14673     default: llvm_unreachable("Unexpected SETCC condition");
14674     case ISD::SETULT:
14675     case ISD::SETLT: CmpMode = 0x00; break;
14676     case ISD::SETULE:
14677     case ISD::SETLE: CmpMode = 0x01; break;
14678     case ISD::SETUGT:
14679     case ISD::SETGT: CmpMode = 0x02; break;
14680     case ISD::SETUGE:
14681     case ISD::SETGE: CmpMode = 0x03; break;
14682     case ISD::SETEQ: CmpMode = 0x04; break;
14683     case ISD::SETNE: CmpMode = 0x05; break;
14684     }
14685
14686     // Are we comparing unsigned or signed integers?
14687     unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14688       ? X86ISD::VPCOMU : X86ISD::VPCOM;
14689
14690     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14691                        DAG.getConstant(CmpMode, dl, MVT::i8));
14692   }
14693
14694   // We are handling one of the integer comparisons here.  Since SSE only has
14695   // GT and EQ comparisons for integer, swapping operands and multiple
14696   // operations may be required for some comparisons.
14697   unsigned Opc;
14698   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14699   bool Subus = false;
14700
14701   switch (SetCCOpcode) {
14702   default: llvm_unreachable("Unexpected SETCC condition");
14703   case ISD::SETNE:  Invert = true;
14704   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14705   case ISD::SETLT:  Swap = true;
14706   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14707   case ISD::SETGE:  Swap = true;
14708   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14709                     Invert = true; break;
14710   case ISD::SETULT: Swap = true;
14711   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14712                     FlipSigns = true; break;
14713   case ISD::SETUGE: Swap = true;
14714   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14715                     FlipSigns = true; Invert = true; break;
14716   }
14717
14718   // Special case: Use min/max operations for SETULE/SETUGE
14719   MVT VET = VT.getVectorElementType();
14720   bool hasMinMax =
14721        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14722     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14723
14724   if (hasMinMax) {
14725     switch (SetCCOpcode) {
14726     default: break;
14727     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14728     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14729     }
14730
14731     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14732   }
14733
14734   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14735   if (!MinMax && hasSubus) {
14736     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14737     // Op0 u<= Op1:
14738     //   t = psubus Op0, Op1
14739     //   pcmpeq t, <0..0>
14740     switch (SetCCOpcode) {
14741     default: break;
14742     case ISD::SETULT: {
14743       // If the comparison is against a constant we can turn this into a
14744       // setule.  With psubus, setule does not require a swap.  This is
14745       // beneficial because the constant in the register is no longer
14746       // destructed as the destination so it can be hoisted out of a loop.
14747       // Only do this pre-AVX since vpcmp* is no longer destructive.
14748       if (Subtarget->hasAVX())
14749         break;
14750       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14751       if (ULEOp1.getNode()) {
14752         Op1 = ULEOp1;
14753         Subus = true; Invert = false; Swap = false;
14754       }
14755       break;
14756     }
14757     // Psubus is better than flip-sign because it requires no inversion.
14758     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14759     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14760     }
14761
14762     if (Subus) {
14763       Opc = X86ISD::SUBUS;
14764       FlipSigns = false;
14765     }
14766   }
14767
14768   if (Swap)
14769     std::swap(Op0, Op1);
14770
14771   // Check that the operation in question is available (most are plain SSE2,
14772   // but PCMPGTQ and PCMPEQQ have different requirements).
14773   if (VT == MVT::v2i64) {
14774     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14775       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14776
14777       // First cast everything to the right type.
14778       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14779       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14780
14781       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14782       // bits of the inputs before performing those operations. The lower
14783       // compare is always unsigned.
14784       SDValue SB;
14785       if (FlipSigns) {
14786         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14787       } else {
14788         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14789         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14790         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14791                          Sign, Zero, Sign, Zero);
14792       }
14793       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14794       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14795
14796       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14797       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14798       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14799
14800       // Create masks for only the low parts/high parts of the 64 bit integers.
14801       static const int MaskHi[] = { 1, 1, 3, 3 };
14802       static const int MaskLo[] = { 0, 0, 2, 2 };
14803       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14804       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14805       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14806
14807       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14808       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14809
14810       if (Invert)
14811         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14812
14813       return DAG.getBitcast(VT, Result);
14814     }
14815
14816     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14817       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14818       // pcmpeqd + pshufd + pand.
14819       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14820
14821       // First cast everything to the right type.
14822       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14823       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14824
14825       // Do the compare.
14826       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14827
14828       // Make sure the lower and upper halves are both all-ones.
14829       static const int Mask[] = { 1, 0, 3, 2 };
14830       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14831       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14832
14833       if (Invert)
14834         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14835
14836       return DAG.getBitcast(VT, Result);
14837     }
14838   }
14839
14840   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14841   // bits of the inputs before performing those operations.
14842   if (FlipSigns) {
14843     MVT EltVT = VT.getVectorElementType();
14844     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14845                                  VT);
14846     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14847     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14848   }
14849
14850   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14851
14852   // If the logical-not of the result is required, perform that now.
14853   if (Invert)
14854     Result = DAG.getNOT(dl, Result, VT);
14855
14856   if (MinMax)
14857     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14858
14859   if (Subus)
14860     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14861                          getZeroVector(VT, Subtarget, DAG, dl));
14862
14863   return Result;
14864 }
14865
14866 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14867
14868   MVT VT = Op.getSimpleValueType();
14869
14870   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14871
14872   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14873          && "SetCC type must be 8-bit or 1-bit integer");
14874   SDValue Op0 = Op.getOperand(0);
14875   SDValue Op1 = Op.getOperand(1);
14876   SDLoc dl(Op);
14877   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14878
14879   // Optimize to BT if possible.
14880   // Lower (X & (1 << N)) == 0 to BT(X, N).
14881   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14882   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14883   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14884       isNullConstant(Op1) &&
14885       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14886     if (SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG)) {
14887       if (VT == MVT::i1)
14888         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14889       return NewSetCC;
14890     }
14891   }
14892
14893   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14894   // these.
14895   if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
14896       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14897
14898     // If the input is a setcc, then reuse the input setcc or use a new one with
14899     // the inverted condition.
14900     if (Op0.getOpcode() == X86ISD::SETCC) {
14901       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14902       bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
14903       if (!Invert)
14904         return Op0;
14905
14906       CCode = X86::GetOppositeBranchCondition(CCode);
14907       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14908                                   DAG.getConstant(CCode, dl, MVT::i8),
14909                                   Op0.getOperand(1));
14910       if (VT == MVT::i1)
14911         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14912       return SetCC;
14913     }
14914   }
14915   if ((Op0.getValueType() == MVT::i1) && isOneConstant(Op1) &&
14916       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14917
14918     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14919     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14920   }
14921
14922   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14923   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14924   if (X86CC == X86::COND_INVALID)
14925     return SDValue();
14926
14927   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14928   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14929   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14930                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14931   if (VT == MVT::i1)
14932     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14933   return SetCC;
14934 }
14935
14936 SDValue X86TargetLowering::LowerSETCCE(SDValue Op, SelectionDAG &DAG) const {
14937   SDValue LHS = Op.getOperand(0);
14938   SDValue RHS = Op.getOperand(1);
14939   SDValue Carry = Op.getOperand(2);
14940   SDValue Cond = Op.getOperand(3);
14941   SDLoc DL(Op);
14942
14943   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
14944   X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
14945
14946   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
14947   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14948   SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry);
14949   return DAG.getNode(X86ISD::SETCC, DL, Op.getValueType(),
14950                      DAG.getConstant(CC, DL, MVT::i8), Cmp.getValue(1));
14951 }
14952
14953 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14954 static bool isX86LogicalCmp(SDValue Op) {
14955   unsigned Opc = Op.getNode()->getOpcode();
14956   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14957       Opc == X86ISD::SAHF)
14958     return true;
14959   if (Op.getResNo() == 1 &&
14960       (Opc == X86ISD::ADD ||
14961        Opc == X86ISD::SUB ||
14962        Opc == X86ISD::ADC ||
14963        Opc == X86ISD::SBB ||
14964        Opc == X86ISD::SMUL ||
14965        Opc == X86ISD::UMUL ||
14966        Opc == X86ISD::INC ||
14967        Opc == X86ISD::DEC ||
14968        Opc == X86ISD::OR ||
14969        Opc == X86ISD::XOR ||
14970        Opc == X86ISD::AND))
14971     return true;
14972
14973   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14974     return true;
14975
14976   return false;
14977 }
14978
14979 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14980   if (V.getOpcode() != ISD::TRUNCATE)
14981     return false;
14982
14983   SDValue VOp0 = V.getOperand(0);
14984   unsigned InBits = VOp0.getValueSizeInBits();
14985   unsigned Bits = V.getValueSizeInBits();
14986   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14987 }
14988
14989 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14990   bool addTest = true;
14991   SDValue Cond  = Op.getOperand(0);
14992   SDValue Op1 = Op.getOperand(1);
14993   SDValue Op2 = Op.getOperand(2);
14994   SDLoc DL(Op);
14995   MVT VT = Op1.getSimpleValueType();
14996   SDValue CC;
14997
14998   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14999   // are available or VBLENDV if AVX is available.
15000   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
15001   if (Cond.getOpcode() == ISD::SETCC &&
15002       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
15003        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
15004       VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
15005     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
15006     int SSECC = translateX86FSETCC(
15007         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
15008
15009     if (SSECC != 8) {
15010       if (Subtarget->hasAVX512()) {
15011         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
15012                                   DAG.getConstant(SSECC, DL, MVT::i8));
15013         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
15014       }
15015
15016       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
15017                                 DAG.getConstant(SSECC, DL, MVT::i8));
15018
15019       // If we have AVX, we can use a variable vector select (VBLENDV) instead
15020       // of 3 logic instructions for size savings and potentially speed.
15021       // Unfortunately, there is no scalar form of VBLENDV.
15022
15023       // If either operand is a constant, don't try this. We can expect to
15024       // optimize away at least one of the logic instructions later in that
15025       // case, so that sequence would be faster than a variable blend.
15026
15027       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
15028       // uses XMM0 as the selection register. That may need just as many
15029       // instructions as the AND/ANDN/OR sequence due to register moves, so
15030       // don't bother.
15031
15032       if (Subtarget->hasAVX() &&
15033           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
15034
15035         // Convert to vectors, do a VSELECT, and convert back to scalar.
15036         // All of the conversions should be optimized away.
15037
15038         MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
15039         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
15040         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
15041         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
15042
15043         MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
15044         VCmp = DAG.getBitcast(VCmpVT, VCmp);
15045
15046         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
15047
15048         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
15049                            VSel, DAG.getIntPtrConstant(0, DL));
15050       }
15051       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
15052       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
15053       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
15054     }
15055   }
15056
15057   if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
15058     SDValue Op1Scalar;
15059     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
15060       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
15061     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
15062       Op1Scalar = Op1.getOperand(0);
15063     SDValue Op2Scalar;
15064     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
15065       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
15066     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
15067       Op2Scalar = Op2.getOperand(0);
15068     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
15069       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
15070                                       Op1Scalar.getValueType(),
15071                                       Cond, Op1Scalar, Op2Scalar);
15072       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
15073         return DAG.getBitcast(VT, newSelect);
15074       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
15075       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
15076                          DAG.getIntPtrConstant(0, DL));
15077     }
15078   }
15079
15080   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
15081     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
15082     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15083                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
15084     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15085                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
15086     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
15087                                     Cond, Op1, Op2);
15088     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
15089   }
15090
15091   if (Cond.getOpcode() == ISD::SETCC) {
15092     SDValue NewCond = LowerSETCC(Cond, DAG);
15093     if (NewCond.getNode())
15094       Cond = NewCond;
15095   }
15096
15097   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
15098   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
15099   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
15100   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
15101   if (Cond.getOpcode() == X86ISD::SETCC &&
15102       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
15103       isNullConstant(Cond.getOperand(1).getOperand(1))) {
15104     SDValue Cmp = Cond.getOperand(1);
15105
15106     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
15107
15108     if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15109         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
15110       SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
15111
15112       SDValue CmpOp0 = Cmp.getOperand(0);
15113       // Apply further optimizations for special cases
15114       // (select (x != 0), -1, 0) -> neg & sbb
15115       // (select (x == 0), 0, -1) -> neg & sbb
15116       if (isNullConstant(Y) &&
15117             (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
15118           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
15119           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
15120                                     DAG.getConstant(0, DL,
15121                                                     CmpOp0.getValueType()),
15122                                     CmpOp0);
15123           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15124                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
15125                                     SDValue(Neg.getNode(), 1));
15126           return Res;
15127         }
15128
15129       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
15130                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
15131       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15132
15133       SDValue Res =   // Res = 0 or -1.
15134         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15135                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
15136
15137       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
15138         Res = DAG.getNOT(DL, Res, Res.getValueType());
15139
15140       if (!isNullConstant(Op2))
15141         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
15142       return Res;
15143     }
15144   }
15145
15146   // Look past (and (setcc_carry (cmp ...)), 1).
15147   if (Cond.getOpcode() == ISD::AND &&
15148       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15149       isOneConstant(Cond.getOperand(1)))
15150     Cond = Cond.getOperand(0);
15151
15152   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15153   // setting operand in place of the X86ISD::SETCC.
15154   unsigned CondOpcode = Cond.getOpcode();
15155   if (CondOpcode == X86ISD::SETCC ||
15156       CondOpcode == X86ISD::SETCC_CARRY) {
15157     CC = Cond.getOperand(0);
15158
15159     SDValue Cmp = Cond.getOperand(1);
15160     unsigned Opc = Cmp.getOpcode();
15161     MVT VT = Op.getSimpleValueType();
15162
15163     bool IllegalFPCMov = false;
15164     if (VT.isFloatingPoint() && !VT.isVector() &&
15165         !isScalarFPTypeInSSEReg(VT))  // FPStack?
15166       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
15167
15168     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
15169         Opc == X86ISD::BT) { // FIXME
15170       Cond = Cmp;
15171       addTest = false;
15172     }
15173   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15174              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15175              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15176               Cond.getOperand(0).getValueType() != MVT::i8)) {
15177     SDValue LHS = Cond.getOperand(0);
15178     SDValue RHS = Cond.getOperand(1);
15179     unsigned X86Opcode;
15180     unsigned X86Cond;
15181     SDVTList VTs;
15182     switch (CondOpcode) {
15183     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15184     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15185     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15186     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15187     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15188     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15189     default: llvm_unreachable("unexpected overflowing operator");
15190     }
15191     if (CondOpcode == ISD::UMULO)
15192       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15193                           MVT::i32);
15194     else
15195       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15196
15197     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15198
15199     if (CondOpcode == ISD::UMULO)
15200       Cond = X86Op.getValue(2);
15201     else
15202       Cond = X86Op.getValue(1);
15203
15204     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
15205     addTest = false;
15206   }
15207
15208   if (addTest) {
15209     // Look past the truncate if the high bits are known zero.
15210     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15211       Cond = Cond.getOperand(0);
15212
15213     // We know the result of AND is compared against zero. Try to match
15214     // it to BT.
15215     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15216       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG)) {
15217         CC = NewSetCC.getOperand(0);
15218         Cond = NewSetCC.getOperand(1);
15219         addTest = false;
15220       }
15221     }
15222   }
15223
15224   if (addTest) {
15225     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
15226     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
15227   }
15228
15229   // a <  b ? -1 :  0 -> RES = ~setcc_carry
15230   // a <  b ?  0 : -1 -> RES = setcc_carry
15231   // a >= b ? -1 :  0 -> RES = setcc_carry
15232   // a >= b ?  0 : -1 -> RES = ~setcc_carry
15233   if (Cond.getOpcode() == X86ISD::SUB) {
15234     Cond = ConvertCmpIfNecessary(Cond, DAG);
15235     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
15236
15237     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
15238         (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15239         (isNullConstant(Op1) || isNullConstant(Op2))) {
15240       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15241                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
15242                                 Cond);
15243       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
15244         return DAG.getNOT(DL, Res, Res.getValueType());
15245       return Res;
15246     }
15247   }
15248
15249   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15250   // widen the cmov and push the truncate through. This avoids introducing a new
15251   // branch during isel and doesn't add any extensions.
15252   if (Op.getValueType() == MVT::i8 &&
15253       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15254     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15255     if (T1.getValueType() == T2.getValueType() &&
15256         // Blacklist CopyFromReg to avoid partial register stalls.
15257         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15258       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15259       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15260       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15261     }
15262   }
15263
15264   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15265   // condition is true.
15266   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15267   SDValue Ops[] = { Op2, Op1, CC, Cond };
15268   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15269 }
15270
15271 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
15272                                        const X86Subtarget *Subtarget,
15273                                        SelectionDAG &DAG) {
15274   MVT VT = Op->getSimpleValueType(0);
15275   SDValue In = Op->getOperand(0);
15276   MVT InVT = In.getSimpleValueType();
15277   MVT VTElt = VT.getVectorElementType();
15278   MVT InVTElt = InVT.getVectorElementType();
15279   SDLoc dl(Op);
15280
15281   // SKX processor
15282   if ((InVTElt == MVT::i1) &&
15283       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15284         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15285
15286        ((Subtarget->hasBWI() && VT.is512BitVector() &&
15287         VTElt.getSizeInBits() <= 16)) ||
15288
15289        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15290         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15291
15292        ((Subtarget->hasDQI() && VT.is512BitVector() &&
15293         VTElt.getSizeInBits() >= 32))))
15294     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15295
15296   unsigned int NumElts = VT.getVectorNumElements();
15297
15298   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
15299     return SDValue();
15300
15301   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
15302     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
15303       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
15304     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15305   }
15306
15307   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15308   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
15309   SDValue NegOne =
15310    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
15311                    ExtVT);
15312   SDValue Zero =
15313    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
15314
15315   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
15316   if (VT.is512BitVector())
15317     return V;
15318   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
15319 }
15320
15321 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
15322                                              const X86Subtarget *Subtarget,
15323                                              SelectionDAG &DAG) {
15324   SDValue In = Op->getOperand(0);
15325   MVT VT = Op->getSimpleValueType(0);
15326   MVT InVT = In.getSimpleValueType();
15327   assert(VT.getSizeInBits() == InVT.getSizeInBits());
15328
15329   MVT InSVT = InVT.getVectorElementType();
15330   assert(VT.getVectorElementType().getSizeInBits() > InSVT.getSizeInBits());
15331
15332   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
15333     return SDValue();
15334   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
15335     return SDValue();
15336
15337   SDLoc dl(Op);
15338
15339   // SSE41 targets can use the pmovsx* instructions directly.
15340   if (Subtarget->hasSSE41())
15341     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15342
15343   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
15344   SDValue Curr = In;
15345   MVT CurrVT = InVT;
15346
15347   // As SRAI is only available on i16/i32 types, we expand only up to i32
15348   // and handle i64 separately.
15349   while (CurrVT != VT && CurrVT.getVectorElementType() != MVT::i32) {
15350     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
15351     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
15352     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
15353     Curr = DAG.getBitcast(CurrVT, Curr);
15354   }
15355
15356   SDValue SignExt = Curr;
15357   if (CurrVT != InVT) {
15358     unsigned SignExtShift =
15359         CurrVT.getVectorElementType().getSizeInBits() - InSVT.getSizeInBits();
15360     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15361                           DAG.getConstant(SignExtShift, dl, MVT::i8));
15362   }
15363
15364   if (CurrVT == VT)
15365     return SignExt;
15366
15367   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
15368     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15369                                DAG.getConstant(31, dl, MVT::i8));
15370     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
15371     return DAG.getBitcast(VT, Ext);
15372   }
15373
15374   return SDValue();
15375 }
15376
15377 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15378                                 SelectionDAG &DAG) {
15379   MVT VT = Op->getSimpleValueType(0);
15380   SDValue In = Op->getOperand(0);
15381   MVT InVT = In.getSimpleValueType();
15382   SDLoc dl(Op);
15383
15384   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15385     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15386
15387   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15388       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15389       (VT != MVT::v16i16 || InVT != MVT::v16i8))
15390     return SDValue();
15391
15392   if (Subtarget->hasInt256())
15393     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15394
15395   // Optimize vectors in AVX mode
15396   // Sign extend  v8i16 to v8i32 and
15397   //              v4i32 to v4i64
15398   //
15399   // Divide input vector into two parts
15400   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15401   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15402   // concat the vectors to original VT
15403
15404   unsigned NumElems = InVT.getVectorNumElements();
15405   SDValue Undef = DAG.getUNDEF(InVT);
15406
15407   SmallVector<int,8> ShufMask1(NumElems, -1);
15408   for (unsigned i = 0; i != NumElems/2; ++i)
15409     ShufMask1[i] = i;
15410
15411   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15412
15413   SmallVector<int,8> ShufMask2(NumElems, -1);
15414   for (unsigned i = 0; i != NumElems/2; ++i)
15415     ShufMask2[i] = i + NumElems/2;
15416
15417   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15418
15419   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
15420                                 VT.getVectorNumElements()/2);
15421
15422   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15423   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15424
15425   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15426 }
15427
15428 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15429 // may emit an illegal shuffle but the expansion is still better than scalar
15430 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15431 // we'll emit a shuffle and a arithmetic shift.
15432 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15433 // TODO: It is possible to support ZExt by zeroing the undef values during
15434 // the shuffle phase or after the shuffle.
15435 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15436                                  SelectionDAG &DAG) {
15437   MVT RegVT = Op.getSimpleValueType();
15438   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15439   assert(RegVT.isInteger() &&
15440          "We only custom lower integer vector sext loads.");
15441
15442   // Nothing useful we can do without SSE2 shuffles.
15443   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15444
15445   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15446   SDLoc dl(Ld);
15447   EVT MemVT = Ld->getMemoryVT();
15448   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15449   unsigned RegSz = RegVT.getSizeInBits();
15450
15451   ISD::LoadExtType Ext = Ld->getExtensionType();
15452
15453   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15454          && "Only anyext and sext are currently implemented.");
15455   assert(MemVT != RegVT && "Cannot extend to the same type");
15456   assert(MemVT.isVector() && "Must load a vector from memory");
15457
15458   unsigned NumElems = RegVT.getVectorNumElements();
15459   unsigned MemSz = MemVT.getSizeInBits();
15460   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15461
15462   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15463     // The only way in which we have a legal 256-bit vector result but not the
15464     // integer 256-bit operations needed to directly lower a sextload is if we
15465     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15466     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15467     // correctly legalized. We do this late to allow the canonical form of
15468     // sextload to persist throughout the rest of the DAG combiner -- it wants
15469     // to fold together any extensions it can, and so will fuse a sign_extend
15470     // of an sextload into a sextload targeting a wider value.
15471     SDValue Load;
15472     if (MemSz == 128) {
15473       // Just switch this to a normal load.
15474       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15475                                        "it must be a legal 128-bit vector "
15476                                        "type!");
15477       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15478                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15479                   Ld->isInvariant(), Ld->getAlignment());
15480     } else {
15481       assert(MemSz < 128 &&
15482              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15483       // Do an sext load to a 128-bit vector type. We want to use the same
15484       // number of elements, but elements half as wide. This will end up being
15485       // recursively lowered by this routine, but will succeed as we definitely
15486       // have all the necessary features if we're using AVX1.
15487       EVT HalfEltVT =
15488           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15489       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15490       Load =
15491           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15492                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15493                          Ld->isNonTemporal(), Ld->isInvariant(),
15494                          Ld->getAlignment());
15495     }
15496
15497     // Replace chain users with the new chain.
15498     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15499     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15500
15501     // Finally, do a normal sign-extend to the desired register.
15502     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15503   }
15504
15505   // All sizes must be a power of two.
15506   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15507          "Non-power-of-two elements are not custom lowered!");
15508
15509   // Attempt to load the original value using scalar loads.
15510   // Find the largest scalar type that divides the total loaded size.
15511   MVT SclrLoadTy = MVT::i8;
15512   for (MVT Tp : MVT::integer_valuetypes()) {
15513     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15514       SclrLoadTy = Tp;
15515     }
15516   }
15517
15518   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15519   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15520       (64 <= MemSz))
15521     SclrLoadTy = MVT::f64;
15522
15523   // Calculate the number of scalar loads that we need to perform
15524   // in order to load our vector from memory.
15525   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15526
15527   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15528          "Can only lower sext loads with a single scalar load!");
15529
15530   unsigned loadRegZize = RegSz;
15531   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15532     loadRegZize = 128;
15533
15534   // Represent our vector as a sequence of elements which are the
15535   // largest scalar that we can load.
15536   EVT LoadUnitVecVT = EVT::getVectorVT(
15537       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15538
15539   // Represent the data using the same element type that is stored in
15540   // memory. In practice, we ''widen'' MemVT.
15541   EVT WideVecVT =
15542       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15543                        loadRegZize / MemVT.getScalarSizeInBits());
15544
15545   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15546          "Invalid vector type");
15547
15548   // We can't shuffle using an illegal type.
15549   assert(TLI.isTypeLegal(WideVecVT) &&
15550          "We only lower types that form legal widened vector types");
15551
15552   SmallVector<SDValue, 8> Chains;
15553   SDValue Ptr = Ld->getBasePtr();
15554   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15555                                       TLI.getPointerTy(DAG.getDataLayout()));
15556   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15557
15558   for (unsigned i = 0; i < NumLoads; ++i) {
15559     // Perform a single load.
15560     SDValue ScalarLoad =
15561         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15562                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15563                     Ld->getAlignment());
15564     Chains.push_back(ScalarLoad.getValue(1));
15565     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15566     // another round of DAGCombining.
15567     if (i == 0)
15568       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15569     else
15570       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15571                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
15572
15573     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15574   }
15575
15576   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15577
15578   // Bitcast the loaded value to a vector of the original element type, in
15579   // the size of the target vector type.
15580   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15581   unsigned SizeRatio = RegSz / MemSz;
15582
15583   if (Ext == ISD::SEXTLOAD) {
15584     // If we have SSE4.1, we can directly emit a VSEXT node.
15585     if (Subtarget->hasSSE41()) {
15586       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15587       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15588       return Sext;
15589     }
15590
15591     // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15592     // lanes.
15593     assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15594            "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15595
15596     SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15597     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15598     return Shuff;
15599   }
15600
15601   // Redistribute the loaded elements into the different locations.
15602   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15603   for (unsigned i = 0; i != NumElems; ++i)
15604     ShuffleVec[i * SizeRatio] = i;
15605
15606   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15607                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15608
15609   // Bitcast to the requested type.
15610   Shuff = DAG.getBitcast(RegVT, Shuff);
15611   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15612   return Shuff;
15613 }
15614
15615 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15616 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15617 // from the AND / OR.
15618 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15619   Opc = Op.getOpcode();
15620   if (Opc != ISD::OR && Opc != ISD::AND)
15621     return false;
15622   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15623           Op.getOperand(0).hasOneUse() &&
15624           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15625           Op.getOperand(1).hasOneUse());
15626 }
15627
15628 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15629 // 1 and that the SETCC node has a single use.
15630 static bool isXor1OfSetCC(SDValue Op) {
15631   if (Op.getOpcode() != ISD::XOR)
15632     return false;
15633   if (isOneConstant(Op.getOperand(1)))
15634     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15635            Op.getOperand(0).hasOneUse();
15636   return false;
15637 }
15638
15639 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15640   bool addTest = true;
15641   SDValue Chain = Op.getOperand(0);
15642   SDValue Cond  = Op.getOperand(1);
15643   SDValue Dest  = Op.getOperand(2);
15644   SDLoc dl(Op);
15645   SDValue CC;
15646   bool Inverted = false;
15647
15648   if (Cond.getOpcode() == ISD::SETCC) {
15649     // Check for setcc([su]{add,sub,mul}o == 0).
15650     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15651         isNullConstant(Cond.getOperand(1)) &&
15652         Cond.getOperand(0).getResNo() == 1 &&
15653         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15654          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15655          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15656          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15657          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15658          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15659       Inverted = true;
15660       Cond = Cond.getOperand(0);
15661     } else {
15662       SDValue NewCond = LowerSETCC(Cond, DAG);
15663       if (NewCond.getNode())
15664         Cond = NewCond;
15665     }
15666   }
15667 #if 0
15668   // FIXME: LowerXALUO doesn't handle these!!
15669   else if (Cond.getOpcode() == X86ISD::ADD  ||
15670            Cond.getOpcode() == X86ISD::SUB  ||
15671            Cond.getOpcode() == X86ISD::SMUL ||
15672            Cond.getOpcode() == X86ISD::UMUL)
15673     Cond = LowerXALUO(Cond, DAG);
15674 #endif
15675
15676   // Look pass (and (setcc_carry (cmp ...)), 1).
15677   if (Cond.getOpcode() == ISD::AND &&
15678       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15679       isOneConstant(Cond.getOperand(1)))
15680     Cond = Cond.getOperand(0);
15681
15682   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15683   // setting operand in place of the X86ISD::SETCC.
15684   unsigned CondOpcode = Cond.getOpcode();
15685   if (CondOpcode == X86ISD::SETCC ||
15686       CondOpcode == X86ISD::SETCC_CARRY) {
15687     CC = Cond.getOperand(0);
15688
15689     SDValue Cmp = Cond.getOperand(1);
15690     unsigned Opc = Cmp.getOpcode();
15691     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15692     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15693       Cond = Cmp;
15694       addTest = false;
15695     } else {
15696       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15697       default: break;
15698       case X86::COND_O:
15699       case X86::COND_B:
15700         // These can only come from an arithmetic instruction with overflow,
15701         // e.g. SADDO, UADDO.
15702         Cond = Cond.getNode()->getOperand(1);
15703         addTest = false;
15704         break;
15705       }
15706     }
15707   }
15708   CondOpcode = Cond.getOpcode();
15709   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15710       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15711       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15712        Cond.getOperand(0).getValueType() != MVT::i8)) {
15713     SDValue LHS = Cond.getOperand(0);
15714     SDValue RHS = Cond.getOperand(1);
15715     unsigned X86Opcode;
15716     unsigned X86Cond;
15717     SDVTList VTs;
15718     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15719     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15720     // X86ISD::INC).
15721     switch (CondOpcode) {
15722     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15723     case ISD::SADDO:
15724       if (isOneConstant(RHS)) {
15725           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15726           break;
15727         }
15728       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15729     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15730     case ISD::SSUBO:
15731       if (isOneConstant(RHS)) {
15732           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15733           break;
15734         }
15735       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15736     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15737     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15738     default: llvm_unreachable("unexpected overflowing operator");
15739     }
15740     if (Inverted)
15741       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15742     if (CondOpcode == ISD::UMULO)
15743       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15744                           MVT::i32);
15745     else
15746       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15747
15748     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15749
15750     if (CondOpcode == ISD::UMULO)
15751       Cond = X86Op.getValue(2);
15752     else
15753       Cond = X86Op.getValue(1);
15754
15755     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15756     addTest = false;
15757   } else {
15758     unsigned CondOpc;
15759     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15760       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15761       if (CondOpc == ISD::OR) {
15762         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15763         // two branches instead of an explicit OR instruction with a
15764         // separate test.
15765         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15766             isX86LogicalCmp(Cmp)) {
15767           CC = Cond.getOperand(0).getOperand(0);
15768           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15769                               Chain, Dest, CC, Cmp);
15770           CC = Cond.getOperand(1).getOperand(0);
15771           Cond = Cmp;
15772           addTest = false;
15773         }
15774       } else { // ISD::AND
15775         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15776         // two branches instead of an explicit AND instruction with a
15777         // separate test. However, we only do this if this block doesn't
15778         // have a fall-through edge, because this requires an explicit
15779         // jmp when the condition is false.
15780         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15781             isX86LogicalCmp(Cmp) &&
15782             Op.getNode()->hasOneUse()) {
15783           X86::CondCode CCode =
15784             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15785           CCode = X86::GetOppositeBranchCondition(CCode);
15786           CC = DAG.getConstant(CCode, dl, MVT::i8);
15787           SDNode *User = *Op.getNode()->use_begin();
15788           // Look for an unconditional branch following this conditional branch.
15789           // We need this because we need to reverse the successors in order
15790           // to implement FCMP_OEQ.
15791           if (User->getOpcode() == ISD::BR) {
15792             SDValue FalseBB = User->getOperand(1);
15793             SDNode *NewBR =
15794               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15795             assert(NewBR == User);
15796             (void)NewBR;
15797             Dest = FalseBB;
15798
15799             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15800                                 Chain, Dest, CC, Cmp);
15801             X86::CondCode CCode =
15802               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15803             CCode = X86::GetOppositeBranchCondition(CCode);
15804             CC = DAG.getConstant(CCode, dl, MVT::i8);
15805             Cond = Cmp;
15806             addTest = false;
15807           }
15808         }
15809       }
15810     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15811       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15812       // It should be transformed during dag combiner except when the condition
15813       // is set by a arithmetics with overflow node.
15814       X86::CondCode CCode =
15815         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15816       CCode = X86::GetOppositeBranchCondition(CCode);
15817       CC = DAG.getConstant(CCode, dl, MVT::i8);
15818       Cond = Cond.getOperand(0).getOperand(1);
15819       addTest = false;
15820     } else if (Cond.getOpcode() == ISD::SETCC &&
15821                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15822       // For FCMP_OEQ, we can emit
15823       // two branches instead of an explicit AND instruction with a
15824       // separate test. However, we only do this if this block doesn't
15825       // have a fall-through edge, because this requires an explicit
15826       // jmp when the condition is false.
15827       if (Op.getNode()->hasOneUse()) {
15828         SDNode *User = *Op.getNode()->use_begin();
15829         // Look for an unconditional branch following this conditional branch.
15830         // We need this because we need to reverse the successors in order
15831         // to implement FCMP_OEQ.
15832         if (User->getOpcode() == ISD::BR) {
15833           SDValue FalseBB = User->getOperand(1);
15834           SDNode *NewBR =
15835             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15836           assert(NewBR == User);
15837           (void)NewBR;
15838           Dest = FalseBB;
15839
15840           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15841                                     Cond.getOperand(0), Cond.getOperand(1));
15842           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15843           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15844           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15845                               Chain, Dest, CC, Cmp);
15846           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15847           Cond = Cmp;
15848           addTest = false;
15849         }
15850       }
15851     } else if (Cond.getOpcode() == ISD::SETCC &&
15852                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15853       // For FCMP_UNE, we can emit
15854       // two branches instead of an explicit AND instruction with a
15855       // separate test. However, we only do this if this block doesn't
15856       // have a fall-through edge, because this requires an explicit
15857       // jmp when the condition is false.
15858       if (Op.getNode()->hasOneUse()) {
15859         SDNode *User = *Op.getNode()->use_begin();
15860         // Look for an unconditional branch following this conditional branch.
15861         // We need this because we need to reverse the successors in order
15862         // to implement FCMP_UNE.
15863         if (User->getOpcode() == ISD::BR) {
15864           SDValue FalseBB = User->getOperand(1);
15865           SDNode *NewBR =
15866             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15867           assert(NewBR == User);
15868           (void)NewBR;
15869
15870           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15871                                     Cond.getOperand(0), Cond.getOperand(1));
15872           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15873           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15874           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15875                               Chain, Dest, CC, Cmp);
15876           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15877           Cond = Cmp;
15878           addTest = false;
15879           Dest = FalseBB;
15880         }
15881       }
15882     }
15883   }
15884
15885   if (addTest) {
15886     // Look pass the truncate if the high bits are known zero.
15887     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15888         Cond = Cond.getOperand(0);
15889
15890     // We know the result of AND is compared against zero. Try to match
15891     // it to BT.
15892     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15893       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG)) {
15894         CC = NewSetCC.getOperand(0);
15895         Cond = NewSetCC.getOperand(1);
15896         addTest = false;
15897       }
15898     }
15899   }
15900
15901   if (addTest) {
15902     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15903     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15904     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15905   }
15906   Cond = ConvertCmpIfNecessary(Cond, DAG);
15907   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15908                      Chain, Dest, CC, Cond);
15909 }
15910
15911 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15912 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15913 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15914 // that the guard pages used by the OS virtual memory manager are allocated in
15915 // correct sequence.
15916 SDValue
15917 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15918                                            SelectionDAG &DAG) const {
15919   MachineFunction &MF = DAG.getMachineFunction();
15920   bool SplitStack = MF.shouldSplitStack();
15921   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15922                SplitStack;
15923   SDLoc dl(Op);
15924
15925   // Get the inputs.
15926   SDNode *Node = Op.getNode();
15927   SDValue Chain = Op.getOperand(0);
15928   SDValue Size  = Op.getOperand(1);
15929   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15930   EVT VT = Node->getValueType(0);
15931
15932   // Chain the dynamic stack allocation so that it doesn't modify the stack
15933   // pointer when other instructions are using the stack.
15934   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true), dl);
15935
15936   bool Is64Bit = Subtarget->is64Bit();
15937   MVT SPTy = getPointerTy(DAG.getDataLayout());
15938
15939   SDValue Result;
15940   if (!Lower) {
15941     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15942     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15943     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15944                     " not tell us which reg is the stack pointer!");
15945     EVT VT = Node->getValueType(0);
15946     SDValue Tmp3 = Node->getOperand(2);
15947
15948     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15949     Chain = SP.getValue(1);
15950     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15951     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15952     unsigned StackAlign = TFI.getStackAlignment();
15953     Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15954     if (Align > StackAlign)
15955       Result = DAG.getNode(ISD::AND, dl, VT, Result,
15956                          DAG.getConstant(-(uint64_t)Align, dl, VT));
15957     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
15958   } else if (SplitStack) {
15959     MachineRegisterInfo &MRI = MF.getRegInfo();
15960
15961     if (Is64Bit) {
15962       // The 64 bit implementation of segmented stacks needs to clobber both r10
15963       // r11. This makes it impossible to use it along with nested parameters.
15964       const Function *F = MF.getFunction();
15965
15966       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15967            I != E; ++I)
15968         if (I->hasNestAttr())
15969           report_fatal_error("Cannot use segmented stacks with functions that "
15970                              "have nested arguments.");
15971     }
15972
15973     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15974     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15975     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15976     Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15977                                 DAG.getRegister(Vreg, SPTy));
15978   } else {
15979     SDValue Flag;
15980     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15981
15982     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15983     Flag = Chain.getValue(1);
15984     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15985
15986     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15987
15988     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15989     unsigned SPReg = RegInfo->getStackRegister();
15990     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15991     Chain = SP.getValue(1);
15992
15993     if (Align) {
15994       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15995                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15996       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15997     }
15998
15999     Result = SP;
16000   }
16001
16002   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
16003                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
16004
16005   SDValue Ops[2] = {Result, Chain};
16006   return DAG.getMergeValues(Ops, dl);
16007 }
16008
16009 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
16010   MachineFunction &MF = DAG.getMachineFunction();
16011   auto PtrVT = getPointerTy(MF.getDataLayout());
16012   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16013
16014   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16015   SDLoc DL(Op);
16016
16017   if (!Subtarget->is64Bit() ||
16018       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
16019     // vastart just stores the address of the VarArgsFrameIndex slot into the
16020     // memory location argument.
16021     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
16022     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
16023                         MachinePointerInfo(SV), false, false, 0);
16024   }
16025
16026   // __va_list_tag:
16027   //   gp_offset         (0 - 6 * 8)
16028   //   fp_offset         (48 - 48 + 8 * 16)
16029   //   overflow_arg_area (point to parameters coming in memory).
16030   //   reg_save_area
16031   SmallVector<SDValue, 8> MemOps;
16032   SDValue FIN = Op.getOperand(1);
16033   // Store gp_offset
16034   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
16035                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
16036                                                DL, MVT::i32),
16037                                FIN, MachinePointerInfo(SV), false, false, 0);
16038   MemOps.push_back(Store);
16039
16040   // Store fp_offset
16041   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
16042   Store = DAG.getStore(Op.getOperand(0), DL,
16043                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
16044                                        MVT::i32),
16045                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
16046   MemOps.push_back(Store);
16047
16048   // Store ptr to overflow_arg_area
16049   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
16050   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
16051   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
16052                        MachinePointerInfo(SV, 8),
16053                        false, false, 0);
16054   MemOps.push_back(Store);
16055
16056   // Store ptr to reg_save_area.
16057   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
16058       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
16059   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
16060   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
16061       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
16062   MemOps.push_back(Store);
16063   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
16064 }
16065
16066 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
16067   assert(Subtarget->is64Bit() &&
16068          "LowerVAARG only handles 64-bit va_arg!");
16069   assert(Op.getNode()->getNumOperands() == 4);
16070
16071   MachineFunction &MF = DAG.getMachineFunction();
16072   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
16073     // The Win64 ABI uses char* instead of a structure.
16074     return DAG.expandVAArg(Op.getNode());
16075
16076   SDValue Chain = Op.getOperand(0);
16077   SDValue SrcPtr = Op.getOperand(1);
16078   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16079   unsigned Align = Op.getConstantOperandVal(3);
16080   SDLoc dl(Op);
16081
16082   EVT ArgVT = Op.getNode()->getValueType(0);
16083   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16084   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
16085   uint8_t ArgMode;
16086
16087   // Decide which area this value should be read from.
16088   // TODO: Implement the AMD64 ABI in its entirety. This simple
16089   // selection mechanism works only for the basic types.
16090   if (ArgVT == MVT::f80) {
16091     llvm_unreachable("va_arg for f80 not yet implemented");
16092   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
16093     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
16094   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
16095     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
16096   } else {
16097     llvm_unreachable("Unhandled argument type in LowerVAARG");
16098   }
16099
16100   if (ArgMode == 2) {
16101     // Sanity Check: Make sure using fp_offset makes sense.
16102     assert(!Subtarget->useSoftFloat() &&
16103            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
16104            Subtarget->hasSSE1());
16105   }
16106
16107   // Insert VAARG_64 node into the DAG
16108   // VAARG_64 returns two values: Variable Argument Address, Chain
16109   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
16110                        DAG.getConstant(ArgMode, dl, MVT::i8),
16111                        DAG.getConstant(Align, dl, MVT::i32)};
16112   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
16113   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
16114                                           VTs, InstOps, MVT::i64,
16115                                           MachinePointerInfo(SV),
16116                                           /*Align=*/0,
16117                                           /*Volatile=*/false,
16118                                           /*ReadMem=*/true,
16119                                           /*WriteMem=*/true);
16120   Chain = VAARG.getValue(1);
16121
16122   // Load the next argument and return it
16123   return DAG.getLoad(ArgVT, dl,
16124                      Chain,
16125                      VAARG,
16126                      MachinePointerInfo(),
16127                      false, false, false, 0);
16128 }
16129
16130 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
16131                            SelectionDAG &DAG) {
16132   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
16133   // where a va_list is still an i8*.
16134   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
16135   if (Subtarget->isCallingConvWin64(
16136         DAG.getMachineFunction().getFunction()->getCallingConv()))
16137     // Probably a Win64 va_copy.
16138     return DAG.expandVACopy(Op.getNode());
16139
16140   SDValue Chain = Op.getOperand(0);
16141   SDValue DstPtr = Op.getOperand(1);
16142   SDValue SrcPtr = Op.getOperand(2);
16143   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
16144   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16145   SDLoc DL(Op);
16146
16147   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
16148                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
16149                        false, false,
16150                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
16151 }
16152
16153 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
16154 // amount is a constant. Takes immediate version of shift as input.
16155 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
16156                                           SDValue SrcOp, uint64_t ShiftAmt,
16157                                           SelectionDAG &DAG) {
16158   MVT ElementType = VT.getVectorElementType();
16159
16160   // Fold this packed shift into its first operand if ShiftAmt is 0.
16161   if (ShiftAmt == 0)
16162     return SrcOp;
16163
16164   // Check for ShiftAmt >= element width
16165   if (ShiftAmt >= ElementType.getSizeInBits()) {
16166     if (Opc == X86ISD::VSRAI)
16167       ShiftAmt = ElementType.getSizeInBits() - 1;
16168     else
16169       return DAG.getConstant(0, dl, VT);
16170   }
16171
16172   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
16173          && "Unknown target vector shift-by-constant node");
16174
16175   // Fold this packed vector shift into a build vector if SrcOp is a
16176   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
16177   if (VT == SrcOp.getSimpleValueType() &&
16178       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
16179     SmallVector<SDValue, 8> Elts;
16180     unsigned NumElts = SrcOp->getNumOperands();
16181     ConstantSDNode *ND;
16182
16183     switch(Opc) {
16184     default: llvm_unreachable(nullptr);
16185     case X86ISD::VSHLI:
16186       for (unsigned i=0; i!=NumElts; ++i) {
16187         SDValue CurrentOp = SrcOp->getOperand(i);
16188         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16189           Elts.push_back(CurrentOp);
16190           continue;
16191         }
16192         ND = cast<ConstantSDNode>(CurrentOp);
16193         const APInt &C = ND->getAPIntValue();
16194         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
16195       }
16196       break;
16197     case X86ISD::VSRLI:
16198       for (unsigned i=0; i!=NumElts; ++i) {
16199         SDValue CurrentOp = SrcOp->getOperand(i);
16200         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16201           Elts.push_back(CurrentOp);
16202           continue;
16203         }
16204         ND = cast<ConstantSDNode>(CurrentOp);
16205         const APInt &C = ND->getAPIntValue();
16206         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
16207       }
16208       break;
16209     case X86ISD::VSRAI:
16210       for (unsigned i=0; i!=NumElts; ++i) {
16211         SDValue CurrentOp = SrcOp->getOperand(i);
16212         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16213           Elts.push_back(CurrentOp);
16214           continue;
16215         }
16216         ND = cast<ConstantSDNode>(CurrentOp);
16217         const APInt &C = ND->getAPIntValue();
16218         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
16219       }
16220       break;
16221     }
16222
16223     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16224   }
16225
16226   return DAG.getNode(Opc, dl, VT, SrcOp,
16227                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
16228 }
16229
16230 // getTargetVShiftNode - Handle vector element shifts where the shift amount
16231 // may or may not be a constant. Takes immediate version of shift as input.
16232 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
16233                                    SDValue SrcOp, SDValue ShAmt,
16234                                    SelectionDAG &DAG) {
16235   MVT SVT = ShAmt.getSimpleValueType();
16236   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
16237
16238   // Catch shift-by-constant.
16239   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
16240     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
16241                                       CShAmt->getZExtValue(), DAG);
16242
16243   // Change opcode to non-immediate version
16244   switch (Opc) {
16245     default: llvm_unreachable("Unknown target vector shift node");
16246     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16247     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16248     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16249   }
16250
16251   const X86Subtarget &Subtarget =
16252       static_cast<const X86Subtarget &>(DAG.getSubtarget());
16253   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
16254       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
16255     // Let the shuffle legalizer expand this shift amount node.
16256     SDValue Op0 = ShAmt.getOperand(0);
16257     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
16258     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
16259   } else {
16260     // Need to build a vector containing shift amount.
16261     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
16262     SmallVector<SDValue, 4> ShOps;
16263     ShOps.push_back(ShAmt);
16264     if (SVT == MVT::i32) {
16265       ShOps.push_back(DAG.getConstant(0, dl, SVT));
16266       ShOps.push_back(DAG.getUNDEF(SVT));
16267     }
16268     ShOps.push_back(DAG.getUNDEF(SVT));
16269
16270     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
16271     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
16272   }
16273
16274   // The return type has to be a 128-bit type with the same element
16275   // type as the input type.
16276   MVT EltVT = VT.getVectorElementType();
16277   MVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16278
16279   ShAmt = DAG.getBitcast(ShVT, ShAmt);
16280   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16281 }
16282
16283 /// \brief Return Mask with the necessary casting or extending
16284 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
16285 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
16286                            const X86Subtarget *Subtarget,
16287                            SelectionDAG &DAG, SDLoc dl) {
16288
16289   if (MaskVT.bitsGT(Mask.getSimpleValueType())) {
16290     // Mask should be extended
16291     Mask = DAG.getNode(ISD::ANY_EXTEND, dl,
16292                        MVT::getIntegerVT(MaskVT.getSizeInBits()), Mask);
16293   }
16294
16295   if (Mask.getSimpleValueType() == MVT::i64 && Subtarget->is32Bit()) {
16296     if (MaskVT == MVT::v64i1) {
16297       assert(Subtarget->hasBWI() && "Expected AVX512BW target!");
16298       // In case 32bit mode, bitcast i64 is illegal, extend/split it.
16299       SDValue Lo, Hi;
16300       Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16301                           DAG.getConstant(0, dl, MVT::i32));
16302       Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16303                           DAG.getConstant(1, dl, MVT::i32));
16304
16305       Lo = DAG.getBitcast(MVT::v32i1, Lo);
16306       Hi = DAG.getBitcast(MVT::v32i1, Hi);
16307
16308       return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
16309     } else {
16310       // MaskVT require < 64bit. Truncate mask (should succeed in any case),
16311       // and bitcast.
16312       MVT TruncVT = MVT::getIntegerVT(MaskVT.getSizeInBits());
16313       return DAG.getBitcast(MaskVT,
16314                             DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Mask));
16315     }
16316
16317   } else {
16318     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16319                                      Mask.getSimpleValueType().getSizeInBits());
16320     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16321     // are extracted by EXTRACT_SUBVECTOR.
16322     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16323                        DAG.getBitcast(BitcastVT, Mask),
16324                        DAG.getIntPtrConstant(0, dl));
16325   }
16326 }
16327
16328 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16329 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16330 /// necessary casting or extending for \p Mask when lowering masking intrinsics
16331 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16332                   SDValue PreservedSrc,
16333                   const X86Subtarget *Subtarget,
16334                   SelectionDAG &DAG) {
16335   MVT VT = Op.getSimpleValueType();
16336   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16337   unsigned OpcodeSelect = ISD::VSELECT;
16338   SDLoc dl(Op);
16339
16340   if (isAllOnesConstant(Mask))
16341     return Op;
16342
16343   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16344
16345   switch (Op.getOpcode()) {
16346   default: break;
16347   case X86ISD::PCMPEQM:
16348   case X86ISD::PCMPGTM:
16349   case X86ISD::CMPM:
16350   case X86ISD::CMPMU:
16351     return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16352   case X86ISD::VFPCLASS:
16353     case X86ISD::VFPCLASSS:
16354     return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
16355   case X86ISD::VTRUNC:
16356   case X86ISD::VTRUNCS:
16357   case X86ISD::VTRUNCUS:
16358     // We can't use ISD::VSELECT here because it is not always "Legal"
16359     // for the destination type. For example vpmovqb require only AVX512
16360     // and vselect that can operate on byte element type require BWI
16361     OpcodeSelect = X86ISD::SELECT;
16362     break;
16363   }
16364   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16365     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16366   return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
16367 }
16368
16369 /// \brief Creates an SDNode for a predicated scalar operation.
16370 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
16371 /// The mask is coming as MVT::i8 and it should be truncated
16372 /// to MVT::i1 while lowering masking intrinsics.
16373 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
16374 /// "X86select" instead of "vselect". We just can't create the "vselect" node
16375 /// for a scalar instruction.
16376 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16377                                     SDValue PreservedSrc,
16378                                     const X86Subtarget *Subtarget,
16379                                     SelectionDAG &DAG) {
16380   if (isAllOnesConstant(Mask))
16381     return Op;
16382
16383   MVT VT = Op.getSimpleValueType();
16384   SDLoc dl(Op);
16385   // The mask should be of type MVT::i1
16386   SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16387
16388   if (Op.getOpcode() == X86ISD::FSETCC)
16389     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
16390   if (Op.getOpcode() == X86ISD::VFPCLASS ||
16391       Op.getOpcode() == X86ISD::VFPCLASSS)
16392     return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
16393
16394   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16395     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16396   return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16397 }
16398
16399 static int getSEHRegistrationNodeSize(const Function *Fn) {
16400   if (!Fn->hasPersonalityFn())
16401     report_fatal_error(
16402         "querying registration node size for function without personality");
16403   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
16404   // WinEHStatePass for the full struct definition.
16405   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
16406   case EHPersonality::MSVC_X86SEH: return 24;
16407   case EHPersonality::MSVC_CXX: return 16;
16408   default: break;
16409   }
16410   report_fatal_error(
16411       "can only recover FP for 32-bit MSVC EH personality functions");
16412 }
16413
16414 /// When the MSVC runtime transfers control to us, either to an outlined
16415 /// function or when returning to a parent frame after catching an exception, we
16416 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
16417 /// Here's the math:
16418 ///   RegNodeBase = EntryEBP - RegNodeSize
16419 ///   ParentFP = RegNodeBase - ParentFrameOffset
16420 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16421 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16422 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16423                                    SDValue EntryEBP) {
16424   MachineFunction &MF = DAG.getMachineFunction();
16425   SDLoc dl;
16426
16427   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16428   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16429
16430   // It's possible that the parent function no longer has a personality function
16431   // if the exceptional code was optimized away, in which case we just return
16432   // the incoming EBP.
16433   if (!Fn->hasPersonalityFn())
16434     return EntryEBP;
16435
16436   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16437   // registration, or the .set_setframe offset.
16438   MCSymbol *OffsetSym =
16439       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16440           GlobalValue::getRealLinkageName(Fn->getName()));
16441   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16442   SDValue ParentFrameOffset =
16443       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16444
16445   // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
16446   // prologue to RBP in the parent function.
16447   const X86Subtarget &Subtarget =
16448       static_cast<const X86Subtarget &>(DAG.getSubtarget());
16449   if (Subtarget.is64Bit())
16450     return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
16451
16452   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16453   // RegNodeBase = EntryEBP - RegNodeSize
16454   // ParentFP = RegNodeBase - ParentFrameOffset
16455   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16456                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
16457   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
16458 }
16459
16460 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16461                                        SelectionDAG &DAG) {
16462   SDLoc dl(Op);
16463   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16464   MVT VT = Op.getSimpleValueType();
16465   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16466   if (IntrData) {
16467     switch(IntrData->Type) {
16468     case INTR_TYPE_1OP:
16469       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16470     case INTR_TYPE_2OP:
16471       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16472         Op.getOperand(2));
16473     case INTR_TYPE_2OP_IMM8:
16474       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16475                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16476     case INTR_TYPE_3OP:
16477       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16478         Op.getOperand(2), Op.getOperand(3));
16479     case INTR_TYPE_4OP:
16480       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16481         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16482     case INTR_TYPE_1OP_MASK_RM: {
16483       SDValue Src = Op.getOperand(1);
16484       SDValue PassThru = Op.getOperand(2);
16485       SDValue Mask = Op.getOperand(3);
16486       SDValue RoundingMode;
16487       // We allways add rounding mode to the Node.
16488       // If the rounding mode is not specified, we add the
16489       // "current direction" mode.
16490       if (Op.getNumOperands() == 4)
16491         RoundingMode =
16492           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16493       else
16494         RoundingMode = Op.getOperand(4);
16495       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16496       if (IntrWithRoundingModeOpcode != 0)
16497         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16498             X86::STATIC_ROUNDING::CUR_DIRECTION)
16499           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16500                                       dl, Op.getValueType(), Src, RoundingMode),
16501                                       Mask, PassThru, Subtarget, DAG);
16502       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16503                                               RoundingMode),
16504                                   Mask, PassThru, Subtarget, DAG);
16505     }
16506     case INTR_TYPE_1OP_MASK: {
16507       SDValue Src = Op.getOperand(1);
16508       SDValue PassThru = Op.getOperand(2);
16509       SDValue Mask = Op.getOperand(3);
16510       // We add rounding mode to the Node when
16511       //   - RM Opcode is specified and
16512       //   - RM is not "current direction".
16513       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16514       if (IntrWithRoundingModeOpcode != 0) {
16515         SDValue Rnd = Op.getOperand(4);
16516         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16517         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16518           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16519                                       dl, Op.getValueType(),
16520                                       Src, Rnd),
16521                                       Mask, PassThru, Subtarget, DAG);
16522         }
16523       }
16524       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16525                                   Mask, PassThru, Subtarget, DAG);
16526     }
16527     case INTR_TYPE_SCALAR_MASK: {
16528       SDValue Src1 = Op.getOperand(1);
16529       SDValue Src2 = Op.getOperand(2);
16530       SDValue passThru = Op.getOperand(3);
16531       SDValue Mask = Op.getOperand(4);
16532       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16533                                   Mask, passThru, Subtarget, DAG);
16534     }
16535     case INTR_TYPE_SCALAR_MASK_RM: {
16536       SDValue Src1 = Op.getOperand(1);
16537       SDValue Src2 = Op.getOperand(2);
16538       SDValue Src0 = Op.getOperand(3);
16539       SDValue Mask = Op.getOperand(4);
16540       // There are 2 kinds of intrinsics in this group:
16541       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16542       // (2) With rounding mode and sae - 7 operands.
16543       if (Op.getNumOperands() == 6) {
16544         SDValue Sae  = Op.getOperand(5);
16545         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16546         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16547                                                 Sae),
16548                                     Mask, Src0, Subtarget, DAG);
16549       }
16550       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16551       SDValue RoundingMode  = Op.getOperand(5);
16552       SDValue Sae  = Op.getOperand(6);
16553       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16554                                               RoundingMode, Sae),
16555                                   Mask, Src0, Subtarget, DAG);
16556     }
16557     case INTR_TYPE_2OP_MASK:
16558     case INTR_TYPE_2OP_IMM8_MASK: {
16559       SDValue Src1 = Op.getOperand(1);
16560       SDValue Src2 = Op.getOperand(2);
16561       SDValue PassThru = Op.getOperand(3);
16562       SDValue Mask = Op.getOperand(4);
16563
16564       if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16565         Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16566
16567       // We specify 2 possible opcodes for intrinsics with rounding modes.
16568       // First, we check if the intrinsic may have non-default rounding mode,
16569       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16570       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16571       if (IntrWithRoundingModeOpcode != 0) {
16572         SDValue Rnd = Op.getOperand(5);
16573         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16574         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16575           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16576                                       dl, Op.getValueType(),
16577                                       Src1, Src2, Rnd),
16578                                       Mask, PassThru, Subtarget, DAG);
16579         }
16580       }
16581       // TODO: Intrinsics should have fast-math-flags to propagate.
16582       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16583                                   Mask, PassThru, Subtarget, DAG);
16584     }
16585     case INTR_TYPE_2OP_MASK_RM: {
16586       SDValue Src1 = Op.getOperand(1);
16587       SDValue Src2 = Op.getOperand(2);
16588       SDValue PassThru = Op.getOperand(3);
16589       SDValue Mask = Op.getOperand(4);
16590       // We specify 2 possible modes for intrinsics, with/without rounding
16591       // modes.
16592       // First, we check if the intrinsic have rounding mode (6 operands),
16593       // if not, we set rounding mode to "current".
16594       SDValue Rnd;
16595       if (Op.getNumOperands() == 6)
16596         Rnd = Op.getOperand(5);
16597       else
16598         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16599       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16600                                               Src1, Src2, Rnd),
16601                                   Mask, PassThru, Subtarget, DAG);
16602     }
16603     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16604       SDValue Src1 = Op.getOperand(1);
16605       SDValue Src2 = Op.getOperand(2);
16606       SDValue Src3 = Op.getOperand(3);
16607       SDValue PassThru = Op.getOperand(4);
16608       SDValue Mask = Op.getOperand(5);
16609       SDValue Sae  = Op.getOperand(6);
16610
16611       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16612                                               Src2, Src3, Sae),
16613                                   Mask, PassThru, Subtarget, DAG);
16614     }
16615     case INTR_TYPE_3OP_MASK_RM: {
16616       SDValue Src1 = Op.getOperand(1);
16617       SDValue Src2 = Op.getOperand(2);
16618       SDValue Imm = Op.getOperand(3);
16619       SDValue PassThru = Op.getOperand(4);
16620       SDValue Mask = Op.getOperand(5);
16621       // We specify 2 possible modes for intrinsics, with/without rounding
16622       // modes.
16623       // First, we check if the intrinsic have rounding mode (7 operands),
16624       // if not, we set rounding mode to "current".
16625       SDValue Rnd;
16626       if (Op.getNumOperands() == 7)
16627         Rnd = Op.getOperand(6);
16628       else
16629         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16630       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16631         Src1, Src2, Imm, Rnd),
16632         Mask, PassThru, Subtarget, DAG);
16633     }
16634     case INTR_TYPE_3OP_IMM8_MASK:
16635     case INTR_TYPE_3OP_MASK:
16636     case INSERT_SUBVEC: {
16637       SDValue Src1 = Op.getOperand(1);
16638       SDValue Src2 = Op.getOperand(2);
16639       SDValue Src3 = Op.getOperand(3);
16640       SDValue PassThru = Op.getOperand(4);
16641       SDValue Mask = Op.getOperand(5);
16642
16643       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16644         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16645       else if (IntrData->Type == INSERT_SUBVEC) {
16646         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16647         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16648         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16649         Imm *= Src2.getSimpleValueType().getVectorNumElements();
16650         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16651       }
16652
16653       // We specify 2 possible opcodes for intrinsics with rounding modes.
16654       // First, we check if the intrinsic may have non-default rounding mode,
16655       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16656       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16657       if (IntrWithRoundingModeOpcode != 0) {
16658         SDValue Rnd = Op.getOperand(6);
16659         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16660         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16661           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16662                                       dl, Op.getValueType(),
16663                                       Src1, Src2, Src3, Rnd),
16664                                       Mask, PassThru, Subtarget, DAG);
16665         }
16666       }
16667       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16668                                               Src1, Src2, Src3),
16669                                   Mask, PassThru, Subtarget, DAG);
16670     }
16671     case VPERM_3OP_MASKZ:
16672     case VPERM_3OP_MASK:{
16673       // Src2 is the PassThru
16674       SDValue Src1 = Op.getOperand(1);
16675       SDValue Src2 = Op.getOperand(2);
16676       SDValue Src3 = Op.getOperand(3);
16677       SDValue Mask = Op.getOperand(4);
16678       MVT VT = Op.getSimpleValueType();
16679       SDValue PassThru = SDValue();
16680
16681       // set PassThru element
16682       if (IntrData->Type == VPERM_3OP_MASKZ)
16683         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16684       else
16685         PassThru = DAG.getBitcast(VT, Src2);
16686
16687       // Swap Src1 and Src2 in the node creation
16688       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16689                                               dl, Op.getValueType(),
16690                                               Src2, Src1, Src3),
16691                                   Mask, PassThru, Subtarget, DAG);
16692     }
16693     case FMA_OP_MASK3:
16694     case FMA_OP_MASKZ:
16695     case FMA_OP_MASK: {
16696       SDValue Src1 = Op.getOperand(1);
16697       SDValue Src2 = Op.getOperand(2);
16698       SDValue Src3 = Op.getOperand(3);
16699       SDValue Mask = Op.getOperand(4);
16700       MVT VT = Op.getSimpleValueType();
16701       SDValue PassThru = SDValue();
16702
16703       // set PassThru element
16704       if (IntrData->Type == FMA_OP_MASKZ)
16705         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16706       else if (IntrData->Type == FMA_OP_MASK3)
16707         PassThru = Src3;
16708       else
16709         PassThru = Src1;
16710
16711       // We specify 2 possible opcodes for intrinsics with rounding modes.
16712       // First, we check if the intrinsic may have non-default rounding mode,
16713       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16714       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16715       if (IntrWithRoundingModeOpcode != 0) {
16716         SDValue Rnd = Op.getOperand(5);
16717         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16718             X86::STATIC_ROUNDING::CUR_DIRECTION)
16719           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16720                                                   dl, Op.getValueType(),
16721                                                   Src1, Src2, Src3, Rnd),
16722                                       Mask, PassThru, Subtarget, DAG);
16723       }
16724       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16725                                               dl, Op.getValueType(),
16726                                               Src1, Src2, Src3),
16727                                   Mask, PassThru, Subtarget, DAG);
16728     }
16729     case TERLOG_OP_MASK:
16730     case TERLOG_OP_MASKZ: {
16731       SDValue Src1 = Op.getOperand(1);
16732       SDValue Src2 = Op.getOperand(2);
16733       SDValue Src3 = Op.getOperand(3);
16734       SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16735       SDValue Mask = Op.getOperand(5);
16736       MVT VT = Op.getSimpleValueType();
16737       SDValue PassThru = Src1;
16738       // Set PassThru element.
16739       if (IntrData->Type == TERLOG_OP_MASKZ)
16740         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16741
16742       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16743                                               Src1, Src2, Src3, Src4),
16744                                   Mask, PassThru, Subtarget, DAG);
16745     }
16746     case FPCLASS: {
16747       // FPclass intrinsics with mask
16748        SDValue Src1 = Op.getOperand(1);
16749        MVT VT = Src1.getSimpleValueType();
16750        MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16751        SDValue Imm = Op.getOperand(2);
16752        SDValue Mask = Op.getOperand(3);
16753        MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16754                                      Mask.getSimpleValueType().getSizeInBits());
16755        SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16756        SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16757                                                  DAG.getTargetConstant(0, dl, MaskVT),
16758                                                  Subtarget, DAG);
16759        SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16760                                  DAG.getUNDEF(BitcastVT), FPclassMask,
16761                                  DAG.getIntPtrConstant(0, dl));
16762        return DAG.getBitcast(Op.getValueType(), Res);
16763     }
16764     case FPCLASSS: {
16765       SDValue Src1 = Op.getOperand(1);
16766       SDValue Imm = Op.getOperand(2);
16767       SDValue Mask = Op.getOperand(3);
16768       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16769       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16770         DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16771       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16772     }
16773     case CMP_MASK:
16774     case CMP_MASK_CC: {
16775       // Comparison intrinsics with masks.
16776       // Example of transformation:
16777       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16778       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16779       // (i8 (bitcast
16780       //   (v8i1 (insert_subvector undef,
16781       //           (v2i1 (and (PCMPEQM %a, %b),
16782       //                      (extract_subvector
16783       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16784       MVT VT = Op.getOperand(1).getSimpleValueType();
16785       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16786       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16787       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16788                                        Mask.getSimpleValueType().getSizeInBits());
16789       SDValue Cmp;
16790       if (IntrData->Type == CMP_MASK_CC) {
16791         SDValue CC = Op.getOperand(3);
16792         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16793         // We specify 2 possible opcodes for intrinsics with rounding modes.
16794         // First, we check if the intrinsic may have non-default rounding mode,
16795         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16796         if (IntrData->Opc1 != 0) {
16797           SDValue Rnd = Op.getOperand(5);
16798           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16799               X86::STATIC_ROUNDING::CUR_DIRECTION)
16800             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16801                               Op.getOperand(2), CC, Rnd);
16802         }
16803         //default rounding mode
16804         if(!Cmp.getNode())
16805             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16806                               Op.getOperand(2), CC);
16807
16808       } else {
16809         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16810         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16811                           Op.getOperand(2));
16812       }
16813       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16814                                              DAG.getTargetConstant(0, dl,
16815                                                                    MaskVT),
16816                                              Subtarget, DAG);
16817       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16818                                 DAG.getUNDEF(BitcastVT), CmpMask,
16819                                 DAG.getIntPtrConstant(0, dl));
16820       return DAG.getBitcast(Op.getValueType(), Res);
16821     }
16822     case CMP_MASK_SCALAR_CC: {
16823       SDValue Src1 = Op.getOperand(1);
16824       SDValue Src2 = Op.getOperand(2);
16825       SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16826       SDValue Mask = Op.getOperand(4);
16827
16828       SDValue Cmp;
16829       if (IntrData->Opc1 != 0) {
16830         SDValue Rnd = Op.getOperand(5);
16831         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16832             X86::STATIC_ROUNDING::CUR_DIRECTION)
16833           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16834       }
16835       //default rounding mode
16836       if(!Cmp.getNode())
16837         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16838
16839       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16840                                              DAG.getTargetConstant(0, dl,
16841                                                                    MVT::i1),
16842                                              Subtarget, DAG);
16843
16844       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16845                          DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16846                          DAG.getValueType(MVT::i1));
16847     }
16848     case COMI: { // Comparison intrinsics
16849       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16850       SDValue LHS = Op.getOperand(1);
16851       SDValue RHS = Op.getOperand(2);
16852       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16853       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16854       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16855       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16856                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16857       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16858     }
16859     case COMI_RM: { // Comparison intrinsics with Sae
16860       SDValue LHS = Op.getOperand(1);
16861       SDValue RHS = Op.getOperand(2);
16862       SDValue CC = Op.getOperand(3);
16863       SDValue Sae = Op.getOperand(4);
16864       auto ComiType = TranslateX86ConstCondToX86CC(CC);
16865       // choose between ordered and unordered (comi/ucomi)
16866       unsigned comiOp = std::get<0>(ComiType) ? IntrData->Opc0 : IntrData->Opc1;
16867       SDValue Cond;
16868       if (cast<ConstantSDNode>(Sae)->getZExtValue() !=
16869                                            X86::STATIC_ROUNDING::CUR_DIRECTION)
16870         Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS, Sae);
16871       else
16872         Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS);
16873       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16874         DAG.getConstant(std::get<1>(ComiType), dl, MVT::i8), Cond);
16875       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16876     }
16877     case VSHIFT:
16878       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16879                                  Op.getOperand(1), Op.getOperand(2), DAG);
16880     case VSHIFT_MASK:
16881       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16882                                                       Op.getSimpleValueType(),
16883                                                       Op.getOperand(1),
16884                                                       Op.getOperand(2), DAG),
16885                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16886                                   DAG);
16887     case COMPRESS_EXPAND_IN_REG: {
16888       SDValue Mask = Op.getOperand(3);
16889       SDValue DataToCompress = Op.getOperand(1);
16890       SDValue PassThru = Op.getOperand(2);
16891       if (isAllOnesConstant(Mask)) // return data as is
16892         return Op.getOperand(1);
16893
16894       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16895                                               DataToCompress),
16896                                   Mask, PassThru, Subtarget, DAG);
16897     }
16898     case BROADCASTM: {
16899       SDValue Mask = Op.getOperand(1);
16900       MVT MaskVT = MVT::getVectorVT(MVT::i1,
16901                                     Mask.getSimpleValueType().getSizeInBits());
16902       Mask = DAG.getBitcast(MaskVT, Mask);
16903       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Mask);
16904     }
16905     case BLEND: {
16906       SDValue Mask = Op.getOperand(3);
16907       MVT VT = Op.getSimpleValueType();
16908       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16909       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16910       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16911                          Op.getOperand(2));
16912     }
16913     case KUNPCK: {
16914       MVT VT = Op.getSimpleValueType();
16915       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits()/2);
16916
16917       SDValue Src1 = getMaskNode(Op.getOperand(1), MaskVT, Subtarget, DAG, dl);
16918       SDValue Src2 = getMaskNode(Op.getOperand(2), MaskVT, Subtarget, DAG, dl);
16919       // Arguments should be swapped.
16920       SDValue Res = DAG.getNode(IntrData->Opc0, dl,
16921                                 MVT::getVectorVT(MVT::i1, VT.getSizeInBits()),
16922                                 Src2, Src1);
16923       return DAG.getBitcast(VT, Res);
16924     }
16925     case CONVERT_TO_MASK: {
16926       MVT SrcVT = Op.getOperand(1).getSimpleValueType();
16927       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
16928       MVT BitcastVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits());
16929
16930       SDValue CvtMask = DAG.getNode(IntrData->Opc0, dl, MaskVT,
16931                                     Op.getOperand(1));
16932       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16933                                 DAG.getUNDEF(BitcastVT), CvtMask,
16934                                 DAG.getIntPtrConstant(0, dl));
16935       return DAG.getBitcast(Op.getValueType(), Res);
16936     }
16937     case CONVERT_MASK_TO_VEC: {
16938       SDValue Mask = Op.getOperand(1);
16939       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16940       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16941       return DAG.getNode(IntrData->Opc0, dl, VT, VMask);
16942     }
16943     case BRCST_SUBVEC_TO_VEC: {
16944       SDValue Src = Op.getOperand(1);
16945       SDValue Passthru = Op.getOperand(2);
16946       SDValue Mask = Op.getOperand(3);
16947       EVT resVT = Passthru.getValueType();
16948       SDValue subVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, resVT,
16949                                        DAG.getUNDEF(resVT), Src,
16950                                        DAG.getIntPtrConstant(0, dl));
16951       SDValue immVal;
16952       if (Src.getSimpleValueType().is256BitVector() && resVT.is512BitVector())
16953         immVal = DAG.getConstant(0x44, dl, MVT::i8);
16954       else
16955         immVal = DAG.getConstant(0, dl, MVT::i8);
16956       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16957                                               subVec, subVec, immVal),
16958                                   Mask, Passthru, Subtarget, DAG);
16959     }
16960     default:
16961       break;
16962     }
16963   }
16964
16965   switch (IntNo) {
16966   default: return SDValue();    // Don't custom lower most intrinsics.
16967
16968   case Intrinsic::x86_avx2_permd:
16969   case Intrinsic::x86_avx2_permps:
16970     // Operands intentionally swapped. Mask is last operand to intrinsic,
16971     // but second operand for node/instruction.
16972     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16973                        Op.getOperand(2), Op.getOperand(1));
16974
16975   // ptest and testp intrinsics. The intrinsic these come from are designed to
16976   // return an integer value, not just an instruction so lower it to the ptest
16977   // or testp pattern and a setcc for the result.
16978   case Intrinsic::x86_sse41_ptestz:
16979   case Intrinsic::x86_sse41_ptestc:
16980   case Intrinsic::x86_sse41_ptestnzc:
16981   case Intrinsic::x86_avx_ptestz_256:
16982   case Intrinsic::x86_avx_ptestc_256:
16983   case Intrinsic::x86_avx_ptestnzc_256:
16984   case Intrinsic::x86_avx_vtestz_ps:
16985   case Intrinsic::x86_avx_vtestc_ps:
16986   case Intrinsic::x86_avx_vtestnzc_ps:
16987   case Intrinsic::x86_avx_vtestz_pd:
16988   case Intrinsic::x86_avx_vtestc_pd:
16989   case Intrinsic::x86_avx_vtestnzc_pd:
16990   case Intrinsic::x86_avx_vtestz_ps_256:
16991   case Intrinsic::x86_avx_vtestc_ps_256:
16992   case Intrinsic::x86_avx_vtestnzc_ps_256:
16993   case Intrinsic::x86_avx_vtestz_pd_256:
16994   case Intrinsic::x86_avx_vtestc_pd_256:
16995   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16996     bool IsTestPacked = false;
16997     unsigned X86CC;
16998     switch (IntNo) {
16999     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
17000     case Intrinsic::x86_avx_vtestz_ps:
17001     case Intrinsic::x86_avx_vtestz_pd:
17002     case Intrinsic::x86_avx_vtestz_ps_256:
17003     case Intrinsic::x86_avx_vtestz_pd_256:
17004       IsTestPacked = true; // Fallthrough
17005     case Intrinsic::x86_sse41_ptestz:
17006     case Intrinsic::x86_avx_ptestz_256:
17007       // ZF = 1
17008       X86CC = X86::COND_E;
17009       break;
17010     case Intrinsic::x86_avx_vtestc_ps:
17011     case Intrinsic::x86_avx_vtestc_pd:
17012     case Intrinsic::x86_avx_vtestc_ps_256:
17013     case Intrinsic::x86_avx_vtestc_pd_256:
17014       IsTestPacked = true; // Fallthrough
17015     case Intrinsic::x86_sse41_ptestc:
17016     case Intrinsic::x86_avx_ptestc_256:
17017       // CF = 1
17018       X86CC = X86::COND_B;
17019       break;
17020     case Intrinsic::x86_avx_vtestnzc_ps:
17021     case Intrinsic::x86_avx_vtestnzc_pd:
17022     case Intrinsic::x86_avx_vtestnzc_ps_256:
17023     case Intrinsic::x86_avx_vtestnzc_pd_256:
17024       IsTestPacked = true; // Fallthrough
17025     case Intrinsic::x86_sse41_ptestnzc:
17026     case Intrinsic::x86_avx_ptestnzc_256:
17027       // ZF and CF = 0
17028       X86CC = X86::COND_A;
17029       break;
17030     }
17031
17032     SDValue LHS = Op.getOperand(1);
17033     SDValue RHS = Op.getOperand(2);
17034     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
17035     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
17036     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
17037     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
17038     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17039   }
17040   case Intrinsic::x86_avx512_kortestz_w:
17041   case Intrinsic::x86_avx512_kortestc_w: {
17042     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
17043     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
17044     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
17045     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
17046     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
17047     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
17048     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17049   }
17050
17051   case Intrinsic::x86_sse42_pcmpistria128:
17052   case Intrinsic::x86_sse42_pcmpestria128:
17053   case Intrinsic::x86_sse42_pcmpistric128:
17054   case Intrinsic::x86_sse42_pcmpestric128:
17055   case Intrinsic::x86_sse42_pcmpistrio128:
17056   case Intrinsic::x86_sse42_pcmpestrio128:
17057   case Intrinsic::x86_sse42_pcmpistris128:
17058   case Intrinsic::x86_sse42_pcmpestris128:
17059   case Intrinsic::x86_sse42_pcmpistriz128:
17060   case Intrinsic::x86_sse42_pcmpestriz128: {
17061     unsigned Opcode;
17062     unsigned X86CC;
17063     switch (IntNo) {
17064     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17065     case Intrinsic::x86_sse42_pcmpistria128:
17066       Opcode = X86ISD::PCMPISTRI;
17067       X86CC = X86::COND_A;
17068       break;
17069     case Intrinsic::x86_sse42_pcmpestria128:
17070       Opcode = X86ISD::PCMPESTRI;
17071       X86CC = X86::COND_A;
17072       break;
17073     case Intrinsic::x86_sse42_pcmpistric128:
17074       Opcode = X86ISD::PCMPISTRI;
17075       X86CC = X86::COND_B;
17076       break;
17077     case Intrinsic::x86_sse42_pcmpestric128:
17078       Opcode = X86ISD::PCMPESTRI;
17079       X86CC = X86::COND_B;
17080       break;
17081     case Intrinsic::x86_sse42_pcmpistrio128:
17082       Opcode = X86ISD::PCMPISTRI;
17083       X86CC = X86::COND_O;
17084       break;
17085     case Intrinsic::x86_sse42_pcmpestrio128:
17086       Opcode = X86ISD::PCMPESTRI;
17087       X86CC = X86::COND_O;
17088       break;
17089     case Intrinsic::x86_sse42_pcmpistris128:
17090       Opcode = X86ISD::PCMPISTRI;
17091       X86CC = X86::COND_S;
17092       break;
17093     case Intrinsic::x86_sse42_pcmpestris128:
17094       Opcode = X86ISD::PCMPESTRI;
17095       X86CC = X86::COND_S;
17096       break;
17097     case Intrinsic::x86_sse42_pcmpistriz128:
17098       Opcode = X86ISD::PCMPISTRI;
17099       X86CC = X86::COND_E;
17100       break;
17101     case Intrinsic::x86_sse42_pcmpestriz128:
17102       Opcode = X86ISD::PCMPESTRI;
17103       X86CC = X86::COND_E;
17104       break;
17105     }
17106     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17107     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17108     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
17109     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17110                                 DAG.getConstant(X86CC, dl, MVT::i8),
17111                                 SDValue(PCMP.getNode(), 1));
17112     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17113   }
17114
17115   case Intrinsic::x86_sse42_pcmpistri128:
17116   case Intrinsic::x86_sse42_pcmpestri128: {
17117     unsigned Opcode;
17118     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
17119       Opcode = X86ISD::PCMPISTRI;
17120     else
17121       Opcode = X86ISD::PCMPESTRI;
17122
17123     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17124     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17125     return DAG.getNode(Opcode, dl, VTs, NewOps);
17126   }
17127
17128   case Intrinsic::x86_seh_lsda: {
17129     // Compute the symbol for the LSDA. We know it'll get emitted later.
17130     MachineFunction &MF = DAG.getMachineFunction();
17131     SDValue Op1 = Op.getOperand(1);
17132     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
17133     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
17134         GlobalValue::getRealLinkageName(Fn->getName()));
17135
17136     // Generate a simple absolute symbol reference. This intrinsic is only
17137     // supported on 32-bit Windows, which isn't PIC.
17138     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
17139     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
17140   }
17141
17142   case Intrinsic::x86_seh_recoverfp: {
17143     SDValue FnOp = Op.getOperand(1);
17144     SDValue IncomingFPOp = Op.getOperand(2);
17145     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
17146     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
17147     if (!Fn)
17148       report_fatal_error(
17149           "llvm.x86.seh.recoverfp must take a function as the first argument");
17150     return recoverFramePointer(DAG, Fn, IncomingFPOp);
17151   }
17152
17153   case Intrinsic::localaddress: {
17154     // Returns one of the stack, base, or frame pointer registers, depending on
17155     // which is used to reference local variables.
17156     MachineFunction &MF = DAG.getMachineFunction();
17157     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17158     unsigned Reg;
17159     if (RegInfo->hasBasePointer(MF))
17160       Reg = RegInfo->getBaseRegister();
17161     else // This function handles the SP or FP case.
17162       Reg = RegInfo->getPtrSizedFrameRegister(MF);
17163     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
17164   }
17165   }
17166 }
17167
17168 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17169                               SDValue Src, SDValue Mask, SDValue Base,
17170                               SDValue Index, SDValue ScaleOp, SDValue Chain,
17171                               const X86Subtarget * Subtarget) {
17172   SDLoc dl(Op);
17173   auto *C = cast<ConstantSDNode>(ScaleOp);
17174   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17175   MVT MaskVT = MVT::getVectorVT(MVT::i1,
17176                              Index.getSimpleValueType().getVectorNumElements());
17177   SDValue MaskInReg;
17178   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17179   if (MaskC)
17180     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17181   else {
17182     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17183                                      Mask.getSimpleValueType().getSizeInBits());
17184
17185     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17186     // are extracted by EXTRACT_SUBVECTOR.
17187     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17188                             DAG.getBitcast(BitcastVT, Mask),
17189                             DAG.getIntPtrConstant(0, dl));
17190   }
17191   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
17192   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17193   SDValue Segment = DAG.getRegister(0, MVT::i32);
17194   if (Src.getOpcode() == ISD::UNDEF)
17195     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
17196   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17197   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17198   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
17199   return DAG.getMergeValues(RetOps, dl);
17200 }
17201
17202 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17203                                SDValue Src, SDValue Mask, SDValue Base,
17204                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
17205   SDLoc dl(Op);
17206   auto *C = cast<ConstantSDNode>(ScaleOp);
17207   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17208   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17209   SDValue Segment = DAG.getRegister(0, MVT::i32);
17210   MVT MaskVT = MVT::getVectorVT(MVT::i1,
17211                              Index.getSimpleValueType().getVectorNumElements());
17212   SDValue MaskInReg;
17213   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17214   if (MaskC)
17215     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17216   else {
17217     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17218                                      Mask.getSimpleValueType().getSizeInBits());
17219
17220     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17221     // are extracted by EXTRACT_SUBVECTOR.
17222     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17223                             DAG.getBitcast(BitcastVT, Mask),
17224                             DAG.getIntPtrConstant(0, dl));
17225   }
17226   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
17227   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
17228   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17229   return SDValue(Res, 1);
17230 }
17231
17232 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17233                                SDValue Mask, SDValue Base, SDValue Index,
17234                                SDValue ScaleOp, SDValue Chain) {
17235   SDLoc dl(Op);
17236   auto *C = cast<ConstantSDNode>(ScaleOp);
17237   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17238   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17239   SDValue Segment = DAG.getRegister(0, MVT::i32);
17240   MVT MaskVT =
17241     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
17242   SDValue MaskInReg;
17243   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17244   if (MaskC)
17245     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17246   else
17247     MaskInReg = DAG.getBitcast(MaskVT, Mask);
17248   //SDVTList VTs = DAG.getVTList(MVT::Other);
17249   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17250   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
17251   return SDValue(Res, 0);
17252 }
17253
17254 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
17255 // read performance monitor counters (x86_rdpmc).
17256 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
17257                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17258                               SmallVectorImpl<SDValue> &Results) {
17259   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17260   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17261   SDValue LO, HI;
17262
17263   // The ECX register is used to select the index of the performance counter
17264   // to read.
17265   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
17266                                    N->getOperand(2));
17267   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
17268
17269   // Reads the content of a 64-bit performance counter and returns it in the
17270   // registers EDX:EAX.
17271   if (Subtarget->is64Bit()) {
17272     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17273     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17274                             LO.getValue(2));
17275   } else {
17276     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17277     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17278                             LO.getValue(2));
17279   }
17280   Chain = HI.getValue(1);
17281
17282   if (Subtarget->is64Bit()) {
17283     // The EAX register is loaded with the low-order 32 bits. The EDX register
17284     // is loaded with the supported high-order bits of the counter.
17285     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17286                               DAG.getConstant(32, DL, MVT::i8));
17287     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17288     Results.push_back(Chain);
17289     return;
17290   }
17291
17292   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17293   SDValue Ops[] = { LO, HI };
17294   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17295   Results.push_back(Pair);
17296   Results.push_back(Chain);
17297 }
17298
17299 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17300 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17301 // also used to custom lower READCYCLECOUNTER nodes.
17302 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17303                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17304                               SmallVectorImpl<SDValue> &Results) {
17305   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17306   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17307   SDValue LO, HI;
17308
17309   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17310   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17311   // and the EAX register is loaded with the low-order 32 bits.
17312   if (Subtarget->is64Bit()) {
17313     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17314     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17315                             LO.getValue(2));
17316   } else {
17317     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17318     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17319                             LO.getValue(2));
17320   }
17321   SDValue Chain = HI.getValue(1);
17322
17323   if (Opcode == X86ISD::RDTSCP_DAG) {
17324     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17325
17326     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17327     // the ECX register. Add 'ecx' explicitly to the chain.
17328     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17329                                      HI.getValue(2));
17330     // Explicitly store the content of ECX at the location passed in input
17331     // to the 'rdtscp' intrinsic.
17332     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17333                          MachinePointerInfo(), false, false, 0);
17334   }
17335
17336   if (Subtarget->is64Bit()) {
17337     // The EDX register is loaded with the high-order 32 bits of the MSR, and
17338     // the EAX register is loaded with the low-order 32 bits.
17339     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17340                               DAG.getConstant(32, DL, MVT::i8));
17341     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17342     Results.push_back(Chain);
17343     return;
17344   }
17345
17346   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17347   SDValue Ops[] = { LO, HI };
17348   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17349   Results.push_back(Pair);
17350   Results.push_back(Chain);
17351 }
17352
17353 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17354                                      SelectionDAG &DAG) {
17355   SmallVector<SDValue, 2> Results;
17356   SDLoc DL(Op);
17357   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17358                           Results);
17359   return DAG.getMergeValues(Results, DL);
17360 }
17361
17362 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
17363   MachineFunction &MF = DAG.getMachineFunction();
17364   SDValue Chain = Op.getOperand(0);
17365   SDValue RegNode = Op.getOperand(2);
17366   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
17367   if (!EHInfo)
17368     report_fatal_error("EH registrations only live in functions using WinEH");
17369
17370   // Cast the operand to an alloca, and remember the frame index.
17371   auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
17372   if (!FINode)
17373     report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
17374   EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
17375
17376   // Return the chain operand without making any DAG nodes.
17377   return Chain;
17378 }
17379
17380 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
17381 /// return truncate Store/MaskedStore Node
17382 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
17383                                                SelectionDAG &DAG,
17384                                                MVT ElementType) {
17385   SDLoc dl(Op);
17386   SDValue Mask = Op.getOperand(4);
17387   SDValue DataToTruncate = Op.getOperand(3);
17388   SDValue Addr = Op.getOperand(2);
17389   SDValue Chain = Op.getOperand(0);
17390
17391   MVT VT  = DataToTruncate.getSimpleValueType();
17392   MVT SVT = MVT::getVectorVT(ElementType, VT.getVectorNumElements());
17393
17394   if (isAllOnesConstant(Mask)) // return just a truncate store
17395     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
17396                              MachinePointerInfo(), SVT, false, false,
17397                              SVT.getScalarSizeInBits()/8);
17398
17399   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17400   MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17401                                    Mask.getSimpleValueType().getSizeInBits());
17402   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17403   // are extracted by EXTRACT_SUBVECTOR.
17404   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17405                               DAG.getBitcast(BitcastVT, Mask),
17406                               DAG.getIntPtrConstant(0, dl));
17407
17408   MachineMemOperand *MMO = DAG.getMachineFunction().
17409     getMachineMemOperand(MachinePointerInfo(),
17410                          MachineMemOperand::MOStore, SVT.getStoreSize(),
17411                          SVT.getScalarSizeInBits()/8);
17412
17413   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
17414                             VMask, SVT, MMO, true);
17415 }
17416
17417 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17418                                       SelectionDAG &DAG) {
17419   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17420
17421   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17422   if (!IntrData) {
17423     if (IntNo == llvm::Intrinsic::x86_seh_ehregnode)
17424       return MarkEHRegistrationNode(Op, DAG);
17425     if (IntNo == llvm::Intrinsic::x86_flags_read_u32 ||
17426         IntNo == llvm::Intrinsic::x86_flags_read_u64 ||
17427         IntNo == llvm::Intrinsic::x86_flags_write_u32 ||
17428         IntNo == llvm::Intrinsic::x86_flags_write_u64) {
17429       // We need a frame pointer because this will get lowered to a PUSH/POP
17430       // sequence.
17431       MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17432       MFI->setHasOpaqueSPAdjustment(true);
17433       // Don't do anything here, we will expand these intrinsics out later
17434       // during ExpandISelPseudos in EmitInstrWithCustomInserter.
17435       return SDValue();
17436     }
17437     return SDValue();
17438   }
17439
17440   SDLoc dl(Op);
17441   switch(IntrData->Type) {
17442   default: llvm_unreachable("Unknown Intrinsic Type");
17443   case RDSEED:
17444   case RDRAND: {
17445     // Emit the node with the right value type.
17446     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17447     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17448
17449     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17450     // Otherwise return the value from Rand, which is always 0, casted to i32.
17451     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17452                       DAG.getConstant(1, dl, Op->getValueType(1)),
17453                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
17454                       SDValue(Result.getNode(), 1) };
17455     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17456                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
17457                                   Ops);
17458
17459     // Return { result, isValid, chain }.
17460     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17461                        SDValue(Result.getNode(), 2));
17462   }
17463   case GATHER: {
17464   //gather(v1, mask, index, base, scale);
17465     SDValue Chain = Op.getOperand(0);
17466     SDValue Src   = Op.getOperand(2);
17467     SDValue Base  = Op.getOperand(3);
17468     SDValue Index = Op.getOperand(4);
17469     SDValue Mask  = Op.getOperand(5);
17470     SDValue Scale = Op.getOperand(6);
17471     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17472                          Chain, Subtarget);
17473   }
17474   case SCATTER: {
17475   //scatter(base, mask, index, v1, scale);
17476     SDValue Chain = Op.getOperand(0);
17477     SDValue Base  = Op.getOperand(2);
17478     SDValue Mask  = Op.getOperand(3);
17479     SDValue Index = Op.getOperand(4);
17480     SDValue Src   = Op.getOperand(5);
17481     SDValue Scale = Op.getOperand(6);
17482     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17483                           Scale, Chain);
17484   }
17485   case PREFETCH: {
17486     SDValue Hint = Op.getOperand(6);
17487     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17488     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17489     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17490     SDValue Chain = Op.getOperand(0);
17491     SDValue Mask  = Op.getOperand(2);
17492     SDValue Index = Op.getOperand(3);
17493     SDValue Base  = Op.getOperand(4);
17494     SDValue Scale = Op.getOperand(5);
17495     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17496   }
17497   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17498   case RDTSC: {
17499     SmallVector<SDValue, 2> Results;
17500     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17501                             Results);
17502     return DAG.getMergeValues(Results, dl);
17503   }
17504   // Read Performance Monitoring Counters.
17505   case RDPMC: {
17506     SmallVector<SDValue, 2> Results;
17507     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17508     return DAG.getMergeValues(Results, dl);
17509   }
17510   // XTEST intrinsics.
17511   case XTEST: {
17512     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17513     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17514     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17515                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17516                                 InTrans);
17517     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17518     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17519                        Ret, SDValue(InTrans.getNode(), 1));
17520   }
17521   // ADC/ADCX/SBB
17522   case ADX: {
17523     SmallVector<SDValue, 2> Results;
17524     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17525     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17526     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17527                                 DAG.getConstant(-1, dl, MVT::i8));
17528     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17529                               Op.getOperand(4), GenCF.getValue(1));
17530     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17531                                  Op.getOperand(5), MachinePointerInfo(),
17532                                  false, false, 0);
17533     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17534                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17535                                 Res.getValue(1));
17536     Results.push_back(SetCC);
17537     Results.push_back(Store);
17538     return DAG.getMergeValues(Results, dl);
17539   }
17540   case COMPRESS_TO_MEM: {
17541     SDLoc dl(Op);
17542     SDValue Mask = Op.getOperand(4);
17543     SDValue DataToCompress = Op.getOperand(3);
17544     SDValue Addr = Op.getOperand(2);
17545     SDValue Chain = Op.getOperand(0);
17546
17547     MVT VT = DataToCompress.getSimpleValueType();
17548     if (isAllOnesConstant(Mask)) // return just a store
17549       return DAG.getStore(Chain, dl, DataToCompress, Addr,
17550                           MachinePointerInfo(), false, false,
17551                           VT.getScalarSizeInBits()/8);
17552
17553     SDValue Compressed =
17554       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17555                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17556     return DAG.getStore(Chain, dl, Compressed, Addr,
17557                         MachinePointerInfo(), false, false,
17558                         VT.getScalarSizeInBits()/8);
17559   }
17560   case TRUNCATE_TO_MEM_VI8:
17561     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17562   case TRUNCATE_TO_MEM_VI16:
17563     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17564   case TRUNCATE_TO_MEM_VI32:
17565     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17566   case EXPAND_FROM_MEM: {
17567     SDLoc dl(Op);
17568     SDValue Mask = Op.getOperand(4);
17569     SDValue PassThru = Op.getOperand(3);
17570     SDValue Addr = Op.getOperand(2);
17571     SDValue Chain = Op.getOperand(0);
17572     MVT VT = Op.getSimpleValueType();
17573
17574     if (isAllOnesConstant(Mask)) // return just a load
17575       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17576                          false, VT.getScalarSizeInBits()/8);
17577
17578     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17579                                        false, false, false,
17580                                        VT.getScalarSizeInBits()/8);
17581
17582     SDValue Results[] = {
17583       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17584                            Mask, PassThru, Subtarget, DAG), Chain};
17585     return DAG.getMergeValues(Results, dl);
17586   }
17587   }
17588 }
17589
17590 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17591                                            SelectionDAG &DAG) const {
17592   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17593   MFI->setReturnAddressIsTaken(true);
17594
17595   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17596     return SDValue();
17597
17598   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17599   SDLoc dl(Op);
17600   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17601
17602   if (Depth > 0) {
17603     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17604     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17605     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17606     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17607                        DAG.getNode(ISD::ADD, dl, PtrVT,
17608                                    FrameAddr, Offset),
17609                        MachinePointerInfo(), false, false, false, 0);
17610   }
17611
17612   // Just load the return address.
17613   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17614   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17615                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17616 }
17617
17618 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17619   MachineFunction &MF = DAG.getMachineFunction();
17620   MachineFrameInfo *MFI = MF.getFrameInfo();
17621   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17622   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17623   EVT VT = Op.getValueType();
17624
17625   MFI->setFrameAddressIsTaken(true);
17626
17627   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17628     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
17629     // is not possible to crawl up the stack without looking at the unwind codes
17630     // simultaneously.
17631     int FrameAddrIndex = FuncInfo->getFAIndex();
17632     if (!FrameAddrIndex) {
17633       // Set up a frame object for the return address.
17634       unsigned SlotSize = RegInfo->getSlotSize();
17635       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17636           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17637       FuncInfo->setFAIndex(FrameAddrIndex);
17638     }
17639     return DAG.getFrameIndex(FrameAddrIndex, VT);
17640   }
17641
17642   unsigned FrameReg =
17643       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17644   SDLoc dl(Op);  // FIXME probably not meaningful
17645   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17646   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17647           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17648          "Invalid Frame Register!");
17649   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17650   while (Depth--)
17651     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17652                             MachinePointerInfo(),
17653                             false, false, false, 0);
17654   return FrameAddr;
17655 }
17656
17657 // FIXME? Maybe this could be a TableGen attribute on some registers and
17658 // this table could be generated automatically from RegInfo.
17659 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17660                                               SelectionDAG &DAG) const {
17661   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17662   const MachineFunction &MF = DAG.getMachineFunction();
17663
17664   unsigned Reg = StringSwitch<unsigned>(RegName)
17665                        .Case("esp", X86::ESP)
17666                        .Case("rsp", X86::RSP)
17667                        .Case("ebp", X86::EBP)
17668                        .Case("rbp", X86::RBP)
17669                        .Default(0);
17670
17671   if (Reg == X86::EBP || Reg == X86::RBP) {
17672     if (!TFI.hasFP(MF))
17673       report_fatal_error("register " + StringRef(RegName) +
17674                          " is allocatable: function has no frame pointer");
17675 #ifndef NDEBUG
17676     else {
17677       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17678       unsigned FrameReg =
17679           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17680       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17681              "Invalid Frame Register!");
17682     }
17683 #endif
17684   }
17685
17686   if (Reg)
17687     return Reg;
17688
17689   report_fatal_error("Invalid register name global variable");
17690 }
17691
17692 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17693                                                      SelectionDAG &DAG) const {
17694   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17695   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17696 }
17697
17698 unsigned X86TargetLowering::getExceptionPointerRegister(
17699     const Constant *PersonalityFn) const {
17700   if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
17701     return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17702
17703   return Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
17704 }
17705
17706 unsigned X86TargetLowering::getExceptionSelectorRegister(
17707     const Constant *PersonalityFn) const {
17708   // Funclet personalities don't use selectors (the runtime does the selection).
17709   assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
17710   return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17711 }
17712
17713 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17714   SDValue Chain     = Op.getOperand(0);
17715   SDValue Offset    = Op.getOperand(1);
17716   SDValue Handler   = Op.getOperand(2);
17717   SDLoc dl      (Op);
17718
17719   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17720   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17721   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17722   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17723           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17724          "Invalid Frame Register!");
17725   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17726   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17727
17728   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17729                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17730                                                        dl));
17731   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17732   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17733                        false, false, 0);
17734   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17735
17736   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17737                      DAG.getRegister(StoreAddrReg, PtrVT));
17738 }
17739
17740 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17741                                                SelectionDAG &DAG) const {
17742   SDLoc DL(Op);
17743   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17744                      DAG.getVTList(MVT::i32, MVT::Other),
17745                      Op.getOperand(0), Op.getOperand(1));
17746 }
17747
17748 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17749                                                 SelectionDAG &DAG) const {
17750   SDLoc DL(Op);
17751   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17752                      Op.getOperand(0), Op.getOperand(1));
17753 }
17754
17755 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17756   return Op.getOperand(0);
17757 }
17758
17759 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17760                                                 SelectionDAG &DAG) const {
17761   SDValue Root = Op.getOperand(0);
17762   SDValue Trmp = Op.getOperand(1); // trampoline
17763   SDValue FPtr = Op.getOperand(2); // nested function
17764   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17765   SDLoc dl (Op);
17766
17767   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17768   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17769
17770   if (Subtarget->is64Bit()) {
17771     SDValue OutChains[6];
17772
17773     // Large code-model.
17774     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17775     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17776
17777     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17778     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17779
17780     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17781
17782     // Load the pointer to the nested function into R11.
17783     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17784     SDValue Addr = Trmp;
17785     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17786                                 Addr, MachinePointerInfo(TrmpAddr),
17787                                 false, false, 0);
17788
17789     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17790                        DAG.getConstant(2, dl, MVT::i64));
17791     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17792                                 MachinePointerInfo(TrmpAddr, 2),
17793                                 false, false, 2);
17794
17795     // Load the 'nest' parameter value into R10.
17796     // R10 is specified in X86CallingConv.td
17797     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17798     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17799                        DAG.getConstant(10, dl, MVT::i64));
17800     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17801                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17802                                 false, false, 0);
17803
17804     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17805                        DAG.getConstant(12, dl, MVT::i64));
17806     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17807                                 MachinePointerInfo(TrmpAddr, 12),
17808                                 false, false, 2);
17809
17810     // Jump to the nested function.
17811     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17812     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17813                        DAG.getConstant(20, dl, MVT::i64));
17814     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17815                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17816                                 false, false, 0);
17817
17818     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17819     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17820                        DAG.getConstant(22, dl, MVT::i64));
17821     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17822                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17823                                 false, false, 0);
17824
17825     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17826   } else {
17827     const Function *Func =
17828       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17829     CallingConv::ID CC = Func->getCallingConv();
17830     unsigned NestReg;
17831
17832     switch (CC) {
17833     default:
17834       llvm_unreachable("Unsupported calling convention");
17835     case CallingConv::C:
17836     case CallingConv::X86_StdCall: {
17837       // Pass 'nest' parameter in ECX.
17838       // Must be kept in sync with X86CallingConv.td
17839       NestReg = X86::ECX;
17840
17841       // Check that ECX wasn't needed by an 'inreg' parameter.
17842       FunctionType *FTy = Func->getFunctionType();
17843       const AttributeSet &Attrs = Func->getAttributes();
17844
17845       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17846         unsigned InRegCount = 0;
17847         unsigned Idx = 1;
17848
17849         for (FunctionType::param_iterator I = FTy->param_begin(),
17850              E = FTy->param_end(); I != E; ++I, ++Idx)
17851           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17852             auto &DL = DAG.getDataLayout();
17853             // FIXME: should only count parameters that are lowered to integers.
17854             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17855           }
17856
17857         if (InRegCount > 2) {
17858           report_fatal_error("Nest register in use - reduce number of inreg"
17859                              " parameters!");
17860         }
17861       }
17862       break;
17863     }
17864     case CallingConv::X86_FastCall:
17865     case CallingConv::X86_ThisCall:
17866     case CallingConv::Fast:
17867       // Pass 'nest' parameter in EAX.
17868       // Must be kept in sync with X86CallingConv.td
17869       NestReg = X86::EAX;
17870       break;
17871     }
17872
17873     SDValue OutChains[4];
17874     SDValue Addr, Disp;
17875
17876     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17877                        DAG.getConstant(10, dl, MVT::i32));
17878     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17879
17880     // This is storing the opcode for MOV32ri.
17881     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17882     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17883     OutChains[0] = DAG.getStore(Root, dl,
17884                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17885                                 Trmp, MachinePointerInfo(TrmpAddr),
17886                                 false, false, 0);
17887
17888     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17889                        DAG.getConstant(1, dl, MVT::i32));
17890     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17891                                 MachinePointerInfo(TrmpAddr, 1),
17892                                 false, false, 1);
17893
17894     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17895     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17896                        DAG.getConstant(5, dl, MVT::i32));
17897     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17898                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17899                                 false, false, 1);
17900
17901     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17902                        DAG.getConstant(6, dl, MVT::i32));
17903     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17904                                 MachinePointerInfo(TrmpAddr, 6),
17905                                 false, false, 1);
17906
17907     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17908   }
17909 }
17910
17911 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17912                                             SelectionDAG &DAG) const {
17913   /*
17914    The rounding mode is in bits 11:10 of FPSR, and has the following
17915    settings:
17916      00 Round to nearest
17917      01 Round to -inf
17918      10 Round to +inf
17919      11 Round to 0
17920
17921   FLT_ROUNDS, on the other hand, expects the following:
17922     -1 Undefined
17923      0 Round to 0
17924      1 Round to nearest
17925      2 Round to +inf
17926      3 Round to -inf
17927
17928   To perform the conversion, we do:
17929     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17930   */
17931
17932   MachineFunction &MF = DAG.getMachineFunction();
17933   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17934   unsigned StackAlignment = TFI.getStackAlignment();
17935   MVT VT = Op.getSimpleValueType();
17936   SDLoc DL(Op);
17937
17938   // Save FP Control Word to stack slot
17939   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17940   SDValue StackSlot =
17941       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17942
17943   MachineMemOperand *MMO =
17944       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17945                               MachineMemOperand::MOStore, 2, 2);
17946
17947   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17948   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17949                                           DAG.getVTList(MVT::Other),
17950                                           Ops, MVT::i16, MMO);
17951
17952   // Load FP Control Word from stack slot
17953   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17954                             MachinePointerInfo(), false, false, false, 0);
17955
17956   // Transform as necessary
17957   SDValue CWD1 =
17958     DAG.getNode(ISD::SRL, DL, MVT::i16,
17959                 DAG.getNode(ISD::AND, DL, MVT::i16,
17960                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17961                 DAG.getConstant(11, DL, MVT::i8));
17962   SDValue CWD2 =
17963     DAG.getNode(ISD::SRL, DL, MVT::i16,
17964                 DAG.getNode(ISD::AND, DL, MVT::i16,
17965                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17966                 DAG.getConstant(9, DL, MVT::i8));
17967
17968   SDValue RetVal =
17969     DAG.getNode(ISD::AND, DL, MVT::i16,
17970                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17971                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17972                             DAG.getConstant(1, DL, MVT::i16)),
17973                 DAG.getConstant(3, DL, MVT::i16));
17974
17975   return DAG.getNode((VT.getSizeInBits() < 16 ?
17976                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17977 }
17978
17979 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
17980 //
17981 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
17982 //    to 512-bit vector.
17983 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
17984 //    ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
17985 //    split the vector, perform operation on it's Lo a Hi part and
17986 //    concatenate the results.
17987 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
17988   SDLoc dl(Op);
17989   MVT VT = Op.getSimpleValueType();
17990   MVT EltVT = VT.getVectorElementType();
17991   unsigned NumElems = VT.getVectorNumElements();
17992
17993   if (EltVT == MVT::i64 || EltVT == MVT::i32) {
17994     // Extend to 512 bit vector.
17995     assert((VT.is256BitVector() || VT.is128BitVector()) &&
17996               "Unsupported value type for operation");
17997
17998     MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
17999     SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
18000                                  DAG.getUNDEF(NewVT),
18001                                  Op.getOperand(0),
18002                                  DAG.getIntPtrConstant(0, dl));
18003     SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
18004
18005     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
18006                        DAG.getIntPtrConstant(0, dl));
18007   }
18008
18009   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
18010           "Unsupported element type");
18011
18012   if (16 < NumElems) {
18013     // Split vector, it's Lo and Hi parts will be handled in next iteration.
18014     SDValue Lo, Hi;
18015     std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
18016     MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
18017
18018     Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
18019     Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
18020
18021     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
18022   }
18023
18024   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
18025
18026   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
18027           "Unsupported value type for operation");
18028
18029   // Use native supported vector instruction vplzcntd.
18030   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
18031   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
18032   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
18033   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
18034
18035   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
18036 }
18037
18038 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
18039                          SelectionDAG &DAG) {
18040   MVT VT = Op.getSimpleValueType();
18041   MVT OpVT = VT;
18042   unsigned NumBits = VT.getSizeInBits();
18043   SDLoc dl(Op);
18044
18045   if (VT.isVector() && Subtarget->hasAVX512())
18046     return LowerVectorCTLZ_AVX512(Op, DAG);
18047
18048   Op = Op.getOperand(0);
18049   if (VT == MVT::i8) {
18050     // Zero extend to i32 since there is not an i8 bsr.
18051     OpVT = MVT::i32;
18052     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18053   }
18054
18055   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
18056   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18057   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18058
18059   // If src is zero (i.e. bsr sets ZF), returns NumBits.
18060   SDValue Ops[] = {
18061     Op,
18062     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
18063     DAG.getConstant(X86::COND_E, dl, MVT::i8),
18064     Op.getValue(1)
18065   };
18066   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
18067
18068   // Finally xor with NumBits-1.
18069   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18070                    DAG.getConstant(NumBits - 1, dl, OpVT));
18071
18072   if (VT == MVT::i8)
18073     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18074   return Op;
18075 }
18076
18077 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
18078                                     SelectionDAG &DAG) {
18079   MVT VT = Op.getSimpleValueType();
18080   EVT OpVT = VT;
18081   unsigned NumBits = VT.getSizeInBits();
18082   SDLoc dl(Op);
18083
18084   Op = Op.getOperand(0);
18085   if (VT == MVT::i8) {
18086     // Zero extend to i32 since there is not an i8 bsr.
18087     OpVT = MVT::i32;
18088     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18089   }
18090
18091   // Issue a bsr (scan bits in reverse).
18092   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18093   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18094
18095   // And xor with NumBits-1.
18096   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18097                    DAG.getConstant(NumBits - 1, dl, OpVT));
18098
18099   if (VT == MVT::i8)
18100     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18101   return Op;
18102 }
18103
18104 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
18105   MVT VT = Op.getSimpleValueType();
18106   unsigned NumBits = VT.getScalarSizeInBits();
18107   SDLoc dl(Op);
18108
18109   if (VT.isVector()) {
18110     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18111
18112     SDValue N0 = Op.getOperand(0);
18113     SDValue Zero = DAG.getConstant(0, dl, VT);
18114
18115     // lsb(x) = (x & -x)
18116     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
18117                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
18118
18119     // cttz_undef(x) = (width - 1) - ctlz(lsb)
18120     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
18121         TLI.isOperationLegal(ISD::CTLZ, VT)) {
18122       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
18123       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
18124                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
18125     }
18126
18127     // cttz(x) = ctpop(lsb - 1)
18128     SDValue One = DAG.getConstant(1, dl, VT);
18129     return DAG.getNode(ISD::CTPOP, dl, VT,
18130                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
18131   }
18132
18133   assert(Op.getOpcode() == ISD::CTTZ &&
18134          "Only scalar CTTZ requires custom lowering");
18135
18136   // Issue a bsf (scan bits forward) which also sets EFLAGS.
18137   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18138   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
18139
18140   // If src is zero (i.e. bsf sets ZF), returns NumBits.
18141   SDValue Ops[] = {
18142     Op,
18143     DAG.getConstant(NumBits, dl, VT),
18144     DAG.getConstant(X86::COND_E, dl, MVT::i8),
18145     Op.getValue(1)
18146   };
18147   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
18148 }
18149
18150 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
18151 // ones, and then concatenate the result back.
18152 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
18153   MVT VT = Op.getSimpleValueType();
18154
18155   assert(VT.is256BitVector() && VT.isInteger() &&
18156          "Unsupported value type for operation");
18157
18158   unsigned NumElems = VT.getVectorNumElements();
18159   SDLoc dl(Op);
18160
18161   // Extract the LHS vectors
18162   SDValue LHS = Op.getOperand(0);
18163   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18164   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18165
18166   // Extract the RHS vectors
18167   SDValue RHS = Op.getOperand(1);
18168   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
18169   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
18170
18171   MVT EltVT = VT.getVectorElementType();
18172   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18173
18174   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18175                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
18176                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
18177 }
18178
18179 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
18180   if (Op.getValueType() == MVT::i1)
18181     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18182                        Op.getOperand(0), Op.getOperand(1));
18183   assert(Op.getSimpleValueType().is256BitVector() &&
18184          Op.getSimpleValueType().isInteger() &&
18185          "Only handle AVX 256-bit vector integer operation");
18186   return Lower256IntArith(Op, DAG);
18187 }
18188
18189 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
18190   if (Op.getValueType() == MVT::i1)
18191     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18192                        Op.getOperand(0), Op.getOperand(1));
18193   assert(Op.getSimpleValueType().is256BitVector() &&
18194          Op.getSimpleValueType().isInteger() &&
18195          "Only handle AVX 256-bit vector integer operation");
18196   return Lower256IntArith(Op, DAG);
18197 }
18198
18199 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
18200   assert(Op.getSimpleValueType().is256BitVector() &&
18201          Op.getSimpleValueType().isInteger() &&
18202          "Only handle AVX 256-bit vector integer operation");
18203   return Lower256IntArith(Op, DAG);
18204 }
18205
18206 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
18207                         SelectionDAG &DAG) {
18208   SDLoc dl(Op);
18209   MVT VT = Op.getSimpleValueType();
18210
18211   if (VT == MVT::i1)
18212     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
18213
18214   // Decompose 256-bit ops into smaller 128-bit ops.
18215   if (VT.is256BitVector() && !Subtarget->hasInt256())
18216     return Lower256IntArith(Op, DAG);
18217
18218   SDValue A = Op.getOperand(0);
18219   SDValue B = Op.getOperand(1);
18220
18221   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
18222   // pairs, multiply and truncate.
18223   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
18224     if (Subtarget->hasInt256()) {
18225       if (VT == MVT::v32i8) {
18226         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
18227         SDValue Lo = DAG.getIntPtrConstant(0, dl);
18228         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
18229         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
18230         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
18231         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
18232         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
18233         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18234                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
18235                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
18236       }
18237
18238       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
18239       return DAG.getNode(
18240           ISD::TRUNCATE, dl, VT,
18241           DAG.getNode(ISD::MUL, dl, ExVT,
18242                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
18243                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
18244     }
18245
18246     assert(VT == MVT::v16i8 &&
18247            "Pre-AVX2 support only supports v16i8 multiplication");
18248     MVT ExVT = MVT::v8i16;
18249
18250     // Extract the lo parts and sign extend to i16
18251     SDValue ALo, BLo;
18252     if (Subtarget->hasSSE41()) {
18253       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
18254       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
18255     } else {
18256       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
18257                               -1, 4, -1, 5, -1, 6, -1, 7};
18258       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18259       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18260       ALo = DAG.getBitcast(ExVT, ALo);
18261       BLo = DAG.getBitcast(ExVT, BLo);
18262       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
18263       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
18264     }
18265
18266     // Extract the hi parts and sign extend to i16
18267     SDValue AHi, BHi;
18268     if (Subtarget->hasSSE41()) {
18269       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
18270                               -1, -1, -1, -1, -1, -1, -1, -1};
18271       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18272       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18273       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
18274       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
18275     } else {
18276       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
18277                               -1, 12, -1, 13, -1, 14, -1, 15};
18278       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18279       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18280       AHi = DAG.getBitcast(ExVT, AHi);
18281       BHi = DAG.getBitcast(ExVT, BHi);
18282       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
18283       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
18284     }
18285
18286     // Multiply, mask the lower 8bits of the lo/hi results and pack
18287     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
18288     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
18289     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
18290     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
18291     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18292   }
18293
18294   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
18295   if (VT == MVT::v4i32) {
18296     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
18297            "Should not custom lower when pmuldq is available!");
18298
18299     // Extract the odd parts.
18300     static const int UnpackMask[] = { 1, -1, 3, -1 };
18301     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18302     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18303
18304     // Multiply the even parts.
18305     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18306     // Now multiply odd parts.
18307     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18308
18309     Evens = DAG.getBitcast(VT, Evens);
18310     Odds = DAG.getBitcast(VT, Odds);
18311
18312     // Merge the two vectors back together with a shuffle. This expands into 2
18313     // shuffles.
18314     static const int ShufMask[] = { 0, 4, 2, 6 };
18315     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18316   }
18317
18318   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18319          "Only know how to lower V2I64/V4I64/V8I64 multiply");
18320
18321   //  Ahi = psrlqi(a, 32);
18322   //  Bhi = psrlqi(b, 32);
18323   //
18324   //  AloBlo = pmuludq(a, b);
18325   //  AloBhi = pmuludq(a, Bhi);
18326   //  AhiBlo = pmuludq(Ahi, b);
18327
18328   //  AloBhi = psllqi(AloBhi, 32);
18329   //  AhiBlo = psllqi(AhiBlo, 32);
18330   //  return AloBlo + AloBhi + AhiBlo;
18331
18332   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18333   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18334
18335   SDValue AhiBlo = Ahi;
18336   SDValue AloBhi = Bhi;
18337   // Bit cast to 32-bit vectors for MULUDQ
18338   MVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18339                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18340   A = DAG.getBitcast(MulVT, A);
18341   B = DAG.getBitcast(MulVT, B);
18342   Ahi = DAG.getBitcast(MulVT, Ahi);
18343   Bhi = DAG.getBitcast(MulVT, Bhi);
18344
18345   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18346   // After shifting right const values the result may be all-zero.
18347   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
18348     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18349     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18350   }
18351   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
18352     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18353     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18354   }
18355
18356   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18357   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18358 }
18359
18360 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18361   assert(Subtarget->isTargetWin64() && "Unexpected target");
18362   EVT VT = Op.getValueType();
18363   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18364          "Unexpected return type for lowering");
18365
18366   RTLIB::Libcall LC;
18367   bool isSigned;
18368   switch (Op->getOpcode()) {
18369   default: llvm_unreachable("Unexpected request for libcall!");
18370   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
18371   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
18372   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
18373   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
18374   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
18375   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18376   }
18377
18378   SDLoc dl(Op);
18379   SDValue InChain = DAG.getEntryNode();
18380
18381   TargetLowering::ArgListTy Args;
18382   TargetLowering::ArgListEntry Entry;
18383   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18384     EVT ArgVT = Op->getOperand(i).getValueType();
18385     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18386            "Unexpected argument type for lowering");
18387     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18388     Entry.Node = StackPtr;
18389     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18390                            false, false, 16);
18391     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18392     Entry.Ty = PointerType::get(ArgTy,0);
18393     Entry.isSExt = false;
18394     Entry.isZExt = false;
18395     Args.push_back(Entry);
18396   }
18397
18398   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18399                                          getPointerTy(DAG.getDataLayout()));
18400
18401   TargetLowering::CallLoweringInfo CLI(DAG);
18402   CLI.setDebugLoc(dl).setChain(InChain)
18403     .setCallee(getLibcallCallingConv(LC),
18404                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18405                Callee, std::move(Args), 0)
18406     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18407
18408   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18409   return DAG.getBitcast(VT, CallInfo.first);
18410 }
18411
18412 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18413                              SelectionDAG &DAG) {
18414   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18415   MVT VT = Op0.getSimpleValueType();
18416   SDLoc dl(Op);
18417
18418   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18419          (VT == MVT::v8i32 && Subtarget->hasInt256()));
18420
18421   // PMULxD operations multiply each even value (starting at 0) of LHS with
18422   // the related value of RHS and produce a widen result.
18423   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18424   // => <2 x i64> <ae|cg>
18425   //
18426   // In other word, to have all the results, we need to perform two PMULxD:
18427   // 1. one with the even values.
18428   // 2. one with the odd values.
18429   // To achieve #2, with need to place the odd values at an even position.
18430   //
18431   // Place the odd value at an even position (basically, shift all values 1
18432   // step to the left):
18433   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18434   // <a|b|c|d> => <b|undef|d|undef>
18435   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18436   // <e|f|g|h> => <f|undef|h|undef>
18437   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18438
18439   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18440   // ints.
18441   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18442   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18443   unsigned Opcode =
18444       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18445   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18446   // => <2 x i64> <ae|cg>
18447   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18448   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18449   // => <2 x i64> <bf|dh>
18450   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18451
18452   // Shuffle it back into the right order.
18453   SDValue Highs, Lows;
18454   if (VT == MVT::v8i32) {
18455     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18456     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18457     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18458     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18459   } else {
18460     const int HighMask[] = {1, 5, 3, 7};
18461     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18462     const int LowMask[] = {0, 4, 2, 6};
18463     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18464   }
18465
18466   // If we have a signed multiply but no PMULDQ fix up the high parts of a
18467   // unsigned multiply.
18468   if (IsSigned && !Subtarget->hasSSE41()) {
18469     SDValue ShAmt = DAG.getConstant(
18470         31, dl,
18471         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
18472     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18473                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18474     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18475                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18476
18477     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18478     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18479   }
18480
18481   // The first result of MUL_LOHI is actually the low value, followed by the
18482   // high value.
18483   SDValue Ops[] = {Lows, Highs};
18484   return DAG.getMergeValues(Ops, dl);
18485 }
18486
18487 // Return true if the required (according to Opcode) shift-imm form is natively
18488 // supported by the Subtarget
18489 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18490                                         unsigned Opcode) {
18491   if (VT.getScalarSizeInBits() < 16)
18492     return false;
18493
18494   if (VT.is512BitVector() &&
18495       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18496     return true;
18497
18498   bool LShift = VT.is128BitVector() ||
18499     (VT.is256BitVector() && Subtarget->hasInt256());
18500
18501   bool AShift = LShift && (Subtarget->hasVLX() ||
18502     (VT != MVT::v2i64 && VT != MVT::v4i64));
18503   return (Opcode == ISD::SRA) ? AShift : LShift;
18504 }
18505
18506 // The shift amount is a variable, but it is the same for all vector lanes.
18507 // These instructions are defined together with shift-immediate.
18508 static
18509 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18510                                       unsigned Opcode) {
18511   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18512 }
18513
18514 // Return true if the required (according to Opcode) variable-shift form is
18515 // natively supported by the Subtarget
18516 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18517                                     unsigned Opcode) {
18518
18519   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18520     return false;
18521
18522   // vXi16 supported only on AVX-512, BWI
18523   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18524     return false;
18525
18526   if (VT.is512BitVector() || Subtarget->hasVLX())
18527     return true;
18528
18529   bool LShift = VT.is128BitVector() || VT.is256BitVector();
18530   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
18531   return (Opcode == ISD::SRA) ? AShift : LShift;
18532 }
18533
18534 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18535                                          const X86Subtarget *Subtarget) {
18536   MVT VT = Op.getSimpleValueType();
18537   SDLoc dl(Op);
18538   SDValue R = Op.getOperand(0);
18539   SDValue Amt = Op.getOperand(1);
18540
18541   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18542     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18543
18544   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18545     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18546     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18547     SDValue Ex = DAG.getBitcast(ExVT, R);
18548
18549     if (ShiftAmt >= 32) {
18550       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18551       SDValue Upper =
18552           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18553       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18554                                                  ShiftAmt - 32, DAG);
18555       if (VT == MVT::v2i64)
18556         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18557       if (VT == MVT::v4i64)
18558         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18559                                   {9, 1, 11, 3, 13, 5, 15, 7});
18560     } else {
18561       // SRA upper i32, SHL whole i64 and select lower i32.
18562       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18563                                                  ShiftAmt, DAG);
18564       SDValue Lower =
18565           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18566       Lower = DAG.getBitcast(ExVT, Lower);
18567       if (VT == MVT::v2i64)
18568         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18569       if (VT == MVT::v4i64)
18570         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18571                                   {8, 1, 10, 3, 12, 5, 14, 7});
18572     }
18573     return DAG.getBitcast(VT, Ex);
18574   };
18575
18576   // Optimize shl/srl/sra with constant shift amount.
18577   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18578     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18579       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18580
18581       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18582         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18583
18584       // i64 SRA needs to be performed as partial shifts.
18585       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18586           Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18587         return ArithmeticShiftRight64(ShiftAmt);
18588
18589       if (VT == MVT::v16i8 ||
18590           (Subtarget->hasInt256() && VT == MVT::v32i8) ||
18591           VT == MVT::v64i8) {
18592         unsigned NumElts = VT.getVectorNumElements();
18593         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18594
18595         // Simple i8 add case
18596         if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18597           return DAG.getNode(ISD::ADD, dl, VT, R, R);
18598
18599         // ashr(R, 7)  === cmp_slt(R, 0)
18600         if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18601           SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18602           return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18603         }
18604
18605         // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18606         if (VT == MVT::v16i8 && Subtarget->hasXOP())
18607           return SDValue();
18608
18609         if (Op.getOpcode() == ISD::SHL) {
18610           // Make a large shift.
18611           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18612                                                    R, ShiftAmt, DAG);
18613           SHL = DAG.getBitcast(VT, SHL);
18614           // Zero out the rightmost bits.
18615           return DAG.getNode(ISD::AND, dl, VT, SHL,
18616                              DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, VT));
18617         }
18618         if (Op.getOpcode() == ISD::SRL) {
18619           // Make a large shift.
18620           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18621                                                    R, ShiftAmt, DAG);
18622           SRL = DAG.getBitcast(VT, SRL);
18623           // Zero out the leftmost bits.
18624           return DAG.getNode(ISD::AND, dl, VT, SRL,
18625                              DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, VT));
18626         }
18627         if (Op.getOpcode() == ISD::SRA) {
18628           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18629           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18630
18631           SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
18632           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18633           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18634           return Res;
18635         }
18636         llvm_unreachable("Unknown shift opcode.");
18637       }
18638     }
18639   }
18640
18641   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18642   if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18643       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18644
18645     // Peek through any splat that was introduced for i64 shift vectorization.
18646     int SplatIndex = -1;
18647     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18648       if (SVN->isSplat()) {
18649         SplatIndex = SVN->getSplatIndex();
18650         Amt = Amt.getOperand(0);
18651         assert(SplatIndex < (int)VT.getVectorNumElements() &&
18652                "Splat shuffle referencing second operand");
18653       }
18654
18655     if (Amt.getOpcode() != ISD::BITCAST ||
18656         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18657       return SDValue();
18658
18659     Amt = Amt.getOperand(0);
18660     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18661                      VT.getVectorNumElements();
18662     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18663     uint64_t ShiftAmt = 0;
18664     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18665     for (unsigned i = 0; i != Ratio; ++i) {
18666       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18667       if (!C)
18668         return SDValue();
18669       // 6 == Log2(64)
18670       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18671     }
18672
18673     // Check remaining shift amounts (if not a splat).
18674     if (SplatIndex < 0) {
18675       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18676         uint64_t ShAmt = 0;
18677         for (unsigned j = 0; j != Ratio; ++j) {
18678           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18679           if (!C)
18680             return SDValue();
18681           // 6 == Log2(64)
18682           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18683         }
18684         if (ShAmt != ShiftAmt)
18685           return SDValue();
18686       }
18687     }
18688
18689     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18690       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18691
18692     if (Op.getOpcode() == ISD::SRA)
18693       return ArithmeticShiftRight64(ShiftAmt);
18694   }
18695
18696   return SDValue();
18697 }
18698
18699 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18700                                         const X86Subtarget* Subtarget) {
18701   MVT VT = Op.getSimpleValueType();
18702   SDLoc dl(Op);
18703   SDValue R = Op.getOperand(0);
18704   SDValue Amt = Op.getOperand(1);
18705
18706   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18707     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18708
18709   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18710     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18711
18712   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18713     SDValue BaseShAmt;
18714     MVT EltVT = VT.getVectorElementType();
18715
18716     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18717       // Check if this build_vector node is doing a splat.
18718       // If so, then set BaseShAmt equal to the splat value.
18719       BaseShAmt = BV->getSplatValue();
18720       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18721         BaseShAmt = SDValue();
18722     } else {
18723       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18724         Amt = Amt.getOperand(0);
18725
18726       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18727       if (SVN && SVN->isSplat()) {
18728         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18729         SDValue InVec = Amt.getOperand(0);
18730         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18731           assert((SplatIdx < InVec.getSimpleValueType().getVectorNumElements()) &&
18732                  "Unexpected shuffle index found!");
18733           BaseShAmt = InVec.getOperand(SplatIdx);
18734         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18735            if (ConstantSDNode *C =
18736                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18737              if (C->getZExtValue() == SplatIdx)
18738                BaseShAmt = InVec.getOperand(1);
18739            }
18740         }
18741
18742         if (!BaseShAmt)
18743           // Avoid introducing an extract element from a shuffle.
18744           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18745                                   DAG.getIntPtrConstant(SplatIdx, dl));
18746       }
18747     }
18748
18749     if (BaseShAmt.getNode()) {
18750       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18751       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18752         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18753       else if (EltVT.bitsLT(MVT::i32))
18754         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18755
18756       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18757     }
18758   }
18759
18760   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18761   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
18762       Amt.getOpcode() == ISD::BITCAST &&
18763       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18764     Amt = Amt.getOperand(0);
18765     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18766                      VT.getVectorNumElements();
18767     std::vector<SDValue> Vals(Ratio);
18768     for (unsigned i = 0; i != Ratio; ++i)
18769       Vals[i] = Amt.getOperand(i);
18770     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18771       for (unsigned j = 0; j != Ratio; ++j)
18772         if (Vals[j] != Amt.getOperand(i + j))
18773           return SDValue();
18774     }
18775
18776     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18777       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18778   }
18779   return SDValue();
18780 }
18781
18782 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18783                           SelectionDAG &DAG) {
18784   MVT VT = Op.getSimpleValueType();
18785   SDLoc dl(Op);
18786   SDValue R = Op.getOperand(0);
18787   SDValue Amt = Op.getOperand(1);
18788
18789   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18790   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18791
18792   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18793     return V;
18794
18795   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18796     return V;
18797
18798   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18799     return Op;
18800
18801   // XOP has 128-bit variable logical/arithmetic shifts.
18802   // +ve/-ve Amt = shift left/right.
18803   if (Subtarget->hasXOP() &&
18804       (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18805        VT == MVT::v8i16 || VT == MVT::v16i8)) {
18806     if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18807       SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18808       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18809     }
18810     if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18811       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18812     if (Op.getOpcode() == ISD::SRA)
18813       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18814   }
18815
18816   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18817   // shifts per-lane and then shuffle the partial results back together.
18818   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18819     // Splat the shift amounts so the scalar shifts above will catch it.
18820     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18821     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18822     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18823     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18824     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18825   }
18826
18827   // i64 vector arithmetic shift can be emulated with the transform:
18828   // M = lshr(SIGN_BIT, Amt)
18829   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18830   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18831       Op.getOpcode() == ISD::SRA) {
18832     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18833     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18834     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18835     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18836     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18837     return R;
18838   }
18839
18840   // If possible, lower this packed shift into a vector multiply instead of
18841   // expanding it into a sequence of scalar shifts.
18842   // Do this only if the vector shift count is a constant build_vector.
18843   if (Op.getOpcode() == ISD::SHL &&
18844       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18845        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18846       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18847     SmallVector<SDValue, 8> Elts;
18848     MVT SVT = VT.getVectorElementType();
18849     unsigned SVTBits = SVT.getSizeInBits();
18850     APInt One(SVTBits, 1);
18851     unsigned NumElems = VT.getVectorNumElements();
18852
18853     for (unsigned i=0; i !=NumElems; ++i) {
18854       SDValue Op = Amt->getOperand(i);
18855       if (Op->getOpcode() == ISD::UNDEF) {
18856         Elts.push_back(Op);
18857         continue;
18858       }
18859
18860       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18861       APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
18862       uint64_t ShAmt = C.getZExtValue();
18863       if (ShAmt >= SVTBits) {
18864         Elts.push_back(DAG.getUNDEF(SVT));
18865         continue;
18866       }
18867       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18868     }
18869     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18870     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18871   }
18872
18873   // Lower SHL with variable shift amount.
18874   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18875     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18876
18877     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18878                      DAG.getConstant(0x3f800000U, dl, VT));
18879     Op = DAG.getBitcast(MVT::v4f32, Op);
18880     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18881     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18882   }
18883
18884   // If possible, lower this shift as a sequence of two shifts by
18885   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18886   // Example:
18887   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18888   //
18889   // Could be rewritten as:
18890   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18891   //
18892   // The advantage is that the two shifts from the example would be
18893   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18894   // the vector shift into four scalar shifts plus four pairs of vector
18895   // insert/extract.
18896   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18897       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18898     unsigned TargetOpcode = X86ISD::MOVSS;
18899     bool CanBeSimplified;
18900     // The splat value for the first packed shift (the 'X' from the example).
18901     SDValue Amt1 = Amt->getOperand(0);
18902     // The splat value for the second packed shift (the 'Y' from the example).
18903     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18904                                         Amt->getOperand(2);
18905
18906     // See if it is possible to replace this node with a sequence of
18907     // two shifts followed by a MOVSS/MOVSD
18908     if (VT == MVT::v4i32) {
18909       // Check if it is legal to use a MOVSS.
18910       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18911                         Amt2 == Amt->getOperand(3);
18912       if (!CanBeSimplified) {
18913         // Otherwise, check if we can still simplify this node using a MOVSD.
18914         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18915                           Amt->getOperand(2) == Amt->getOperand(3);
18916         TargetOpcode = X86ISD::MOVSD;
18917         Amt2 = Amt->getOperand(2);
18918       }
18919     } else {
18920       // Do similar checks for the case where the machine value type
18921       // is MVT::v8i16.
18922       CanBeSimplified = Amt1 == Amt->getOperand(1);
18923       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18924         CanBeSimplified = Amt2 == Amt->getOperand(i);
18925
18926       if (!CanBeSimplified) {
18927         TargetOpcode = X86ISD::MOVSD;
18928         CanBeSimplified = true;
18929         Amt2 = Amt->getOperand(4);
18930         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18931           CanBeSimplified = Amt1 == Amt->getOperand(i);
18932         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18933           CanBeSimplified = Amt2 == Amt->getOperand(j);
18934       }
18935     }
18936
18937     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18938         isa<ConstantSDNode>(Amt2)) {
18939       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18940       MVT CastVT = MVT::v4i32;
18941       SDValue Splat1 =
18942         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18943       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18944       SDValue Splat2 =
18945         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18946       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18947       if (TargetOpcode == X86ISD::MOVSD)
18948         CastVT = MVT::v2i64;
18949       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18950       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18951       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18952                                             BitCast1, DAG);
18953       return DAG.getBitcast(VT, Result);
18954     }
18955   }
18956
18957   // v4i32 Non Uniform Shifts.
18958   // If the shift amount is constant we can shift each lane using the SSE2
18959   // immediate shifts, else we need to zero-extend each lane to the lower i64
18960   // and shift using the SSE2 variable shifts.
18961   // The separate results can then be blended together.
18962   if (VT == MVT::v4i32) {
18963     unsigned Opc = Op.getOpcode();
18964     SDValue Amt0, Amt1, Amt2, Amt3;
18965     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18966       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18967       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18968       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18969       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18970     } else {
18971       // ISD::SHL is handled above but we include it here for completeness.
18972       switch (Opc) {
18973       default:
18974         llvm_unreachable("Unknown target vector shift node");
18975       case ISD::SHL:
18976         Opc = X86ISD::VSHL;
18977         break;
18978       case ISD::SRL:
18979         Opc = X86ISD::VSRL;
18980         break;
18981       case ISD::SRA:
18982         Opc = X86ISD::VSRA;
18983         break;
18984       }
18985       // The SSE2 shifts use the lower i64 as the same shift amount for
18986       // all lanes and the upper i64 is ignored. These shuffle masks
18987       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18988       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18989       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18990       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18991       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18992       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18993     }
18994
18995     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18996     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18997     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18998     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18999     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
19000     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
19001     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
19002   }
19003
19004   if (VT == MVT::v16i8 ||
19005       (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
19006     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
19007     unsigned ShiftOpcode = Op->getOpcode();
19008
19009     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
19010       // On SSE41 targets we make use of the fact that VSELECT lowers
19011       // to PBLENDVB which selects bytes based just on the sign bit.
19012       if (Subtarget->hasSSE41()) {
19013         V0 = DAG.getBitcast(VT, V0);
19014         V1 = DAG.getBitcast(VT, V1);
19015         Sel = DAG.getBitcast(VT, Sel);
19016         return DAG.getBitcast(SelVT,
19017                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
19018       }
19019       // On pre-SSE41 targets we test for the sign bit by comparing to
19020       // zero - a negative value will set all bits of the lanes to true
19021       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
19022       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
19023       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
19024       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
19025     };
19026
19027     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
19028     // We can safely do this using i16 shifts as we're only interested in
19029     // the 3 lower bits of each byte.
19030     Amt = DAG.getBitcast(ExtVT, Amt);
19031     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
19032     Amt = DAG.getBitcast(VT, Amt);
19033
19034     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
19035       // r = VSELECT(r, shift(r, 4), a);
19036       SDValue M =
19037           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
19038       R = SignBitSelect(VT, Amt, M, R);
19039
19040       // a += a
19041       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19042
19043       // r = VSELECT(r, shift(r, 2), a);
19044       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
19045       R = SignBitSelect(VT, Amt, M, R);
19046
19047       // a += a
19048       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19049
19050       // return VSELECT(r, shift(r, 1), a);
19051       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19052       R = SignBitSelect(VT, Amt, M, R);
19053       return R;
19054     }
19055
19056     if (Op->getOpcode() == ISD::SRA) {
19057       // For SRA we need to unpack each byte to the higher byte of a i16 vector
19058       // so we can correctly sign extend. We don't care what happens to the
19059       // lower byte.
19060       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
19061       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
19062       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
19063       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
19064       ALo = DAG.getBitcast(ExtVT, ALo);
19065       AHi = DAG.getBitcast(ExtVT, AHi);
19066       RLo = DAG.getBitcast(ExtVT, RLo);
19067       RHi = DAG.getBitcast(ExtVT, RHi);
19068
19069       // r = VSELECT(r, shift(r, 4), a);
19070       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19071                                 DAG.getConstant(4, dl, ExtVT));
19072       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19073                                 DAG.getConstant(4, dl, ExtVT));
19074       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19075       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19076
19077       // a += a
19078       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19079       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19080
19081       // r = VSELECT(r, shift(r, 2), a);
19082       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19083                         DAG.getConstant(2, dl, ExtVT));
19084       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19085                         DAG.getConstant(2, dl, ExtVT));
19086       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19087       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19088
19089       // a += a
19090       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19091       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19092
19093       // r = VSELECT(r, shift(r, 1), a);
19094       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19095                         DAG.getConstant(1, dl, ExtVT));
19096       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19097                         DAG.getConstant(1, dl, ExtVT));
19098       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19099       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19100
19101       // Logical shift the result back to the lower byte, leaving a zero upper
19102       // byte
19103       // meaning that we can safely pack with PACKUSWB.
19104       RLo =
19105           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
19106       RHi =
19107           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
19108       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
19109     }
19110   }
19111
19112   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
19113   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
19114   // solution better.
19115   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
19116     MVT ExtVT = MVT::v8i32;
19117     unsigned ExtOpc =
19118         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
19119     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
19120     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
19121     return DAG.getNode(ISD::TRUNCATE, dl, VT,
19122                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
19123   }
19124
19125   if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
19126     MVT ExtVT = MVT::v8i32;
19127     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
19128     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
19129     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
19130     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
19131     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
19132     ALo = DAG.getBitcast(ExtVT, ALo);
19133     AHi = DAG.getBitcast(ExtVT, AHi);
19134     RLo = DAG.getBitcast(ExtVT, RLo);
19135     RHi = DAG.getBitcast(ExtVT, RHi);
19136     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
19137     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
19138     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
19139     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
19140     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
19141   }
19142
19143   if (VT == MVT::v8i16) {
19144     unsigned ShiftOpcode = Op->getOpcode();
19145
19146     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
19147       // On SSE41 targets we make use of the fact that VSELECT lowers
19148       // to PBLENDVB which selects bytes based just on the sign bit.
19149       if (Subtarget->hasSSE41()) {
19150         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
19151         V0 = DAG.getBitcast(ExtVT, V0);
19152         V1 = DAG.getBitcast(ExtVT, V1);
19153         Sel = DAG.getBitcast(ExtVT, Sel);
19154         return DAG.getBitcast(
19155             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
19156       }
19157       // On pre-SSE41 targets we splat the sign bit - a negative value will
19158       // set all bits of the lanes to true and VSELECT uses that in
19159       // its OR(AND(V0,C),AND(V1,~C)) lowering.
19160       SDValue C =
19161           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
19162       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
19163     };
19164
19165     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
19166     if (Subtarget->hasSSE41()) {
19167       // On SSE41 targets we need to replicate the shift mask in both
19168       // bytes for PBLENDVB.
19169       Amt = DAG.getNode(
19170           ISD::OR, dl, VT,
19171           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
19172           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
19173     } else {
19174       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
19175     }
19176
19177     // r = VSELECT(r, shift(r, 8), a);
19178     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
19179     R = SignBitSelect(Amt, M, R);
19180
19181     // a += a
19182     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19183
19184     // r = VSELECT(r, shift(r, 4), a);
19185     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
19186     R = SignBitSelect(Amt, M, R);
19187
19188     // a += a
19189     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19190
19191     // r = VSELECT(r, shift(r, 2), a);
19192     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
19193     R = SignBitSelect(Amt, M, R);
19194
19195     // a += a
19196     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19197
19198     // return VSELECT(r, shift(r, 1), a);
19199     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19200     R = SignBitSelect(Amt, M, R);
19201     return R;
19202   }
19203
19204   // Decompose 256-bit shifts into smaller 128-bit shifts.
19205   if (VT.is256BitVector()) {
19206     unsigned NumElems = VT.getVectorNumElements();
19207     MVT EltVT = VT.getVectorElementType();
19208     MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
19209
19210     // Extract the two vectors
19211     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
19212     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
19213
19214     // Recreate the shift amount vectors
19215     SDValue Amt1, Amt2;
19216     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
19217       // Constant shift amount
19218       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
19219       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
19220       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
19221
19222       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
19223       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
19224     } else {
19225       // Variable shift amount
19226       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
19227       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
19228     }
19229
19230     // Issue new vector shifts for the smaller types
19231     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
19232     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
19233
19234     // Concatenate the result back
19235     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
19236   }
19237
19238   return SDValue();
19239 }
19240
19241 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
19242                            SelectionDAG &DAG) {
19243   MVT VT = Op.getSimpleValueType();
19244   SDLoc DL(Op);
19245   SDValue R = Op.getOperand(0);
19246   SDValue Amt = Op.getOperand(1);
19247
19248   assert(VT.isVector() && "Custom lowering only for vector rotates!");
19249   assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
19250   assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
19251
19252   // XOP has 128-bit vector variable + immediate rotates.
19253   // +ve/-ve Amt = rotate left/right.
19254
19255   // Split 256-bit integers.
19256   if (VT.is256BitVector())
19257     return Lower256IntArith(Op, DAG);
19258
19259   assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
19260
19261   // Attempt to rotate by immediate.
19262   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
19263     if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
19264       uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
19265       assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
19266       return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
19267                          DAG.getConstant(RotateAmt, DL, MVT::i8));
19268     }
19269   }
19270
19271   // Use general rotate by variable (per-element).
19272   return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
19273 }
19274
19275 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
19276   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
19277   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
19278   // looks for this combo and may remove the "setcc" instruction if the "setcc"
19279   // has only one use.
19280   SDNode *N = Op.getNode();
19281   SDValue LHS = N->getOperand(0);
19282   SDValue RHS = N->getOperand(1);
19283   unsigned BaseOp = 0;
19284   unsigned Cond = 0;
19285   SDLoc DL(Op);
19286   switch (Op.getOpcode()) {
19287   default: llvm_unreachable("Unknown ovf instruction!");
19288   case ISD::SADDO:
19289     // A subtract of one will be selected as a INC. Note that INC doesn't
19290     // set CF, so we can't do this for UADDO.
19291     if (isOneConstant(RHS)) {
19292         BaseOp = X86ISD::INC;
19293         Cond = X86::COND_O;
19294         break;
19295       }
19296     BaseOp = X86ISD::ADD;
19297     Cond = X86::COND_O;
19298     break;
19299   case ISD::UADDO:
19300     BaseOp = X86ISD::ADD;
19301     Cond = X86::COND_B;
19302     break;
19303   case ISD::SSUBO:
19304     // A subtract of one will be selected as a DEC. Note that DEC doesn't
19305     // set CF, so we can't do this for USUBO.
19306     if (isOneConstant(RHS)) {
19307         BaseOp = X86ISD::DEC;
19308         Cond = X86::COND_O;
19309         break;
19310       }
19311     BaseOp = X86ISD::SUB;
19312     Cond = X86::COND_O;
19313     break;
19314   case ISD::USUBO:
19315     BaseOp = X86ISD::SUB;
19316     Cond = X86::COND_B;
19317     break;
19318   case ISD::SMULO:
19319     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
19320     Cond = X86::COND_O;
19321     break;
19322   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
19323     if (N->getValueType(0) == MVT::i8) {
19324       BaseOp = X86ISD::UMUL8;
19325       Cond = X86::COND_O;
19326       break;
19327     }
19328     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
19329                                  MVT::i32);
19330     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
19331
19332     SDValue SetCC =
19333       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19334                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
19335                   SDValue(Sum.getNode(), 2));
19336
19337     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19338   }
19339   }
19340
19341   // Also sets EFLAGS.
19342   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
19343   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
19344
19345   SDValue SetCC =
19346     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
19347                 DAG.getConstant(Cond, DL, MVT::i32),
19348                 SDValue(Sum.getNode(), 1));
19349
19350   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19351 }
19352
19353 /// Returns true if the operand type is exactly twice the native width, and
19354 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
19355 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
19356 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
19357 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
19358   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
19359
19360   if (OpWidth == 64)
19361     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
19362   else if (OpWidth == 128)
19363     return Subtarget->hasCmpxchg16b();
19364   else
19365     return false;
19366 }
19367
19368 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
19369   return needsCmpXchgNb(SI->getValueOperand()->getType());
19370 }
19371
19372 // Note: this turns large loads into lock cmpxchg8b/16b.
19373 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
19374 TargetLowering::AtomicExpansionKind
19375 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
19376   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
19377   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
19378                                                : AtomicExpansionKind::None;
19379 }
19380
19381 TargetLowering::AtomicExpansionKind
19382 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
19383   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19384   Type *MemType = AI->getType();
19385
19386   // If the operand is too big, we must see if cmpxchg8/16b is available
19387   // and default to library calls otherwise.
19388   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
19389     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
19390                                    : AtomicExpansionKind::None;
19391   }
19392
19393   AtomicRMWInst::BinOp Op = AI->getOperation();
19394   switch (Op) {
19395   default:
19396     llvm_unreachable("Unknown atomic operation");
19397   case AtomicRMWInst::Xchg:
19398   case AtomicRMWInst::Add:
19399   case AtomicRMWInst::Sub:
19400     // It's better to use xadd, xsub or xchg for these in all cases.
19401     return AtomicExpansionKind::None;
19402   case AtomicRMWInst::Or:
19403   case AtomicRMWInst::And:
19404   case AtomicRMWInst::Xor:
19405     // If the atomicrmw's result isn't actually used, we can just add a "lock"
19406     // prefix to a normal instruction for these operations.
19407     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
19408                             : AtomicExpansionKind::None;
19409   case AtomicRMWInst::Nand:
19410   case AtomicRMWInst::Max:
19411   case AtomicRMWInst::Min:
19412   case AtomicRMWInst::UMax:
19413   case AtomicRMWInst::UMin:
19414     // These always require a non-trivial set of data operations on x86. We must
19415     // use a cmpxchg loop.
19416     return AtomicExpansionKind::CmpXChg;
19417   }
19418 }
19419
19420 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19421   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19422   // no-sse2). There isn't any reason to disable it if the target processor
19423   // supports it.
19424   return Subtarget.hasSSE2() || Subtarget.is64Bit();
19425 }
19426
19427 LoadInst *
19428 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19429   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19430   Type *MemType = AI->getType();
19431   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19432   // there is no benefit in turning such RMWs into loads, and it is actually
19433   // harmful as it introduces a mfence.
19434   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19435     return nullptr;
19436
19437   auto Builder = IRBuilder<>(AI);
19438   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19439   auto SynchScope = AI->getSynchScope();
19440   // We must restrict the ordering to avoid generating loads with Release or
19441   // ReleaseAcquire orderings.
19442   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19443   auto Ptr = AI->getPointerOperand();
19444
19445   // Before the load we need a fence. Here is an example lifted from
19446   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19447   // is required:
19448   // Thread 0:
19449   //   x.store(1, relaxed);
19450   //   r1 = y.fetch_add(0, release);
19451   // Thread 1:
19452   //   y.fetch_add(42, acquire);
19453   //   r2 = x.load(relaxed);
19454   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19455   // lowered to just a load without a fence. A mfence flushes the store buffer,
19456   // making the optimization clearly correct.
19457   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19458   // otherwise, we might be able to be more aggressive on relaxed idempotent
19459   // rmw. In practice, they do not look useful, so we don't try to be
19460   // especially clever.
19461   if (SynchScope == SingleThread)
19462     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19463     // the IR level, so we must wrap it in an intrinsic.
19464     return nullptr;
19465
19466   if (!hasMFENCE(*Subtarget))
19467     // FIXME: it might make sense to use a locked operation here but on a
19468     // different cache-line to prevent cache-line bouncing. In practice it
19469     // is probably a small win, and x86 processors without mfence are rare
19470     // enough that we do not bother.
19471     return nullptr;
19472
19473   Function *MFence =
19474       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19475   Builder.CreateCall(MFence, {});
19476
19477   // Finally we can emit the atomic load.
19478   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19479           AI->getType()->getPrimitiveSizeInBits());
19480   Loaded->setAtomic(Order, SynchScope);
19481   AI->replaceAllUsesWith(Loaded);
19482   AI->eraseFromParent();
19483   return Loaded;
19484 }
19485
19486 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19487                                  SelectionDAG &DAG) {
19488   SDLoc dl(Op);
19489   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19490     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19491   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19492     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19493
19494   // The only fence that needs an instruction is a sequentially-consistent
19495   // cross-thread fence.
19496   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19497     if (hasMFENCE(*Subtarget))
19498       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19499
19500     SDValue Chain = Op.getOperand(0);
19501     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19502     SDValue Ops[] = {
19503       DAG.getRegister(X86::ESP, MVT::i32),     // Base
19504       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
19505       DAG.getRegister(0, MVT::i32),            // Index
19506       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
19507       DAG.getRegister(0, MVT::i32),            // Segment.
19508       Zero,
19509       Chain
19510     };
19511     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19512     return SDValue(Res, 0);
19513   }
19514
19515   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19516   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19517 }
19518
19519 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19520                              SelectionDAG &DAG) {
19521   MVT T = Op.getSimpleValueType();
19522   SDLoc DL(Op);
19523   unsigned Reg = 0;
19524   unsigned size = 0;
19525   switch(T.SimpleTy) {
19526   default: llvm_unreachable("Invalid value type!");
19527   case MVT::i8:  Reg = X86::AL;  size = 1; break;
19528   case MVT::i16: Reg = X86::AX;  size = 2; break;
19529   case MVT::i32: Reg = X86::EAX; size = 4; break;
19530   case MVT::i64:
19531     assert(Subtarget->is64Bit() && "Node not type legal!");
19532     Reg = X86::RAX; size = 8;
19533     break;
19534   }
19535   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19536                                   Op.getOperand(2), SDValue());
19537   SDValue Ops[] = { cpIn.getValue(0),
19538                     Op.getOperand(1),
19539                     Op.getOperand(3),
19540                     DAG.getTargetConstant(size, DL, MVT::i8),
19541                     cpIn.getValue(1) };
19542   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19543   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19544   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19545                                            Ops, T, MMO);
19546
19547   SDValue cpOut =
19548     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19549   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19550                                       MVT::i32, cpOut.getValue(2));
19551   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19552                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19553                                 EFLAGS);
19554
19555   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19556   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19557   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19558   return SDValue();
19559 }
19560
19561 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19562                             SelectionDAG &DAG) {
19563   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19564   MVT DstVT = Op.getSimpleValueType();
19565
19566   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8 ||
19567       SrcVT == MVT::i64) {
19568     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19569     if (DstVT != MVT::f64)
19570       // This conversion needs to be expanded.
19571       return SDValue();
19572
19573     SDValue Op0 = Op->getOperand(0);
19574     SmallVector<SDValue, 16> Elts;
19575     SDLoc dl(Op);
19576     unsigned NumElts;
19577     MVT SVT;
19578     if (SrcVT.isVector()) {
19579       NumElts = SrcVT.getVectorNumElements();
19580       SVT = SrcVT.getVectorElementType();
19581
19582       // Widen the vector in input in the case of MVT::v2i32.
19583       // Example: from MVT::v2i32 to MVT::v4i32.
19584       for (unsigned i = 0, e = NumElts; i != e; ++i)
19585         Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, Op0,
19586                                    DAG.getIntPtrConstant(i, dl)));
19587     } else {
19588       assert(SrcVT == MVT::i64 && !Subtarget->is64Bit() &&
19589              "Unexpected source type in LowerBITCAST");
19590       Elts.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op0,
19591                                  DAG.getIntPtrConstant(0, dl)));
19592       Elts.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op0,
19593                                  DAG.getIntPtrConstant(1, dl)));
19594       NumElts = 2;
19595       SVT = MVT::i32;
19596     }
19597     // Explicitly mark the extra elements as Undef.
19598     Elts.append(NumElts, DAG.getUNDEF(SVT));
19599
19600     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19601     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19602     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19603     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19604                        DAG.getIntPtrConstant(0, dl));
19605   }
19606
19607   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19608          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19609   assert((DstVT == MVT::i64 ||
19610           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19611          "Unexpected custom BITCAST");
19612   // i64 <=> MMX conversions are Legal.
19613   if (SrcVT==MVT::i64 && DstVT.isVector())
19614     return Op;
19615   if (DstVT==MVT::i64 && SrcVT.isVector())
19616     return Op;
19617   // MMX <=> MMX conversions are Legal.
19618   if (SrcVT.isVector() && DstVT.isVector())
19619     return Op;
19620   // All other conversions need to be expanded.
19621   return SDValue();
19622 }
19623
19624 /// Compute the horizontal sum of bytes in V for the elements of VT.
19625 ///
19626 /// Requires V to be a byte vector and VT to be an integer vector type with
19627 /// wider elements than V's type. The width of the elements of VT determines
19628 /// how many bytes of V are summed horizontally to produce each element of the
19629 /// result.
19630 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19631                                       const X86Subtarget *Subtarget,
19632                                       SelectionDAG &DAG) {
19633   SDLoc DL(V);
19634   MVT ByteVecVT = V.getSimpleValueType();
19635   MVT EltVT = VT.getVectorElementType();
19636   int NumElts = VT.getVectorNumElements();
19637   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19638          "Expected value to have byte element type.");
19639   assert(EltVT != MVT::i8 &&
19640          "Horizontal byte sum only makes sense for wider elements!");
19641   unsigned VecSize = VT.getSizeInBits();
19642   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19643
19644   // PSADBW instruction horizontally add all bytes and leave the result in i64
19645   // chunks, thus directly computes the pop count for v2i64 and v4i64.
19646   if (EltVT == MVT::i64) {
19647     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19648     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19649     V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
19650     return DAG.getBitcast(VT, V);
19651   }
19652
19653   if (EltVT == MVT::i32) {
19654     // We unpack the low half and high half into i32s interleaved with zeros so
19655     // that we can use PSADBW to horizontally sum them. The most useful part of
19656     // this is that it lines up the results of two PSADBW instructions to be
19657     // two v2i64 vectors which concatenated are the 4 population counts. We can
19658     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19659     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19660     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19661     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19662
19663     // Do the horizontal sums into two v2i64s.
19664     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19665     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19666     Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19667                       DAG.getBitcast(ByteVecVT, Low), Zeros);
19668     High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19669                        DAG.getBitcast(ByteVecVT, High), Zeros);
19670
19671     // Merge them together.
19672     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19673     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19674                     DAG.getBitcast(ShortVecVT, Low),
19675                     DAG.getBitcast(ShortVecVT, High));
19676
19677     return DAG.getBitcast(VT, V);
19678   }
19679
19680   // The only element type left is i16.
19681   assert(EltVT == MVT::i16 && "Unknown how to handle type");
19682
19683   // To obtain pop count for each i16 element starting from the pop count for
19684   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19685   // right by 8. It is important to shift as i16s as i8 vector shift isn't
19686   // directly supported.
19687   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19688   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19689   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19690   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19691                   DAG.getBitcast(ByteVecVT, V));
19692   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19693 }
19694
19695 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19696                                         const X86Subtarget *Subtarget,
19697                                         SelectionDAG &DAG) {
19698   MVT VT = Op.getSimpleValueType();
19699   MVT EltVT = VT.getVectorElementType();
19700   unsigned VecSize = VT.getSizeInBits();
19701
19702   // Implement a lookup table in register by using an algorithm based on:
19703   // http://wm.ite.pl/articles/sse-popcount.html
19704   //
19705   // The general idea is that every lower byte nibble in the input vector is an
19706   // index into a in-register pre-computed pop count table. We then split up the
19707   // input vector in two new ones: (1) a vector with only the shifted-right
19708   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19709   // masked out higher ones) for each byte. PSHUB is used separately with both
19710   // to index the in-register table. Next, both are added and the result is a
19711   // i8 vector where each element contains the pop count for input byte.
19712   //
19713   // To obtain the pop count for elements != i8, we follow up with the same
19714   // approach and use additional tricks as described below.
19715   //
19716   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19717                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19718                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19719                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19720
19721   int NumByteElts = VecSize / 8;
19722   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19723   SDValue In = DAG.getBitcast(ByteVecVT, Op);
19724   SmallVector<SDValue, 16> LUTVec;
19725   for (int i = 0; i < NumByteElts; ++i)
19726     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19727   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19728   SmallVector<SDValue, 16> Mask0F(NumByteElts,
19729                                   DAG.getConstant(0x0F, DL, MVT::i8));
19730   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19731
19732   // High nibbles
19733   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19734   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19735   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19736
19737   // Low nibbles
19738   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19739
19740   // The input vector is used as the shuffle mask that index elements into the
19741   // LUT. After counting low and high nibbles, add the vector to obtain the
19742   // final pop count per i8 element.
19743   SDValue HighPopCnt =
19744       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19745   SDValue LowPopCnt =
19746       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19747   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19748
19749   if (EltVT == MVT::i8)
19750     return PopCnt;
19751
19752   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19753 }
19754
19755 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19756                                        const X86Subtarget *Subtarget,
19757                                        SelectionDAG &DAG) {
19758   MVT VT = Op.getSimpleValueType();
19759   assert(VT.is128BitVector() &&
19760          "Only 128-bit vector bitmath lowering supported.");
19761
19762   int VecSize = VT.getSizeInBits();
19763   MVT EltVT = VT.getVectorElementType();
19764   int Len = EltVT.getSizeInBits();
19765
19766   // This is the vectorized version of the "best" algorithm from
19767   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19768   // with a minor tweak to use a series of adds + shifts instead of vector
19769   // multiplications. Implemented for all integer vector types. We only use
19770   // this when we don't have SSSE3 which allows a LUT-based lowering that is
19771   // much faster, even faster than using native popcnt instructions.
19772
19773   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19774     MVT VT = V.getSimpleValueType();
19775     SmallVector<SDValue, 32> Shifters(
19776         VT.getVectorNumElements(),
19777         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19778     return DAG.getNode(OpCode, DL, VT, V,
19779                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19780   };
19781   auto GetMask = [&](SDValue V, APInt Mask) {
19782     MVT VT = V.getSimpleValueType();
19783     SmallVector<SDValue, 32> Masks(
19784         VT.getVectorNumElements(),
19785         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19786     return DAG.getNode(ISD::AND, DL, VT, V,
19787                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19788   };
19789
19790   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19791   // x86, so set the SRL type to have elements at least i16 wide. This is
19792   // correct because all of our SRLs are followed immediately by a mask anyways
19793   // that handles any bits that sneak into the high bits of the byte elements.
19794   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19795
19796   SDValue V = Op;
19797
19798   // v = v - ((v >> 1) & 0x55555555...)
19799   SDValue Srl =
19800       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19801   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19802   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19803
19804   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19805   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19806   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19807   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19808   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19809
19810   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19811   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19812   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19813   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19814
19815   // At this point, V contains the byte-wise population count, and we are
19816   // merely doing a horizontal sum if necessary to get the wider element
19817   // counts.
19818   if (EltVT == MVT::i8)
19819     return V;
19820
19821   return LowerHorizontalByteSum(
19822       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19823       DAG);
19824 }
19825
19826 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19827                                 SelectionDAG &DAG) {
19828   MVT VT = Op.getSimpleValueType();
19829   // FIXME: Need to add AVX-512 support here!
19830   assert((VT.is256BitVector() || VT.is128BitVector()) &&
19831          "Unknown CTPOP type to handle");
19832   SDLoc DL(Op.getNode());
19833   SDValue Op0 = Op.getOperand(0);
19834
19835   if (!Subtarget->hasSSSE3()) {
19836     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19837     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19838     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19839   }
19840
19841   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19842     unsigned NumElems = VT.getVectorNumElements();
19843
19844     // Extract each 128-bit vector, compute pop count and concat the result.
19845     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19846     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19847
19848     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19849                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19850                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19851   }
19852
19853   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19854 }
19855
19856 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19857                           SelectionDAG &DAG) {
19858   assert(Op.getSimpleValueType().isVector() &&
19859          "We only do custom lowering for vector population count.");
19860   return LowerVectorCTPOP(Op, Subtarget, DAG);
19861 }
19862
19863 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19864   SDNode *Node = Op.getNode();
19865   SDLoc dl(Node);
19866   EVT T = Node->getValueType(0);
19867   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19868                               DAG.getConstant(0, dl, T), Node->getOperand(2));
19869   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19870                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19871                        Node->getOperand(0),
19872                        Node->getOperand(1), negOp,
19873                        cast<AtomicSDNode>(Node)->getMemOperand(),
19874                        cast<AtomicSDNode>(Node)->getOrdering(),
19875                        cast<AtomicSDNode>(Node)->getSynchScope());
19876 }
19877
19878 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19879   SDNode *Node = Op.getNode();
19880   SDLoc dl(Node);
19881   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19882
19883   // Convert seq_cst store -> xchg
19884   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19885   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19886   //        (The only way to get a 16-byte store is cmpxchg16b)
19887   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19888   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19889       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19890     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19891                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19892                                  Node->getOperand(0),
19893                                  Node->getOperand(1), Node->getOperand(2),
19894                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19895                                  cast<AtomicSDNode>(Node)->getOrdering(),
19896                                  cast<AtomicSDNode>(Node)->getSynchScope());
19897     return Swap.getValue(1);
19898   }
19899   // Other atomic stores have a simple pattern.
19900   return Op;
19901 }
19902
19903 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19904   MVT VT = Op.getNode()->getSimpleValueType(0);
19905
19906   // Let legalize expand this if it isn't a legal type yet.
19907   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19908     return SDValue();
19909
19910   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19911
19912   unsigned Opc;
19913   bool ExtraOp = false;
19914   switch (Op.getOpcode()) {
19915   default: llvm_unreachable("Invalid code");
19916   case ISD::ADDC: Opc = X86ISD::ADD; break;
19917   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19918   case ISD::SUBC: Opc = X86ISD::SUB; break;
19919   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19920   }
19921
19922   if (!ExtraOp)
19923     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19924                        Op.getOperand(1));
19925   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19926                      Op.getOperand(1), Op.getOperand(2));
19927 }
19928
19929 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19930                             SelectionDAG &DAG) {
19931   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19932
19933   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19934   // which returns the values as { float, float } (in XMM0) or
19935   // { double, double } (which is returned in XMM0, XMM1).
19936   SDLoc dl(Op);
19937   SDValue Arg = Op.getOperand(0);
19938   EVT ArgVT = Arg.getValueType();
19939   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19940
19941   TargetLowering::ArgListTy Args;
19942   TargetLowering::ArgListEntry Entry;
19943
19944   Entry.Node = Arg;
19945   Entry.Ty = ArgTy;
19946   Entry.isSExt = false;
19947   Entry.isZExt = false;
19948   Args.push_back(Entry);
19949
19950   bool isF64 = ArgVT == MVT::f64;
19951   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19952   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19953   // the results are returned via SRet in memory.
19954   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19955   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19956   SDValue Callee =
19957       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19958
19959   Type *RetTy = isF64
19960     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19961     : (Type*)VectorType::get(ArgTy, 4);
19962
19963   TargetLowering::CallLoweringInfo CLI(DAG);
19964   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19965     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19966
19967   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19968
19969   if (isF64)
19970     // Returned in xmm0 and xmm1.
19971     return CallResult.first;
19972
19973   // Returned in bits 0:31 and 32:64 xmm0.
19974   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19975                                CallResult.first, DAG.getIntPtrConstant(0, dl));
19976   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19977                                CallResult.first, DAG.getIntPtrConstant(1, dl));
19978   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19979   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19980 }
19981
19982 /// Widen a vector input to a vector of NVT.  The
19983 /// input vector must have the same element type as NVT.
19984 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
19985                             bool FillWithZeroes = false) {
19986   // Check if InOp already has the right width.
19987   MVT InVT = InOp.getSimpleValueType();
19988   if (InVT == NVT)
19989     return InOp;
19990
19991   if (InOp.isUndef())
19992     return DAG.getUNDEF(NVT);
19993
19994   assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
19995          "input and widen element type must match");
19996
19997   unsigned InNumElts = InVT.getVectorNumElements();
19998   unsigned WidenNumElts = NVT.getVectorNumElements();
19999   assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
20000          "Unexpected request for vector widening");
20001
20002   EVT EltVT = NVT.getVectorElementType();
20003
20004   SDLoc dl(InOp);
20005   if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
20006       InOp.getNumOperands() == 2) {
20007     SDValue N1 = InOp.getOperand(1);
20008     if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
20009         N1.isUndef()) {
20010       InOp = InOp.getOperand(0);
20011       InVT = InOp.getSimpleValueType();
20012       InNumElts = InVT.getVectorNumElements();
20013     }
20014   }
20015   if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
20016       ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
20017     SmallVector<SDValue, 16> Ops;
20018     for (unsigned i = 0; i < InNumElts; ++i)
20019       Ops.push_back(InOp.getOperand(i));
20020
20021     SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
20022       DAG.getUNDEF(EltVT);
20023     for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
20024       Ops.push_back(FillVal);
20025     return DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Ops);
20026   }
20027   SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
20028     DAG.getUNDEF(NVT);
20029   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
20030                      InOp, DAG.getIntPtrConstant(0, dl));
20031 }
20032
20033 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
20034                              SelectionDAG &DAG) {
20035   assert(Subtarget->hasAVX512() &&
20036          "MGATHER/MSCATTER are supported on AVX-512 arch only");
20037
20038   // X86 scatter kills mask register, so its type should be added to
20039   // the list of return values.
20040   // If the "scatter" has 2 return values, it is already handled.
20041   if (Op.getNode()->getNumValues() == 2)
20042     return Op;
20043
20044   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
20045   SDValue Src = N->getValue();
20046   MVT VT = Src.getSimpleValueType();
20047   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
20048   SDLoc dl(Op);
20049
20050   SDValue NewScatter;
20051   SDValue Index = N->getIndex();
20052   SDValue Mask = N->getMask();
20053   SDValue Chain = N->getChain();
20054   SDValue BasePtr = N->getBasePtr();
20055   MVT MemVT = N->getMemoryVT().getSimpleVT();
20056   MVT IndexVT = Index.getSimpleValueType();
20057   MVT MaskVT = Mask.getSimpleValueType();
20058
20059   if (MemVT.getScalarSizeInBits() < VT.getScalarSizeInBits()) {
20060     // The v2i32 value was promoted to v2i64.
20061     // Now we "redo" the type legalizer's work and widen the original
20062     // v2i32 value to v4i32. The original v2i32 is retrieved from v2i64
20063     // with a shuffle.
20064     assert((MemVT == MVT::v2i32 && VT == MVT::v2i64) &&
20065            "Unexpected memory type");
20066     int ShuffleMask[] = {0, 2, -1, -1};
20067     Src = DAG.getVectorShuffle(MVT::v4i32, dl, DAG.getBitcast(MVT::v4i32, Src),
20068                                DAG.getUNDEF(MVT::v4i32), ShuffleMask);
20069     // Now we have 4 elements instead of 2.
20070     // Expand the index.
20071     MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), 4);
20072     Index = ExtendToType(Index, NewIndexVT, DAG);
20073
20074     // Expand the mask with zeroes
20075     // Mask may be <2 x i64> or <2 x i1> at this moment
20076     assert((MaskVT == MVT::v2i1 || MaskVT == MVT::v2i64) &&
20077            "Unexpected mask type");
20078     MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), 4);
20079     Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20080     VT = MVT::v4i32;
20081   }
20082
20083   unsigned NumElts = VT.getVectorNumElements();
20084   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20085       !Index.getSimpleValueType().is512BitVector()) {
20086     // AVX512F supports only 512-bit vectors. Or data or index should
20087     // be 512 bit wide. If now the both index and data are 256-bit, but
20088     // the vector contains 8 elements, we just sign-extend the index
20089     if (IndexVT == MVT::v8i32)
20090       // Just extend index
20091       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20092     else {
20093       // The minimal number of elts in scatter is 8
20094       NumElts = 8;
20095       // Index
20096       MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20097       // Use original index here, do not modify the index twice
20098       Index = ExtendToType(N->getIndex(), NewIndexVT, DAG);
20099       if (IndexVT.getScalarType() == MVT::i32)
20100         Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20101
20102       // Mask
20103       // At this point we have promoted mask operand
20104       assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20105       MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20106       // Use the original mask here, do not modify the mask twice
20107       Mask = ExtendToType(N->getMask(), ExtMaskVT, DAG, true);
20108
20109       // The value that should be stored
20110       MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20111       Src = ExtendToType(Src, NewVT, DAG);
20112     }
20113   }
20114   // If the mask is "wide" at this point - truncate it to i1 vector
20115   MVT BitMaskVT = MVT::getVectorVT(MVT::i1, NumElts);
20116   Mask = DAG.getNode(ISD::TRUNCATE, dl, BitMaskVT, Mask);
20117
20118   // The mask is killed by scatter, add it to the values
20119   SDVTList VTs = DAG.getVTList(BitMaskVT, MVT::Other);
20120   SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index};
20121   NewScatter = DAG.getMaskedScatter(VTs, N->getMemoryVT(), dl, Ops,
20122                                     N->getMemOperand());
20123   DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
20124   return SDValue(NewScatter.getNode(), 0);
20125 }
20126
20127 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget *Subtarget,
20128                           SelectionDAG &DAG) {
20129
20130   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
20131   MVT VT = Op.getSimpleValueType();
20132   SDValue Mask = N->getMask();
20133   SDLoc dl(Op);
20134
20135   if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20136       !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20137     // This operation is legal for targets with VLX, but without
20138     // VLX the vector should be widened to 512 bit
20139     unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20140     MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20141     MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20142     SDValue Src0 = N->getSrc0();
20143     Src0 = ExtendToType(Src0, WideDataVT, DAG);
20144     Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20145     SDValue NewLoad = DAG.getMaskedLoad(WideDataVT, dl, N->getChain(),
20146                                         N->getBasePtr(), Mask, Src0,
20147                                         N->getMemoryVT(), N->getMemOperand(),
20148                                         N->getExtensionType());
20149
20150     SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20151                                  NewLoad.getValue(0),
20152                                  DAG.getIntPtrConstant(0, dl));
20153     SDValue RetOps[] = {Exract, NewLoad.getValue(1)};
20154     return DAG.getMergeValues(RetOps, dl);
20155   }
20156   return Op;
20157 }
20158
20159 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget *Subtarget,
20160                            SelectionDAG &DAG) {
20161   MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
20162   SDValue DataToStore = N->getValue();
20163   MVT VT = DataToStore.getSimpleValueType();
20164   SDValue Mask = N->getMask();
20165   SDLoc dl(Op);
20166
20167   if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20168       !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20169     // This operation is legal for targets with VLX, but without
20170     // VLX the vector should be widened to 512 bit
20171     unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20172     MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20173     MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20174     DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
20175     Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20176     return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
20177                               Mask, N->getMemoryVT(), N->getMemOperand(),
20178                               N->isTruncatingStore());
20179   }
20180   return Op;
20181 }
20182
20183 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
20184                             SelectionDAG &DAG) {
20185   assert(Subtarget->hasAVX512() &&
20186          "MGATHER/MSCATTER are supported on AVX-512 arch only");
20187
20188   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
20189   SDLoc dl(Op);
20190   MVT VT = Op.getSimpleValueType();
20191   SDValue Index = N->getIndex();
20192   SDValue Mask = N->getMask();
20193   SDValue Src0 = N->getValue();
20194   MVT IndexVT = Index.getSimpleValueType();
20195   MVT MaskVT = Mask.getSimpleValueType();
20196
20197   unsigned NumElts = VT.getVectorNumElements();
20198   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
20199
20200   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20201       !Index.getSimpleValueType().is512BitVector()) {
20202     // AVX512F supports only 512-bit vectors. Or data or index should
20203     // be 512 bit wide. If now the both index and data are 256-bit, but
20204     // the vector contains 8 elements, we just sign-extend the index
20205     if (NumElts == 8) {
20206       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20207       SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
20208                         N->getOperand(3), Index };
20209       DAG.UpdateNodeOperands(N, Ops);
20210       return Op;
20211     }
20212
20213     // Minimal number of elements in Gather
20214     NumElts = 8;
20215     // Index
20216     MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20217     Index = ExtendToType(Index, NewIndexVT, DAG);
20218     if (IndexVT.getScalarType() == MVT::i32)
20219       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20220
20221     // Mask
20222     MVT MaskBitVT = MVT::getVectorVT(MVT::i1, NumElts);
20223     // At this point we have promoted mask operand
20224     assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20225     MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20226     Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20227     Mask = DAG.getNode(ISD::TRUNCATE, dl, MaskBitVT, Mask);
20228
20229     // The pass-thru value
20230     MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20231     Src0 = ExtendToType(Src0, NewVT, DAG);
20232
20233     SDValue Ops[] = { N->getChain(), Src0, Mask, N->getBasePtr(), Index };
20234     SDValue NewGather = DAG.getMaskedGather(DAG.getVTList(NewVT, MVT::Other),
20235                                             N->getMemoryVT(), dl, Ops,
20236                                             N->getMemOperand());
20237     SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20238                                  NewGather.getValue(0),
20239                                  DAG.getIntPtrConstant(0, dl));
20240     SDValue RetOps[] = {Exract, NewGather.getValue(1)};
20241     return DAG.getMergeValues(RetOps, dl);
20242   }
20243   return Op;
20244 }
20245
20246 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
20247                                                     SelectionDAG &DAG) const {
20248   // TODO: Eventually, the lowering of these nodes should be informed by or
20249   // deferred to the GC strategy for the function in which they appear. For
20250   // now, however, they must be lowered to something. Since they are logically
20251   // no-ops in the case of a null GC strategy (or a GC strategy which does not
20252   // require special handling for these nodes), lower them as literal NOOPs for
20253   // the time being.
20254   SmallVector<SDValue, 2> Ops;
20255
20256   Ops.push_back(Op.getOperand(0));
20257   if (Op->getGluedNode())
20258     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20259
20260   SDLoc OpDL(Op);
20261   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20262   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20263
20264   return NOOP;
20265 }
20266
20267 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
20268                                                   SelectionDAG &DAG) const {
20269   // TODO: Eventually, the lowering of these nodes should be informed by or
20270   // deferred to the GC strategy for the function in which they appear. For
20271   // now, however, they must be lowered to something. Since they are logically
20272   // no-ops in the case of a null GC strategy (or a GC strategy which does not
20273   // require special handling for these nodes), lower them as literal NOOPs for
20274   // the time being.
20275   SmallVector<SDValue, 2> Ops;
20276
20277   Ops.push_back(Op.getOperand(0));
20278   if (Op->getGluedNode())
20279     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20280
20281   SDLoc OpDL(Op);
20282   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20283   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20284
20285   return NOOP;
20286 }
20287
20288 /// LowerOperation - Provide custom lowering hooks for some operations.
20289 ///
20290 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
20291   switch (Op.getOpcode()) {
20292   default: llvm_unreachable("Should not custom lower this!");
20293   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
20294   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
20295     return LowerCMP_SWAP(Op, Subtarget, DAG);
20296   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
20297   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
20298   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
20299   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
20300   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
20301   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
20302   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
20303   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
20304   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
20305   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
20306   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
20307   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
20308   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
20309   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
20310   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
20311   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
20312   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
20313   case ISD::SHL_PARTS:
20314   case ISD::SRA_PARTS:
20315   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
20316   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
20317   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
20318   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
20319   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
20320   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
20321   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
20322   case ISD::SIGN_EXTEND_VECTOR_INREG:
20323     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
20324   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
20325   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
20326   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
20327   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
20328   case ISD::FABS:
20329   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
20330   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
20331   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
20332   case ISD::SETCC:              return LowerSETCC(Op, DAG);
20333   case ISD::SETCCE:             return LowerSETCCE(Op, DAG);
20334   case ISD::SELECT:             return LowerSELECT(Op, DAG);
20335   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
20336   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
20337   case ISD::VASTART:            return LowerVASTART(Op, DAG);
20338   case ISD::VAARG:              return LowerVAARG(Op, DAG);
20339   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
20340   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
20341   case ISD::INTRINSIC_VOID:
20342   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
20343   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
20344   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
20345   case ISD::FRAME_TO_ARGS_OFFSET:
20346                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
20347   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
20348   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
20349   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
20350   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
20351   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
20352   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
20353   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
20354   case ISD::CTLZ:               return LowerCTLZ(Op, Subtarget, DAG);
20355   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
20356   case ISD::CTTZ:
20357   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
20358   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
20359   case ISD::UMUL_LOHI:
20360   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
20361   case ISD::ROTL:               return LowerRotate(Op, Subtarget, DAG);
20362   case ISD::SRA:
20363   case ISD::SRL:
20364   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
20365   case ISD::SADDO:
20366   case ISD::UADDO:
20367   case ISD::SSUBO:
20368   case ISD::USUBO:
20369   case ISD::SMULO:
20370   case ISD::UMULO:              return LowerXALUO(Op, DAG);
20371   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
20372   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
20373   case ISD::ADDC:
20374   case ISD::ADDE:
20375   case ISD::SUBC:
20376   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
20377   case ISD::ADD:                return LowerADD(Op, DAG);
20378   case ISD::SUB:                return LowerSUB(Op, DAG);
20379   case ISD::SMAX:
20380   case ISD::SMIN:
20381   case ISD::UMAX:
20382   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
20383   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
20384   case ISD::MLOAD:              return LowerMLOAD(Op, Subtarget, DAG);
20385   case ISD::MSTORE:             return LowerMSTORE(Op, Subtarget, DAG);
20386   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
20387   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
20388   case ISD::GC_TRANSITION_START:
20389                                 return LowerGC_TRANSITION_START(Op, DAG);
20390   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
20391   }
20392 }
20393
20394 /// ReplaceNodeResults - Replace a node with an illegal result type
20395 /// with a new node built out of custom code.
20396 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
20397                                            SmallVectorImpl<SDValue>&Results,
20398                                            SelectionDAG &DAG) const {
20399   SDLoc dl(N);
20400   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20401   switch (N->getOpcode()) {
20402   default:
20403     llvm_unreachable("Do not know how to custom type legalize this operation!");
20404   case X86ISD::AVG: {
20405     // Legalize types for X86ISD::AVG by expanding vectors.
20406     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20407
20408     auto InVT = N->getValueType(0);
20409     auto InVTSize = InVT.getSizeInBits();
20410     const unsigned RegSize =
20411         (InVTSize > 128) ? ((InVTSize > 256) ? 512 : 256) : 128;
20412     assert((!Subtarget->hasAVX512() || RegSize < 512) &&
20413            "512-bit vector requires AVX512");
20414     assert((!Subtarget->hasAVX2() || RegSize < 256) &&
20415            "256-bit vector requires AVX2");
20416
20417     auto ElemVT = InVT.getVectorElementType();
20418     auto RegVT = EVT::getVectorVT(*DAG.getContext(), ElemVT,
20419                                   RegSize / ElemVT.getSizeInBits());
20420     assert(RegSize % InVT.getSizeInBits() == 0);
20421     unsigned NumConcat = RegSize / InVT.getSizeInBits();
20422
20423     SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
20424     Ops[0] = N->getOperand(0);
20425     SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20426     Ops[0] = N->getOperand(1);
20427     SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20428
20429     SDValue Res = DAG.getNode(X86ISD::AVG, dl, RegVT, InVec0, InVec1);
20430     Results.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InVT, Res,
20431                                   DAG.getIntPtrConstant(0, dl)));
20432     return;
20433   }
20434   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
20435   case X86ISD::FMINC:
20436   case X86ISD::FMIN:
20437   case X86ISD::FMAXC:
20438   case X86ISD::FMAX: {
20439     EVT VT = N->getValueType(0);
20440     assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
20441     SDValue UNDEF = DAG.getUNDEF(VT);
20442     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20443                               N->getOperand(0), UNDEF);
20444     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20445                               N->getOperand(1), UNDEF);
20446     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
20447     return;
20448   }
20449   case ISD::SIGN_EXTEND_INREG:
20450   case ISD::ADDC:
20451   case ISD::ADDE:
20452   case ISD::SUBC:
20453   case ISD::SUBE:
20454     // We don't want to expand or promote these.
20455     return;
20456   case ISD::SDIV:
20457   case ISD::UDIV:
20458   case ISD::SREM:
20459   case ISD::UREM:
20460   case ISD::SDIVREM:
20461   case ISD::UDIVREM: {
20462     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
20463     Results.push_back(V);
20464     return;
20465   }
20466   case ISD::FP_TO_SINT:
20467   case ISD::FP_TO_UINT: {
20468     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
20469
20470     std::pair<SDValue,SDValue> Vals =
20471         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
20472     SDValue FIST = Vals.first, StackSlot = Vals.second;
20473     if (FIST.getNode()) {
20474       EVT VT = N->getValueType(0);
20475       // Return a load from the stack slot.
20476       if (StackSlot.getNode())
20477         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
20478                                       MachinePointerInfo(),
20479                                       false, false, false, 0));
20480       else
20481         Results.push_back(FIST);
20482     }
20483     return;
20484   }
20485   case ISD::UINT_TO_FP: {
20486     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20487     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
20488         N->getValueType(0) != MVT::v2f32)
20489       return;
20490     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
20491                                  N->getOperand(0));
20492     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
20493                                      MVT::f64);
20494     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
20495     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
20496                              DAG.getBitcast(MVT::v2i64, VBias));
20497     Or = DAG.getBitcast(MVT::v2f64, Or);
20498     // TODO: Are there any fast-math-flags to propagate here?
20499     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
20500     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
20501     return;
20502   }
20503   case ISD::FP_ROUND: {
20504     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
20505         return;
20506     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
20507     Results.push_back(V);
20508     return;
20509   }
20510   case ISD::FP_EXTEND: {
20511     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
20512     // No other ValueType for FP_EXTEND should reach this point.
20513     assert(N->getValueType(0) == MVT::v2f32 &&
20514            "Do not know how to legalize this Node");
20515     return;
20516   }
20517   case ISD::INTRINSIC_W_CHAIN: {
20518     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
20519     switch (IntNo) {
20520     default : llvm_unreachable("Do not know how to custom type "
20521                                "legalize this intrinsic operation!");
20522     case Intrinsic::x86_rdtsc:
20523       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20524                                      Results);
20525     case Intrinsic::x86_rdtscp:
20526       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
20527                                      Results);
20528     case Intrinsic::x86_rdpmc:
20529       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
20530     }
20531   }
20532   case ISD::INTRINSIC_WO_CHAIN: {
20533     if (SDValue V = LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), Subtarget, DAG))
20534       Results.push_back(V);
20535     return;
20536   }
20537   case ISD::READCYCLECOUNTER: {
20538     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20539                                    Results);
20540   }
20541   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
20542     EVT T = N->getValueType(0);
20543     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
20544     bool Regs64bit = T == MVT::i128;
20545     MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
20546     SDValue cpInL, cpInH;
20547     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20548                         DAG.getConstant(0, dl, HalfT));
20549     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20550                         DAG.getConstant(1, dl, HalfT));
20551     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
20552                              Regs64bit ? X86::RAX : X86::EAX,
20553                              cpInL, SDValue());
20554     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
20555                              Regs64bit ? X86::RDX : X86::EDX,
20556                              cpInH, cpInL.getValue(1));
20557     SDValue swapInL, swapInH;
20558     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20559                           DAG.getConstant(0, dl, HalfT));
20560     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20561                           DAG.getConstant(1, dl, HalfT));
20562     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
20563                                Regs64bit ? X86::RBX : X86::EBX,
20564                                swapInL, cpInH.getValue(1));
20565     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
20566                                Regs64bit ? X86::RCX : X86::ECX,
20567                                swapInH, swapInL.getValue(1));
20568     SDValue Ops[] = { swapInH.getValue(0),
20569                       N->getOperand(1),
20570                       swapInH.getValue(1) };
20571     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
20572     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
20573     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
20574                                   X86ISD::LCMPXCHG8_DAG;
20575     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
20576     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
20577                                         Regs64bit ? X86::RAX : X86::EAX,
20578                                         HalfT, Result.getValue(1));
20579     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
20580                                         Regs64bit ? X86::RDX : X86::EDX,
20581                                         HalfT, cpOutL.getValue(2));
20582     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
20583
20584     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
20585                                         MVT::i32, cpOutH.getValue(2));
20586     SDValue Success =
20587         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
20588                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
20589     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
20590
20591     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
20592     Results.push_back(Success);
20593     Results.push_back(EFLAGS.getValue(1));
20594     return;
20595   }
20596   case ISD::ATOMIC_SWAP:
20597   case ISD::ATOMIC_LOAD_ADD:
20598   case ISD::ATOMIC_LOAD_SUB:
20599   case ISD::ATOMIC_LOAD_AND:
20600   case ISD::ATOMIC_LOAD_OR:
20601   case ISD::ATOMIC_LOAD_XOR:
20602   case ISD::ATOMIC_LOAD_NAND:
20603   case ISD::ATOMIC_LOAD_MIN:
20604   case ISD::ATOMIC_LOAD_MAX:
20605   case ISD::ATOMIC_LOAD_UMIN:
20606   case ISD::ATOMIC_LOAD_UMAX:
20607   case ISD::ATOMIC_LOAD: {
20608     // Delegate to generic TypeLegalization. Situations we can really handle
20609     // should have already been dealt with by AtomicExpandPass.cpp.
20610     break;
20611   }
20612   case ISD::BITCAST: {
20613     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20614     EVT DstVT = N->getValueType(0);
20615     EVT SrcVT = N->getOperand(0)->getValueType(0);
20616
20617     if (SrcVT != MVT::f64 ||
20618         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
20619       return;
20620
20621     unsigned NumElts = DstVT.getVectorNumElements();
20622     EVT SVT = DstVT.getVectorElementType();
20623     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
20624     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
20625                                    MVT::v2f64, N->getOperand(0));
20626     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
20627
20628     if (ExperimentalVectorWideningLegalization) {
20629       // If we are legalizing vectors by widening, we already have the desired
20630       // legal vector type, just return it.
20631       Results.push_back(ToVecInt);
20632       return;
20633     }
20634
20635     SmallVector<SDValue, 8> Elts;
20636     for (unsigned i = 0, e = NumElts; i != e; ++i)
20637       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
20638                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
20639
20640     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
20641   }
20642   }
20643 }
20644
20645 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
20646   switch ((X86ISD::NodeType)Opcode) {
20647   case X86ISD::FIRST_NUMBER:       break;
20648   case X86ISD::BSF:                return "X86ISD::BSF";
20649   case X86ISD::BSR:                return "X86ISD::BSR";
20650   case X86ISD::SHLD:               return "X86ISD::SHLD";
20651   case X86ISD::SHRD:               return "X86ISD::SHRD";
20652   case X86ISD::FAND:               return "X86ISD::FAND";
20653   case X86ISD::FANDN:              return "X86ISD::FANDN";
20654   case X86ISD::FOR:                return "X86ISD::FOR";
20655   case X86ISD::FXOR:               return "X86ISD::FXOR";
20656   case X86ISD::FILD:               return "X86ISD::FILD";
20657   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
20658   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
20659   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
20660   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
20661   case X86ISD::FLD:                return "X86ISD::FLD";
20662   case X86ISD::FST:                return "X86ISD::FST";
20663   case X86ISD::CALL:               return "X86ISD::CALL";
20664   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
20665   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
20666   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
20667   case X86ISD::BT:                 return "X86ISD::BT";
20668   case X86ISD::CMP:                return "X86ISD::CMP";
20669   case X86ISD::COMI:               return "X86ISD::COMI";
20670   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
20671   case X86ISD::CMPM:               return "X86ISD::CMPM";
20672   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
20673   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
20674   case X86ISD::SETCC:              return "X86ISD::SETCC";
20675   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
20676   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
20677   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
20678   case X86ISD::CMOV:               return "X86ISD::CMOV";
20679   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
20680   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
20681   case X86ISD::IRET:               return "X86ISD::IRET";
20682   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
20683   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
20684   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
20685   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
20686   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
20687   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
20688   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
20689   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
20690   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
20691   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
20692   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
20693   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
20694   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
20695   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
20696   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
20697   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
20698   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
20699   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
20700   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
20701   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
20702   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
20703   case X86ISD::HADD:               return "X86ISD::HADD";
20704   case X86ISD::HSUB:               return "X86ISD::HSUB";
20705   case X86ISD::FHADD:              return "X86ISD::FHADD";
20706   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
20707   case X86ISD::ABS:                return "X86ISD::ABS";
20708   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
20709   case X86ISD::FMAX:               return "X86ISD::FMAX";
20710   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
20711   case X86ISD::FMIN:               return "X86ISD::FMIN";
20712   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
20713   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
20714   case X86ISD::FMINC:              return "X86ISD::FMINC";
20715   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
20716   case X86ISD::FRCP:               return "X86ISD::FRCP";
20717   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
20718   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
20719   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
20720   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
20721   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
20722   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
20723   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
20724   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
20725   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
20726   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
20727   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
20728   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
20729   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
20730   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
20731   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
20732   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
20733   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
20734   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
20735   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
20736   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
20737   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
20738   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
20739   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
20740   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
20741   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
20742   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
20743   case X86ISD::CVT2MASK:           return "X86ISD::CVT2MASK";
20744   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
20745   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
20746   case X86ISD::VSHL:               return "X86ISD::VSHL";
20747   case X86ISD::VSRL:               return "X86ISD::VSRL";
20748   case X86ISD::VSRA:               return "X86ISD::VSRA";
20749   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
20750   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
20751   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
20752   case X86ISD::CMPP:               return "X86ISD::CMPP";
20753   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
20754   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
20755   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
20756   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
20757   case X86ISD::ADD:                return "X86ISD::ADD";
20758   case X86ISD::SUB:                return "X86ISD::SUB";
20759   case X86ISD::ADC:                return "X86ISD::ADC";
20760   case X86ISD::SBB:                return "X86ISD::SBB";
20761   case X86ISD::SMUL:               return "X86ISD::SMUL";
20762   case X86ISD::UMUL:               return "X86ISD::UMUL";
20763   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
20764   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
20765   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20766   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20767   case X86ISD::INC:                return "X86ISD::INC";
20768   case X86ISD::DEC:                return "X86ISD::DEC";
20769   case X86ISD::OR:                 return "X86ISD::OR";
20770   case X86ISD::XOR:                return "X86ISD::XOR";
20771   case X86ISD::AND:                return "X86ISD::AND";
20772   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
20773   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
20774   case X86ISD::PTEST:              return "X86ISD::PTEST";
20775   case X86ISD::TESTP:              return "X86ISD::TESTP";
20776   case X86ISD::TESTM:              return "X86ISD::TESTM";
20777   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
20778   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
20779   case X86ISD::KTEST:              return "X86ISD::KTEST";
20780   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
20781   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
20782   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
20783   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
20784   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
20785   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
20786   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
20787   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
20788   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
20789   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
20790   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
20791   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
20792   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
20793   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
20794   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
20795   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
20796   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
20797   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
20798   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
20799   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
20800   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
20801   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
20802   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
20803   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
20804   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
20805   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
20806   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
20807   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
20808   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
20809   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
20810   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
20811   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
20812   case X86ISD::VPTERNLOG:          return "X86ISD::VPTERNLOG";
20813   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
20814   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
20815   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
20816   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
20817   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
20818   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
20819   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20820   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
20821   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
20822   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
20823   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
20824   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
20825   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
20826   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
20827   case X86ISD::SAHF:               return "X86ISD::SAHF";
20828   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
20829   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
20830   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
20831   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
20832   case X86ISD::VPROT:              return "X86ISD::VPROT";
20833   case X86ISD::VPROTI:             return "X86ISD::VPROTI";
20834   case X86ISD::VPSHA:              return "X86ISD::VPSHA";
20835   case X86ISD::VPSHL:              return "X86ISD::VPSHL";
20836   case X86ISD::VPCOM:              return "X86ISD::VPCOM";
20837   case X86ISD::VPCOMU:             return "X86ISD::VPCOMU";
20838   case X86ISD::FMADD:              return "X86ISD::FMADD";
20839   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
20840   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
20841   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
20842   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
20843   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
20844   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
20845   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
20846   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
20847   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
20848   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
20849   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
20850   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
20851   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
20852   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
20853   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
20854   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
20855   case X86ISD::XTEST:              return "X86ISD::XTEST";
20856   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
20857   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
20858   case X86ISD::SELECT:             return "X86ISD::SELECT";
20859   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
20860   case X86ISD::RCP28:              return "X86ISD::RCP28";
20861   case X86ISD::EXP2:               return "X86ISD::EXP2";
20862   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
20863   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
20864   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
20865   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
20866   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
20867   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
20868   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
20869   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
20870   case X86ISD::ADDS:               return "X86ISD::ADDS";
20871   case X86ISD::SUBS:               return "X86ISD::SUBS";
20872   case X86ISD::AVG:                return "X86ISD::AVG";
20873   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
20874   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
20875   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
20876   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
20877   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
20878   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
20879   case X86ISD::VFPCLASSS:          return "X86ISD::VFPCLASSS";
20880   }
20881   return nullptr;
20882 }
20883
20884 // isLegalAddressingMode - Return true if the addressing mode represented
20885 // by AM is legal for this target, for a load/store of the specified type.
20886 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20887                                               const AddrMode &AM, Type *Ty,
20888                                               unsigned AS) const {
20889   // X86 supports extremely general addressing modes.
20890   CodeModel::Model M = getTargetMachine().getCodeModel();
20891   Reloc::Model R = getTargetMachine().getRelocationModel();
20892
20893   // X86 allows a sign-extended 32-bit immediate field as a displacement.
20894   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20895     return false;
20896
20897   if (AM.BaseGV) {
20898     unsigned GVFlags =
20899       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20900
20901     // If a reference to this global requires an extra load, we can't fold it.
20902     if (isGlobalStubReference(GVFlags))
20903       return false;
20904
20905     // If BaseGV requires a register for the PIC base, we cannot also have a
20906     // BaseReg specified.
20907     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20908       return false;
20909
20910     // If lower 4G is not available, then we must use rip-relative addressing.
20911     if ((M != CodeModel::Small || R != Reloc::Static) &&
20912         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20913       return false;
20914   }
20915
20916   switch (AM.Scale) {
20917   case 0:
20918   case 1:
20919   case 2:
20920   case 4:
20921   case 8:
20922     // These scales always work.
20923     break;
20924   case 3:
20925   case 5:
20926   case 9:
20927     // These scales are formed with basereg+scalereg.  Only accept if there is
20928     // no basereg yet.
20929     if (AM.HasBaseReg)
20930       return false;
20931     break;
20932   default:  // Other stuff never works.
20933     return false;
20934   }
20935
20936   return true;
20937 }
20938
20939 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20940   unsigned Bits = Ty->getScalarSizeInBits();
20941
20942   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20943   // particularly cheaper than those without.
20944   if (Bits == 8)
20945     return false;
20946
20947   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20948   // variable shifts just as cheap as scalar ones.
20949   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20950     return false;
20951
20952   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20953   // fully general vector.
20954   return true;
20955 }
20956
20957 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20958   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20959     return false;
20960   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20961   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20962   return NumBits1 > NumBits2;
20963 }
20964
20965 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20966   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20967     return false;
20968
20969   if (!isTypeLegal(EVT::getEVT(Ty1)))
20970     return false;
20971
20972   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20973
20974   // Assuming the caller doesn't have a zeroext or signext return parameter,
20975   // truncation all the way down to i1 is valid.
20976   return true;
20977 }
20978
20979 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20980   return isInt<32>(Imm);
20981 }
20982
20983 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20984   // Can also use sub to handle negated immediates.
20985   return isInt<32>(Imm);
20986 }
20987
20988 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20989   if (!VT1.isInteger() || !VT2.isInteger())
20990     return false;
20991   unsigned NumBits1 = VT1.getSizeInBits();
20992   unsigned NumBits2 = VT2.getSizeInBits();
20993   return NumBits1 > NumBits2;
20994 }
20995
20996 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20997   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20998   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20999 }
21000
21001 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
21002   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
21003   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
21004 }
21005
21006 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
21007   EVT VT1 = Val.getValueType();
21008   if (isZExtFree(VT1, VT2))
21009     return true;
21010
21011   if (Val.getOpcode() != ISD::LOAD)
21012     return false;
21013
21014   if (!VT1.isSimple() || !VT1.isInteger() ||
21015       !VT2.isSimple() || !VT2.isInteger())
21016     return false;
21017
21018   switch (VT1.getSimpleVT().SimpleTy) {
21019   default: break;
21020   case MVT::i8:
21021   case MVT::i16:
21022   case MVT::i32:
21023     // X86 has 8, 16, and 32-bit zero-extending loads.
21024     return true;
21025   }
21026
21027   return false;
21028 }
21029
21030 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
21031
21032 bool
21033 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
21034   if (!Subtarget->hasAnyFMA())
21035     return false;
21036
21037   VT = VT.getScalarType();
21038
21039   if (!VT.isSimple())
21040     return false;
21041
21042   switch (VT.getSimpleVT().SimpleTy) {
21043   case MVT::f32:
21044   case MVT::f64:
21045     return true;
21046   default:
21047     break;
21048   }
21049
21050   return false;
21051 }
21052
21053 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
21054   // i16 instructions are longer (0x66 prefix) and potentially slower.
21055   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
21056 }
21057
21058 /// isShuffleMaskLegal - Targets can use this to indicate that they only
21059 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
21060 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
21061 /// are assumed to be legal.
21062 bool
21063 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
21064                                       EVT VT) const {
21065   if (!VT.isSimple())
21066     return false;
21067
21068   // Not for i1 vectors
21069   if (VT.getSimpleVT().getScalarType() == MVT::i1)
21070     return false;
21071
21072   // Very little shuffling can be done for 64-bit vectors right now.
21073   if (VT.getSimpleVT().getSizeInBits() == 64)
21074     return false;
21075
21076   // We only care that the types being shuffled are legal. The lowering can
21077   // handle any possible shuffle mask that results.
21078   return isTypeLegal(VT.getSimpleVT());
21079 }
21080
21081 bool
21082 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
21083                                           EVT VT) const {
21084   // Just delegate to the generic legality, clear masks aren't special.
21085   return isShuffleMaskLegal(Mask, VT);
21086 }
21087
21088 //===----------------------------------------------------------------------===//
21089 //                           X86 Scheduler Hooks
21090 //===----------------------------------------------------------------------===//
21091
21092 /// Utility function to emit xbegin specifying the start of an RTM region.
21093 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
21094                                      const TargetInstrInfo *TII) {
21095   DebugLoc DL = MI->getDebugLoc();
21096
21097   const BasicBlock *BB = MBB->getBasicBlock();
21098   MachineFunction::iterator I = ++MBB->getIterator();
21099
21100   // For the v = xbegin(), we generate
21101   //
21102   // thisMBB:
21103   //  xbegin sinkMBB
21104   //
21105   // mainMBB:
21106   //  eax = -1
21107   //
21108   // sinkMBB:
21109   //  v = eax
21110
21111   MachineBasicBlock *thisMBB = MBB;
21112   MachineFunction *MF = MBB->getParent();
21113   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21114   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21115   MF->insert(I, mainMBB);
21116   MF->insert(I, sinkMBB);
21117
21118   // Transfer the remainder of BB and its successor edges to sinkMBB.
21119   sinkMBB->splice(sinkMBB->begin(), MBB,
21120                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21121   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21122
21123   // thisMBB:
21124   //  xbegin sinkMBB
21125   //  # fallthrough to mainMBB
21126   //  # abortion to sinkMBB
21127   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
21128   thisMBB->addSuccessor(mainMBB);
21129   thisMBB->addSuccessor(sinkMBB);
21130
21131   // mainMBB:
21132   //  EAX = -1
21133   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
21134   mainMBB->addSuccessor(sinkMBB);
21135
21136   // sinkMBB:
21137   // EAX is live into the sinkMBB
21138   sinkMBB->addLiveIn(X86::EAX);
21139   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21140           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21141     .addReg(X86::EAX);
21142
21143   MI->eraseFromParent();
21144   return sinkMBB;
21145 }
21146
21147 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
21148 // or XMM0_V32I8 in AVX all of this code can be replaced with that
21149 // in the .td file.
21150 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
21151                                        const TargetInstrInfo *TII) {
21152   unsigned Opc;
21153   switch (MI->getOpcode()) {
21154   default: llvm_unreachable("illegal opcode!");
21155   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
21156   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
21157   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
21158   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
21159   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
21160   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
21161   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
21162   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
21163   }
21164
21165   DebugLoc dl = MI->getDebugLoc();
21166   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21167
21168   unsigned NumArgs = MI->getNumOperands();
21169   for (unsigned i = 1; i < NumArgs; ++i) {
21170     MachineOperand &Op = MI->getOperand(i);
21171     if (!(Op.isReg() && Op.isImplicit()))
21172       MIB.addOperand(Op);
21173   }
21174   if (MI->hasOneMemOperand())
21175     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21176
21177   BuildMI(*BB, MI, dl,
21178     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21179     .addReg(X86::XMM0);
21180
21181   MI->eraseFromParent();
21182   return BB;
21183 }
21184
21185 // FIXME: Custom handling because TableGen doesn't support multiple implicit
21186 // defs in an instruction pattern
21187 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
21188                                        const TargetInstrInfo *TII) {
21189   unsigned Opc;
21190   switch (MI->getOpcode()) {
21191   default: llvm_unreachable("illegal opcode!");
21192   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
21193   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
21194   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
21195   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
21196   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
21197   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
21198   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
21199   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
21200   }
21201
21202   DebugLoc dl = MI->getDebugLoc();
21203   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21204
21205   unsigned NumArgs = MI->getNumOperands(); // remove the results
21206   for (unsigned i = 1; i < NumArgs; ++i) {
21207     MachineOperand &Op = MI->getOperand(i);
21208     if (!(Op.isReg() && Op.isImplicit()))
21209       MIB.addOperand(Op);
21210   }
21211   if (MI->hasOneMemOperand())
21212     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21213
21214   BuildMI(*BB, MI, dl,
21215     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21216     .addReg(X86::ECX);
21217
21218   MI->eraseFromParent();
21219   return BB;
21220 }
21221
21222 static MachineBasicBlock *EmitWRPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21223                                      const X86Subtarget *Subtarget) {
21224   DebugLoc dl = MI->getDebugLoc();
21225   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21226
21227   // insert input VAL into EAX
21228   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
21229                            .addReg(MI->getOperand(0).getReg());
21230   // insert zero to ECX
21231   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21232                            .addReg(X86::ECX)
21233                            .addReg(X86::ECX);
21234   // insert zero to EDX
21235   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::EDX)
21236                            .addReg(X86::EDX)
21237                            .addReg(X86::EDX);
21238   // insert WRPKRU instruction
21239   BuildMI(*BB, MI, dl, TII->get(X86::WRPKRUr));
21240
21241   MI->eraseFromParent(); // The pseudo is gone now.
21242   return BB;
21243 }
21244
21245 static MachineBasicBlock *EmitRDPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21246                                      const X86Subtarget *Subtarget) {
21247   DebugLoc dl = MI->getDebugLoc();
21248   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21249
21250   // insert zero to ECX
21251   BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21252                            .addReg(X86::ECX)
21253                            .addReg(X86::ECX);
21254   // insert RDPKRU instruction
21255   BuildMI(*BB, MI, dl, TII->get(X86::RDPKRUr));
21256   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21257                            .addReg(X86::EAX);
21258
21259   MI->eraseFromParent(); // The pseudo is gone now.
21260   return BB;
21261 }
21262
21263 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
21264                                       const X86Subtarget *Subtarget) {
21265   DebugLoc dl = MI->getDebugLoc();
21266   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21267   // Address into RAX/EAX, other two args into ECX, EDX.
21268   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
21269   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
21270   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
21271   for (int i = 0; i < X86::AddrNumOperands; ++i)
21272     MIB.addOperand(MI->getOperand(i));
21273
21274   unsigned ValOps = X86::AddrNumOperands;
21275   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
21276     .addReg(MI->getOperand(ValOps).getReg());
21277   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
21278     .addReg(MI->getOperand(ValOps+1).getReg());
21279
21280   // The instruction doesn't actually take any operands though.
21281   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
21282
21283   MI->eraseFromParent(); // The pseudo is gone now.
21284   return BB;
21285 }
21286
21287 MachineBasicBlock *
21288 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
21289                                                  MachineBasicBlock *MBB) const {
21290   // Emit va_arg instruction on X86-64.
21291
21292   // Operands to this pseudo-instruction:
21293   // 0  ) Output        : destination address (reg)
21294   // 1-5) Input         : va_list address (addr, i64mem)
21295   // 6  ) ArgSize       : Size (in bytes) of vararg type
21296   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
21297   // 8  ) Align         : Alignment of type
21298   // 9  ) EFLAGS (implicit-def)
21299
21300   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
21301   static_assert(X86::AddrNumOperands == 5,
21302                 "VAARG_64 assumes 5 address operands");
21303
21304   unsigned DestReg = MI->getOperand(0).getReg();
21305   MachineOperand &Base = MI->getOperand(1);
21306   MachineOperand &Scale = MI->getOperand(2);
21307   MachineOperand &Index = MI->getOperand(3);
21308   MachineOperand &Disp = MI->getOperand(4);
21309   MachineOperand &Segment = MI->getOperand(5);
21310   unsigned ArgSize = MI->getOperand(6).getImm();
21311   unsigned ArgMode = MI->getOperand(7).getImm();
21312   unsigned Align = MI->getOperand(8).getImm();
21313
21314   // Memory Reference
21315   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
21316   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21317   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21318
21319   // Machine Information
21320   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21321   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
21322   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
21323   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
21324   DebugLoc DL = MI->getDebugLoc();
21325
21326   // struct va_list {
21327   //   i32   gp_offset
21328   //   i32   fp_offset
21329   //   i64   overflow_area (address)
21330   //   i64   reg_save_area (address)
21331   // }
21332   // sizeof(va_list) = 24
21333   // alignment(va_list) = 8
21334
21335   unsigned TotalNumIntRegs = 6;
21336   unsigned TotalNumXMMRegs = 8;
21337   bool UseGPOffset = (ArgMode == 1);
21338   bool UseFPOffset = (ArgMode == 2);
21339   unsigned MaxOffset = TotalNumIntRegs * 8 +
21340                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
21341
21342   /* Align ArgSize to a multiple of 8 */
21343   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
21344   bool NeedsAlign = (Align > 8);
21345
21346   MachineBasicBlock *thisMBB = MBB;
21347   MachineBasicBlock *overflowMBB;
21348   MachineBasicBlock *offsetMBB;
21349   MachineBasicBlock *endMBB;
21350
21351   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
21352   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
21353   unsigned OffsetReg = 0;
21354
21355   if (!UseGPOffset && !UseFPOffset) {
21356     // If we only pull from the overflow region, we don't create a branch.
21357     // We don't need to alter control flow.
21358     OffsetDestReg = 0; // unused
21359     OverflowDestReg = DestReg;
21360
21361     offsetMBB = nullptr;
21362     overflowMBB = thisMBB;
21363     endMBB = thisMBB;
21364   } else {
21365     // First emit code to check if gp_offset (or fp_offset) is below the bound.
21366     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
21367     // If not, pull from overflow_area. (branch to overflowMBB)
21368     //
21369     //       thisMBB
21370     //         |     .
21371     //         |        .
21372     //     offsetMBB   overflowMBB
21373     //         |        .
21374     //         |     .
21375     //        endMBB
21376
21377     // Registers for the PHI in endMBB
21378     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
21379     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
21380
21381     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21382     MachineFunction *MF = MBB->getParent();
21383     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21384     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21385     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21386
21387     MachineFunction::iterator MBBIter = ++MBB->getIterator();
21388
21389     // Insert the new basic blocks
21390     MF->insert(MBBIter, offsetMBB);
21391     MF->insert(MBBIter, overflowMBB);
21392     MF->insert(MBBIter, endMBB);
21393
21394     // Transfer the remainder of MBB and its successor edges to endMBB.
21395     endMBB->splice(endMBB->begin(), thisMBB,
21396                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
21397     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
21398
21399     // Make offsetMBB and overflowMBB successors of thisMBB
21400     thisMBB->addSuccessor(offsetMBB);
21401     thisMBB->addSuccessor(overflowMBB);
21402
21403     // endMBB is a successor of both offsetMBB and overflowMBB
21404     offsetMBB->addSuccessor(endMBB);
21405     overflowMBB->addSuccessor(endMBB);
21406
21407     // Load the offset value into a register
21408     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21409     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
21410       .addOperand(Base)
21411       .addOperand(Scale)
21412       .addOperand(Index)
21413       .addDisp(Disp, UseFPOffset ? 4 : 0)
21414       .addOperand(Segment)
21415       .setMemRefs(MMOBegin, MMOEnd);
21416
21417     // Check if there is enough room left to pull this argument.
21418     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
21419       .addReg(OffsetReg)
21420       .addImm(MaxOffset + 8 - ArgSizeA8);
21421
21422     // Branch to "overflowMBB" if offset >= max
21423     // Fall through to "offsetMBB" otherwise
21424     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
21425       .addMBB(overflowMBB);
21426   }
21427
21428   // In offsetMBB, emit code to use the reg_save_area.
21429   if (offsetMBB) {
21430     assert(OffsetReg != 0);
21431
21432     // Read the reg_save_area address.
21433     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
21434     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
21435       .addOperand(Base)
21436       .addOperand(Scale)
21437       .addOperand(Index)
21438       .addDisp(Disp, 16)
21439       .addOperand(Segment)
21440       .setMemRefs(MMOBegin, MMOEnd);
21441
21442     // Zero-extend the offset
21443     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
21444       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
21445         .addImm(0)
21446         .addReg(OffsetReg)
21447         .addImm(X86::sub_32bit);
21448
21449     // Add the offset to the reg_save_area to get the final address.
21450     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
21451       .addReg(OffsetReg64)
21452       .addReg(RegSaveReg);
21453
21454     // Compute the offset for the next argument
21455     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21456     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
21457       .addReg(OffsetReg)
21458       .addImm(UseFPOffset ? 16 : 8);
21459
21460     // Store it back into the va_list.
21461     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
21462       .addOperand(Base)
21463       .addOperand(Scale)
21464       .addOperand(Index)
21465       .addDisp(Disp, UseFPOffset ? 4 : 0)
21466       .addOperand(Segment)
21467       .addReg(NextOffsetReg)
21468       .setMemRefs(MMOBegin, MMOEnd);
21469
21470     // Jump to endMBB
21471     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
21472       .addMBB(endMBB);
21473   }
21474
21475   //
21476   // Emit code to use overflow area
21477   //
21478
21479   // Load the overflow_area address into a register.
21480   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
21481   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
21482     .addOperand(Base)
21483     .addOperand(Scale)
21484     .addOperand(Index)
21485     .addDisp(Disp, 8)
21486     .addOperand(Segment)
21487     .setMemRefs(MMOBegin, MMOEnd);
21488
21489   // If we need to align it, do so. Otherwise, just copy the address
21490   // to OverflowDestReg.
21491   if (NeedsAlign) {
21492     // Align the overflow address
21493     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
21494     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
21495
21496     // aligned_addr = (addr + (align-1)) & ~(align-1)
21497     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
21498       .addReg(OverflowAddrReg)
21499       .addImm(Align-1);
21500
21501     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
21502       .addReg(TmpReg)
21503       .addImm(~(uint64_t)(Align-1));
21504   } else {
21505     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
21506       .addReg(OverflowAddrReg);
21507   }
21508
21509   // Compute the next overflow address after this argument.
21510   // (the overflow address should be kept 8-byte aligned)
21511   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
21512   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
21513     .addReg(OverflowDestReg)
21514     .addImm(ArgSizeA8);
21515
21516   // Store the new overflow address.
21517   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
21518     .addOperand(Base)
21519     .addOperand(Scale)
21520     .addOperand(Index)
21521     .addDisp(Disp, 8)
21522     .addOperand(Segment)
21523     .addReg(NextAddrReg)
21524     .setMemRefs(MMOBegin, MMOEnd);
21525
21526   // If we branched, emit the PHI to the front of endMBB.
21527   if (offsetMBB) {
21528     BuildMI(*endMBB, endMBB->begin(), DL,
21529             TII->get(X86::PHI), DestReg)
21530       .addReg(OffsetDestReg).addMBB(offsetMBB)
21531       .addReg(OverflowDestReg).addMBB(overflowMBB);
21532   }
21533
21534   // Erase the pseudo instruction
21535   MI->eraseFromParent();
21536
21537   return endMBB;
21538 }
21539
21540 MachineBasicBlock *
21541 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
21542                                                  MachineInstr *MI,
21543                                                  MachineBasicBlock *MBB) const {
21544   // Emit code to save XMM registers to the stack. The ABI says that the
21545   // number of registers to save is given in %al, so it's theoretically
21546   // possible to do an indirect jump trick to avoid saving all of them,
21547   // however this code takes a simpler approach and just executes all
21548   // of the stores if %al is non-zero. It's less code, and it's probably
21549   // easier on the hardware branch predictor, and stores aren't all that
21550   // expensive anyway.
21551
21552   // Create the new basic blocks. One block contains all the XMM stores,
21553   // and one block is the final destination regardless of whether any
21554   // stores were performed.
21555   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21556   MachineFunction *F = MBB->getParent();
21557   MachineFunction::iterator MBBIter = ++MBB->getIterator();
21558   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
21559   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
21560   F->insert(MBBIter, XMMSaveMBB);
21561   F->insert(MBBIter, EndMBB);
21562
21563   // Transfer the remainder of MBB and its successor edges to EndMBB.
21564   EndMBB->splice(EndMBB->begin(), MBB,
21565                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21566   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
21567
21568   // The original block will now fall through to the XMM save block.
21569   MBB->addSuccessor(XMMSaveMBB);
21570   // The XMMSaveMBB will fall through to the end block.
21571   XMMSaveMBB->addSuccessor(EndMBB);
21572
21573   // Now add the instructions.
21574   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21575   DebugLoc DL = MI->getDebugLoc();
21576
21577   unsigned CountReg = MI->getOperand(0).getReg();
21578   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
21579   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
21580
21581   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
21582     // If %al is 0, branch around the XMM save block.
21583     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
21584     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
21585     MBB->addSuccessor(EndMBB);
21586   }
21587
21588   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
21589   // that was just emitted, but clearly shouldn't be "saved".
21590   assert((MI->getNumOperands() <= 3 ||
21591           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
21592           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
21593          && "Expected last argument to be EFLAGS");
21594   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
21595   // In the XMM save block, save all the XMM argument registers.
21596   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
21597     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
21598     MachineMemOperand *MMO = F->getMachineMemOperand(
21599         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
21600         MachineMemOperand::MOStore,
21601         /*Size=*/16, /*Align=*/16);
21602     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
21603       .addFrameIndex(RegSaveFrameIndex)
21604       .addImm(/*Scale=*/1)
21605       .addReg(/*IndexReg=*/0)
21606       .addImm(/*Disp=*/Offset)
21607       .addReg(/*Segment=*/0)
21608       .addReg(MI->getOperand(i).getReg())
21609       .addMemOperand(MMO);
21610   }
21611
21612   MI->eraseFromParent();   // The pseudo instruction is gone now.
21613
21614   return EndMBB;
21615 }
21616
21617 // The EFLAGS operand of SelectItr might be missing a kill marker
21618 // because there were multiple uses of EFLAGS, and ISel didn't know
21619 // which to mark. Figure out whether SelectItr should have had a
21620 // kill marker, and set it if it should. Returns the correct kill
21621 // marker value.
21622 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
21623                                      MachineBasicBlock* BB,
21624                                      const TargetRegisterInfo* TRI) {
21625   // Scan forward through BB for a use/def of EFLAGS.
21626   MachineBasicBlock::iterator miI(std::next(SelectItr));
21627   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
21628     const MachineInstr& mi = *miI;
21629     if (mi.readsRegister(X86::EFLAGS))
21630       return false;
21631     if (mi.definesRegister(X86::EFLAGS))
21632       break; // Should have kill-flag - update below.
21633   }
21634
21635   // If we hit the end of the block, check whether EFLAGS is live into a
21636   // successor.
21637   if (miI == BB->end()) {
21638     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
21639                                           sEnd = BB->succ_end();
21640          sItr != sEnd; ++sItr) {
21641       MachineBasicBlock* succ = *sItr;
21642       if (succ->isLiveIn(X86::EFLAGS))
21643         return false;
21644     }
21645   }
21646
21647   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
21648   // out. SelectMI should have a kill flag on EFLAGS.
21649   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
21650   return true;
21651 }
21652
21653 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
21654 // together with other CMOV pseudo-opcodes into a single basic-block with
21655 // conditional jump around it.
21656 static bool isCMOVPseudo(MachineInstr *MI) {
21657   switch (MI->getOpcode()) {
21658   case X86::CMOV_FR32:
21659   case X86::CMOV_FR64:
21660   case X86::CMOV_GR8:
21661   case X86::CMOV_GR16:
21662   case X86::CMOV_GR32:
21663   case X86::CMOV_RFP32:
21664   case X86::CMOV_RFP64:
21665   case X86::CMOV_RFP80:
21666   case X86::CMOV_V2F64:
21667   case X86::CMOV_V2I64:
21668   case X86::CMOV_V4F32:
21669   case X86::CMOV_V4F64:
21670   case X86::CMOV_V4I64:
21671   case X86::CMOV_V16F32:
21672   case X86::CMOV_V8F32:
21673   case X86::CMOV_V8F64:
21674   case X86::CMOV_V8I64:
21675   case X86::CMOV_V8I1:
21676   case X86::CMOV_V16I1:
21677   case X86::CMOV_V32I1:
21678   case X86::CMOV_V64I1:
21679     return true;
21680
21681   default:
21682     return false;
21683   }
21684 }
21685
21686 MachineBasicBlock *
21687 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
21688                                      MachineBasicBlock *BB) const {
21689   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21690   DebugLoc DL = MI->getDebugLoc();
21691
21692   // To "insert" a SELECT_CC instruction, we actually have to insert the
21693   // diamond control-flow pattern.  The incoming instruction knows the
21694   // destination vreg to set, the condition code register to branch on, the
21695   // true/false values to select between, and a branch opcode to use.
21696   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21697   MachineFunction::iterator It = ++BB->getIterator();
21698
21699   //  thisMBB:
21700   //  ...
21701   //   TrueVal = ...
21702   //   cmpTY ccX, r1, r2
21703   //   bCC copy1MBB
21704   //   fallthrough --> copy0MBB
21705   MachineBasicBlock *thisMBB = BB;
21706   MachineFunction *F = BB->getParent();
21707
21708   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
21709   // as described above, by inserting a BB, and then making a PHI at the join
21710   // point to select the true and false operands of the CMOV in the PHI.
21711   //
21712   // The code also handles two different cases of multiple CMOV opcodes
21713   // in a row.
21714   //
21715   // Case 1:
21716   // In this case, there are multiple CMOVs in a row, all which are based on
21717   // the same condition setting (or the exact opposite condition setting).
21718   // In this case we can lower all the CMOVs using a single inserted BB, and
21719   // then make a number of PHIs at the join point to model the CMOVs. The only
21720   // trickiness here, is that in a case like:
21721   //
21722   // t2 = CMOV cond1 t1, f1
21723   // t3 = CMOV cond1 t2, f2
21724   //
21725   // when rewriting this into PHIs, we have to perform some renaming on the
21726   // temps since you cannot have a PHI operand refer to a PHI result earlier
21727   // in the same block.  The "simple" but wrong lowering would be:
21728   //
21729   // t2 = PHI t1(BB1), f1(BB2)
21730   // t3 = PHI t2(BB1), f2(BB2)
21731   //
21732   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
21733   // renaming is to note that on the path through BB1, t2 is really just a
21734   // copy of t1, and do that renaming, properly generating:
21735   //
21736   // t2 = PHI t1(BB1), f1(BB2)
21737   // t3 = PHI t1(BB1), f2(BB2)
21738   //
21739   // Case 2, we lower cascaded CMOVs such as
21740   //
21741   //   (CMOV (CMOV F, T, cc1), T, cc2)
21742   //
21743   // to two successives branches.  For that, we look for another CMOV as the
21744   // following instruction.
21745   //
21746   // Without this, we would add a PHI between the two jumps, which ends up
21747   // creating a few copies all around. For instance, for
21748   //
21749   //    (sitofp (zext (fcmp une)))
21750   //
21751   // we would generate:
21752   //
21753   //         ucomiss %xmm1, %xmm0
21754   //         movss  <1.0f>, %xmm0
21755   //         movaps  %xmm0, %xmm1
21756   //         jne     .LBB5_2
21757   //         xorps   %xmm1, %xmm1
21758   // .LBB5_2:
21759   //         jp      .LBB5_4
21760   //         movaps  %xmm1, %xmm0
21761   // .LBB5_4:
21762   //         retq
21763   //
21764   // because this custom-inserter would have generated:
21765   //
21766   //   A
21767   //   | \
21768   //   |  B
21769   //   | /
21770   //   C
21771   //   | \
21772   //   |  D
21773   //   | /
21774   //   E
21775   //
21776   // A: X = ...; Y = ...
21777   // B: empty
21778   // C: Z = PHI [X, A], [Y, B]
21779   // D: empty
21780   // E: PHI [X, C], [Z, D]
21781   //
21782   // If we lower both CMOVs in a single step, we can instead generate:
21783   //
21784   //   A
21785   //   | \
21786   //   |  C
21787   //   | /|
21788   //   |/ |
21789   //   |  |
21790   //   |  D
21791   //   | /
21792   //   E
21793   //
21794   // A: X = ...; Y = ...
21795   // D: empty
21796   // E: PHI [X, A], [X, C], [Y, D]
21797   //
21798   // Which, in our sitofp/fcmp example, gives us something like:
21799   //
21800   //         ucomiss %xmm1, %xmm0
21801   //         movss  <1.0f>, %xmm0
21802   //         jne     .LBB5_4
21803   //         jp      .LBB5_4
21804   //         xorps   %xmm0, %xmm0
21805   // .LBB5_4:
21806   //         retq
21807   //
21808   MachineInstr *CascadedCMOV = nullptr;
21809   MachineInstr *LastCMOV = MI;
21810   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21811   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21812   MachineBasicBlock::iterator NextMIIt =
21813       std::next(MachineBasicBlock::iterator(MI));
21814
21815   // Check for case 1, where there are multiple CMOVs with the same condition
21816   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
21817   // number of jumps the most.
21818
21819   if (isCMOVPseudo(MI)) {
21820     // See if we have a string of CMOVS with the same condition.
21821     while (NextMIIt != BB->end() &&
21822            isCMOVPseudo(NextMIIt) &&
21823            (NextMIIt->getOperand(3).getImm() == CC ||
21824             NextMIIt->getOperand(3).getImm() == OppCC)) {
21825       LastCMOV = &*NextMIIt;
21826       ++NextMIIt;
21827     }
21828   }
21829
21830   // This checks for case 2, but only do this if we didn't already find
21831   // case 1, as indicated by LastCMOV == MI.
21832   if (LastCMOV == MI &&
21833       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21834       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21835       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
21836     CascadedCMOV = &*NextMIIt;
21837   }
21838
21839   MachineBasicBlock *jcc1MBB = nullptr;
21840
21841   // If we have a cascaded CMOV, we lower it to two successive branches to
21842   // the same block.  EFLAGS is used by both, so mark it as live in the second.
21843   if (CascadedCMOV) {
21844     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21845     F->insert(It, jcc1MBB);
21846     jcc1MBB->addLiveIn(X86::EFLAGS);
21847   }
21848
21849   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21850   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21851   F->insert(It, copy0MBB);
21852   F->insert(It, sinkMBB);
21853
21854   // If the EFLAGS register isn't dead in the terminator, then claim that it's
21855   // live into the sink and copy blocks.
21856   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21857
21858   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21859   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21860       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21861     copy0MBB->addLiveIn(X86::EFLAGS);
21862     sinkMBB->addLiveIn(X86::EFLAGS);
21863   }
21864
21865   // Transfer the remainder of BB and its successor edges to sinkMBB.
21866   sinkMBB->splice(sinkMBB->begin(), BB,
21867                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21868   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21869
21870   // Add the true and fallthrough blocks as its successors.
21871   if (CascadedCMOV) {
21872     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21873     BB->addSuccessor(jcc1MBB);
21874
21875     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21876     // jump to the sinkMBB.
21877     jcc1MBB->addSuccessor(copy0MBB);
21878     jcc1MBB->addSuccessor(sinkMBB);
21879   } else {
21880     BB->addSuccessor(copy0MBB);
21881   }
21882
21883   // The true block target of the first (or only) branch is always sinkMBB.
21884   BB->addSuccessor(sinkMBB);
21885
21886   // Create the conditional branch instruction.
21887   unsigned Opc = X86::GetCondBranchFromCond(CC);
21888   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21889
21890   if (CascadedCMOV) {
21891     unsigned Opc2 = X86::GetCondBranchFromCond(
21892         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21893     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21894   }
21895
21896   //  copy0MBB:
21897   //   %FalseValue = ...
21898   //   # fallthrough to sinkMBB
21899   copy0MBB->addSuccessor(sinkMBB);
21900
21901   //  sinkMBB:
21902   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21903   //  ...
21904   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21905   MachineBasicBlock::iterator MIItEnd =
21906     std::next(MachineBasicBlock::iterator(LastCMOV));
21907   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21908   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21909   MachineInstrBuilder MIB;
21910
21911   // As we are creating the PHIs, we have to be careful if there is more than
21912   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
21913   // PHIs have to reference the individual true/false inputs from earlier PHIs.
21914   // That also means that PHI construction must work forward from earlier to
21915   // later, and that the code must maintain a mapping from earlier PHI's
21916   // destination registers, and the registers that went into the PHI.
21917
21918   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21919     unsigned DestReg = MIIt->getOperand(0).getReg();
21920     unsigned Op1Reg = MIIt->getOperand(1).getReg();
21921     unsigned Op2Reg = MIIt->getOperand(2).getReg();
21922
21923     // If this CMOV we are generating is the opposite condition from
21924     // the jump we generated, then we have to swap the operands for the
21925     // PHI that is going to be generated.
21926     if (MIIt->getOperand(3).getImm() == OppCC)
21927         std::swap(Op1Reg, Op2Reg);
21928
21929     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21930       Op1Reg = RegRewriteTable[Op1Reg].first;
21931
21932     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21933       Op2Reg = RegRewriteTable[Op2Reg].second;
21934
21935     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21936                   TII->get(X86::PHI), DestReg)
21937           .addReg(Op1Reg).addMBB(copy0MBB)
21938           .addReg(Op2Reg).addMBB(thisMBB);
21939
21940     // Add this PHI to the rewrite table.
21941     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21942   }
21943
21944   // If we have a cascaded CMOV, the second Jcc provides the same incoming
21945   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21946   if (CascadedCMOV) {
21947     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21948     // Copy the PHI result to the register defined by the second CMOV.
21949     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21950             DL, TII->get(TargetOpcode::COPY),
21951             CascadedCMOV->getOperand(0).getReg())
21952         .addReg(MI->getOperand(0).getReg());
21953     CascadedCMOV->eraseFromParent();
21954   }
21955
21956   // Now remove the CMOV(s).
21957   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
21958     (MIIt++)->eraseFromParent();
21959
21960   return sinkMBB;
21961 }
21962
21963 MachineBasicBlock *
21964 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
21965                                        MachineBasicBlock *BB) const {
21966   // Combine the following atomic floating-point modification pattern:
21967   //   a.store(reg OP a.load(acquire), release)
21968   // Transform them into:
21969   //   OPss (%gpr), %xmm
21970   //   movss %xmm, (%gpr)
21971   // Or sd equivalent for 64-bit operations.
21972   unsigned MOp, FOp;
21973   switch (MI->getOpcode()) {
21974   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
21975   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
21976   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
21977   }
21978   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21979   DebugLoc DL = MI->getDebugLoc();
21980   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
21981   MachineOperand MSrc = MI->getOperand(0);
21982   unsigned VSrc = MI->getOperand(5).getReg();
21983   const MachineOperand &Disp = MI->getOperand(3);
21984   MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
21985   bool hasDisp = Disp.isGlobal() || Disp.isImm();
21986   if (hasDisp && MSrc.isReg())
21987     MSrc.setIsKill(false);
21988   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
21989                                 .addOperand(/*Base=*/MSrc)
21990                                 .addImm(/*Scale=*/1)
21991                                 .addReg(/*Index=*/0)
21992                                 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21993                                 .addReg(0);
21994   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
21995                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
21996                           .addReg(VSrc)
21997                           .addOperand(/*Base=*/MSrc)
21998                           .addImm(/*Scale=*/1)
21999                           .addReg(/*Index=*/0)
22000                           .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
22001                           .addReg(/*Segment=*/0);
22002   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
22003   MI->eraseFromParent(); // The pseudo instruction is gone now.
22004   return BB;
22005 }
22006
22007 MachineBasicBlock *
22008 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
22009                                         MachineBasicBlock *BB) const {
22010   MachineFunction *MF = BB->getParent();
22011   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22012   DebugLoc DL = MI->getDebugLoc();
22013   const BasicBlock *LLVM_BB = BB->getBasicBlock();
22014
22015   assert(MF->shouldSplitStack());
22016
22017   const bool Is64Bit = Subtarget->is64Bit();
22018   const bool IsLP64 = Subtarget->isTarget64BitLP64();
22019
22020   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
22021   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
22022
22023   // BB:
22024   //  ... [Till the alloca]
22025   // If stacklet is not large enough, jump to mallocMBB
22026   //
22027   // bumpMBB:
22028   //  Allocate by subtracting from RSP
22029   //  Jump to continueMBB
22030   //
22031   // mallocMBB:
22032   //  Allocate by call to runtime
22033   //
22034   // continueMBB:
22035   //  ...
22036   //  [rest of original BB]
22037   //
22038
22039   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22040   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22041   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22042
22043   MachineRegisterInfo &MRI = MF->getRegInfo();
22044   const TargetRegisterClass *AddrRegClass =
22045       getRegClassFor(getPointerTy(MF->getDataLayout()));
22046
22047   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
22048     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
22049     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
22050     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
22051     sizeVReg = MI->getOperand(1).getReg(),
22052     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
22053
22054   MachineFunction::iterator MBBIter = ++BB->getIterator();
22055
22056   MF->insert(MBBIter, bumpMBB);
22057   MF->insert(MBBIter, mallocMBB);
22058   MF->insert(MBBIter, continueMBB);
22059
22060   continueMBB->splice(continueMBB->begin(), BB,
22061                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
22062   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
22063
22064   // Add code to the main basic block to check if the stack limit has been hit,
22065   // and if so, jump to mallocMBB otherwise to bumpMBB.
22066   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
22067   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
22068     .addReg(tmpSPVReg).addReg(sizeVReg);
22069   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
22070     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
22071     .addReg(SPLimitVReg);
22072   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
22073
22074   // bumpMBB simply decreases the stack pointer, since we know the current
22075   // stacklet has enough space.
22076   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
22077     .addReg(SPLimitVReg);
22078   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
22079     .addReg(SPLimitVReg);
22080   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22081
22082   // Calls into a routine in libgcc to allocate more space from the heap.
22083   const uint32_t *RegMask =
22084       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
22085   if (IsLP64) {
22086     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
22087       .addReg(sizeVReg);
22088     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22089       .addExternalSymbol("__morestack_allocate_stack_space")
22090       .addRegMask(RegMask)
22091       .addReg(X86::RDI, RegState::Implicit)
22092       .addReg(X86::RAX, RegState::ImplicitDefine);
22093   } else if (Is64Bit) {
22094     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
22095       .addReg(sizeVReg);
22096     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22097       .addExternalSymbol("__morestack_allocate_stack_space")
22098       .addRegMask(RegMask)
22099       .addReg(X86::EDI, RegState::Implicit)
22100       .addReg(X86::EAX, RegState::ImplicitDefine);
22101   } else {
22102     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
22103       .addImm(12);
22104     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
22105     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
22106       .addExternalSymbol("__morestack_allocate_stack_space")
22107       .addRegMask(RegMask)
22108       .addReg(X86::EAX, RegState::ImplicitDefine);
22109   }
22110
22111   if (!Is64Bit)
22112     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
22113       .addImm(16);
22114
22115   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
22116     .addReg(IsLP64 ? X86::RAX : X86::EAX);
22117   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22118
22119   // Set up the CFG correctly.
22120   BB->addSuccessor(bumpMBB);
22121   BB->addSuccessor(mallocMBB);
22122   mallocMBB->addSuccessor(continueMBB);
22123   bumpMBB->addSuccessor(continueMBB);
22124
22125   // Take care of the PHI nodes.
22126   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
22127           MI->getOperand(0).getReg())
22128     .addReg(mallocPtrVReg).addMBB(mallocMBB)
22129     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
22130
22131   // Delete the original pseudo instruction.
22132   MI->eraseFromParent();
22133
22134   // And we're done.
22135   return continueMBB;
22136 }
22137
22138 MachineBasicBlock *
22139 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
22140                                         MachineBasicBlock *BB) const {
22141   assert(!Subtarget->isTargetMachO());
22142   DebugLoc DL = MI->getDebugLoc();
22143   MachineInstr *ResumeMI = Subtarget->getFrameLowering()->emitStackProbe(
22144       *BB->getParent(), *BB, MI, DL, false);
22145   MachineBasicBlock *ResumeBB = ResumeMI->getParent();
22146   MI->eraseFromParent(); // The pseudo instruction is gone now.
22147   return ResumeBB;
22148 }
22149
22150 MachineBasicBlock *
22151 X86TargetLowering::EmitLoweredCatchRet(MachineInstr *MI,
22152                                        MachineBasicBlock *BB) const {
22153   MachineFunction *MF = BB->getParent();
22154   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22155   MachineBasicBlock *TargetMBB = MI->getOperand(0).getMBB();
22156   DebugLoc DL = MI->getDebugLoc();
22157
22158   assert(!isAsynchronousEHPersonality(
22159              classifyEHPersonality(MF->getFunction()->getPersonalityFn())) &&
22160          "SEH does not use catchret!");
22161
22162   // Only 32-bit EH needs to worry about manually restoring stack pointers.
22163   if (!Subtarget->is32Bit())
22164     return BB;
22165
22166   // C++ EH creates a new target block to hold the restore code, and wires up
22167   // the new block to the return destination with a normal JMP_4.
22168   MachineBasicBlock *RestoreMBB =
22169       MF->CreateMachineBasicBlock(BB->getBasicBlock());
22170   assert(BB->succ_size() == 1);
22171   MF->insert(std::next(BB->getIterator()), RestoreMBB);
22172   RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
22173   BB->addSuccessor(RestoreMBB);
22174   MI->getOperand(0).setMBB(RestoreMBB);
22175
22176   auto RestoreMBBI = RestoreMBB->begin();
22177   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
22178   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
22179   return BB;
22180 }
22181
22182 MachineBasicBlock *
22183 X86TargetLowering::EmitLoweredCatchPad(MachineInstr *MI,
22184                                        MachineBasicBlock *BB) const {
22185   MachineFunction *MF = BB->getParent();
22186   const Constant *PerFn = MF->getFunction()->getPersonalityFn();
22187   bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
22188   // Only 32-bit SEH requires special handling for catchpad.
22189   if (IsSEH && Subtarget->is32Bit()) {
22190     const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22191     DebugLoc DL = MI->getDebugLoc();
22192     BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
22193   }
22194   MI->eraseFromParent();
22195   return BB;
22196 }
22197
22198 MachineBasicBlock *
22199 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
22200                                       MachineBasicBlock *BB) const {
22201   // This is pretty easy.  We're taking the value that we received from
22202   // our load from the relocation, sticking it in either RDI (x86-64)
22203   // or EAX and doing an indirect call.  The return value will then
22204   // be in the normal return register.
22205   MachineFunction *F = BB->getParent();
22206   const X86InstrInfo *TII = Subtarget->getInstrInfo();
22207   DebugLoc DL = MI->getDebugLoc();
22208
22209   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
22210   assert(MI->getOperand(3).isGlobal() && "This should be a global");
22211
22212   // Get a register mask for the lowered call.
22213   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
22214   // proper register mask.
22215   const uint32_t *RegMask =
22216       Subtarget->is64Bit() ?
22217       Subtarget->getRegisterInfo()->getDarwinTLSCallPreservedMask() :
22218       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
22219   if (Subtarget->is64Bit()) {
22220     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22221                                       TII->get(X86::MOV64rm), X86::RDI)
22222     .addReg(X86::RIP)
22223     .addImm(0).addReg(0)
22224     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22225                       MI->getOperand(3).getTargetFlags())
22226     .addReg(0);
22227     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
22228     addDirectMem(MIB, X86::RDI);
22229     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
22230   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
22231     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22232                                       TII->get(X86::MOV32rm), X86::EAX)
22233     .addReg(0)
22234     .addImm(0).addReg(0)
22235     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22236                       MI->getOperand(3).getTargetFlags())
22237     .addReg(0);
22238     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22239     addDirectMem(MIB, X86::EAX);
22240     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22241   } else {
22242     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22243                                       TII->get(X86::MOV32rm), X86::EAX)
22244     .addReg(TII->getGlobalBaseReg(F))
22245     .addImm(0).addReg(0)
22246     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22247                       MI->getOperand(3).getTargetFlags())
22248     .addReg(0);
22249     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22250     addDirectMem(MIB, X86::EAX);
22251     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22252   }
22253
22254   MI->eraseFromParent(); // The pseudo instruction is gone now.
22255   return BB;
22256 }
22257
22258 MachineBasicBlock *
22259 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
22260                                     MachineBasicBlock *MBB) const {
22261   DebugLoc DL = MI->getDebugLoc();
22262   MachineFunction *MF = MBB->getParent();
22263   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22264   MachineRegisterInfo &MRI = MF->getRegInfo();
22265
22266   const BasicBlock *BB = MBB->getBasicBlock();
22267   MachineFunction::iterator I = ++MBB->getIterator();
22268
22269   // Memory Reference
22270   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22271   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22272
22273   unsigned DstReg;
22274   unsigned MemOpndSlot = 0;
22275
22276   unsigned CurOp = 0;
22277
22278   DstReg = MI->getOperand(CurOp++).getReg();
22279   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
22280   assert(RC->hasType(MVT::i32) && "Invalid destination!");
22281   unsigned mainDstReg = MRI.createVirtualRegister(RC);
22282   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
22283
22284   MemOpndSlot = CurOp;
22285
22286   MVT PVT = getPointerTy(MF->getDataLayout());
22287   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22288          "Invalid Pointer Size!");
22289
22290   // For v = setjmp(buf), we generate
22291   //
22292   // thisMBB:
22293   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
22294   //  SjLjSetup restoreMBB
22295   //
22296   // mainMBB:
22297   //  v_main = 0
22298   //
22299   // sinkMBB:
22300   //  v = phi(main, restore)
22301   //
22302   // restoreMBB:
22303   //  if base pointer being used, load it from frame
22304   //  v_restore = 1
22305
22306   MachineBasicBlock *thisMBB = MBB;
22307   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
22308   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
22309   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
22310   MF->insert(I, mainMBB);
22311   MF->insert(I, sinkMBB);
22312   MF->push_back(restoreMBB);
22313   restoreMBB->setHasAddressTaken();
22314
22315   MachineInstrBuilder MIB;
22316
22317   // Transfer the remainder of BB and its successor edges to sinkMBB.
22318   sinkMBB->splice(sinkMBB->begin(), MBB,
22319                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
22320   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
22321
22322   // thisMBB:
22323   unsigned PtrStoreOpc = 0;
22324   unsigned LabelReg = 0;
22325   const int64_t LabelOffset = 1 * PVT.getStoreSize();
22326   Reloc::Model RM = MF->getTarget().getRelocationModel();
22327   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
22328                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
22329
22330   // Prepare IP either in reg or imm.
22331   if (!UseImmLabel) {
22332     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
22333     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
22334     LabelReg = MRI.createVirtualRegister(PtrRC);
22335     if (Subtarget->is64Bit()) {
22336       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
22337               .addReg(X86::RIP)
22338               .addImm(0)
22339               .addReg(0)
22340               .addMBB(restoreMBB)
22341               .addReg(0);
22342     } else {
22343       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
22344       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
22345               .addReg(XII->getGlobalBaseReg(MF))
22346               .addImm(0)
22347               .addReg(0)
22348               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
22349               .addReg(0);
22350     }
22351   } else
22352     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
22353   // Store IP
22354   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
22355   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22356     if (i == X86::AddrDisp)
22357       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
22358     else
22359       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
22360   }
22361   if (!UseImmLabel)
22362     MIB.addReg(LabelReg);
22363   else
22364     MIB.addMBB(restoreMBB);
22365   MIB.setMemRefs(MMOBegin, MMOEnd);
22366   // Setup
22367   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
22368           .addMBB(restoreMBB);
22369
22370   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22371   MIB.addRegMask(RegInfo->getNoPreservedMask());
22372   thisMBB->addSuccessor(mainMBB);
22373   thisMBB->addSuccessor(restoreMBB);
22374
22375   // mainMBB:
22376   //  EAX = 0
22377   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
22378   mainMBB->addSuccessor(sinkMBB);
22379
22380   // sinkMBB:
22381   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
22382           TII->get(X86::PHI), DstReg)
22383     .addReg(mainDstReg).addMBB(mainMBB)
22384     .addReg(restoreDstReg).addMBB(restoreMBB);
22385
22386   // restoreMBB:
22387   if (RegInfo->hasBasePointer(*MF)) {
22388     const bool Uses64BitFramePtr =
22389         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
22390     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
22391     X86FI->setRestoreBasePointer(MF);
22392     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
22393     unsigned BasePtr = RegInfo->getBaseRegister();
22394     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
22395     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
22396                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
22397       .setMIFlag(MachineInstr::FrameSetup);
22398   }
22399   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
22400   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
22401   restoreMBB->addSuccessor(sinkMBB);
22402
22403   MI->eraseFromParent();
22404   return sinkMBB;
22405 }
22406
22407 MachineBasicBlock *
22408 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
22409                                      MachineBasicBlock *MBB) const {
22410   DebugLoc DL = MI->getDebugLoc();
22411   MachineFunction *MF = MBB->getParent();
22412   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22413   MachineRegisterInfo &MRI = MF->getRegInfo();
22414
22415   // Memory Reference
22416   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22417   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22418
22419   MVT PVT = getPointerTy(MF->getDataLayout());
22420   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22421          "Invalid Pointer Size!");
22422
22423   const TargetRegisterClass *RC =
22424     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
22425   unsigned Tmp = MRI.createVirtualRegister(RC);
22426   // Since FP is only updated here but NOT referenced, it's treated as GPR.
22427   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22428   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
22429   unsigned SP = RegInfo->getStackRegister();
22430
22431   MachineInstrBuilder MIB;
22432
22433   const int64_t LabelOffset = 1 * PVT.getStoreSize();
22434   const int64_t SPOffset = 2 * PVT.getStoreSize();
22435
22436   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
22437   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
22438
22439   // Reload FP
22440   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
22441   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
22442     MIB.addOperand(MI->getOperand(i));
22443   MIB.setMemRefs(MMOBegin, MMOEnd);
22444   // Reload IP
22445   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
22446   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22447     if (i == X86::AddrDisp)
22448       MIB.addDisp(MI->getOperand(i), LabelOffset);
22449     else
22450       MIB.addOperand(MI->getOperand(i));
22451   }
22452   MIB.setMemRefs(MMOBegin, MMOEnd);
22453   // Reload SP
22454   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
22455   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22456     if (i == X86::AddrDisp)
22457       MIB.addDisp(MI->getOperand(i), SPOffset);
22458     else
22459       MIB.addOperand(MI->getOperand(i));
22460   }
22461   MIB.setMemRefs(MMOBegin, MMOEnd);
22462   // Jump
22463   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
22464
22465   MI->eraseFromParent();
22466   return MBB;
22467 }
22468
22469 // Replace 213-type (isel default) FMA3 instructions with 231-type for
22470 // accumulator loops. Writing back to the accumulator allows the coalescer
22471 // to remove extra copies in the loop.
22472 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
22473 MachineBasicBlock *
22474 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
22475                                  MachineBasicBlock *MBB) const {
22476   MachineOperand &AddendOp = MI->getOperand(3);
22477
22478   // Bail out early if the addend isn't a register - we can't switch these.
22479   if (!AddendOp.isReg())
22480     return MBB;
22481
22482   MachineFunction &MF = *MBB->getParent();
22483   MachineRegisterInfo &MRI = MF.getRegInfo();
22484
22485   // Check whether the addend is defined by a PHI:
22486   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
22487   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
22488   if (!AddendDef.isPHI())
22489     return MBB;
22490
22491   // Look for the following pattern:
22492   // loop:
22493   //   %addend = phi [%entry, 0], [%loop, %result]
22494   //   ...
22495   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
22496
22497   // Replace with:
22498   //   loop:
22499   //   %addend = phi [%entry, 0], [%loop, %result]
22500   //   ...
22501   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
22502
22503   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
22504     assert(AddendDef.getOperand(i).isReg());
22505     MachineOperand PHISrcOp = AddendDef.getOperand(i);
22506     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
22507     if (&PHISrcInst == MI) {
22508       // Found a matching instruction.
22509       unsigned NewFMAOpc = 0;
22510       switch (MI->getOpcode()) {
22511         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
22512         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
22513         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
22514         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
22515         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
22516         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
22517         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
22518         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
22519         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
22520         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
22521         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
22522         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
22523         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
22524         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
22525         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
22526         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
22527         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
22528         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
22529         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
22530         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
22531
22532         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
22533         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
22534         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
22535         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
22536         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
22537         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
22538         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
22539         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
22540         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
22541         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
22542         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
22543         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
22544         default: llvm_unreachable("Unrecognized FMA variant.");
22545       }
22546
22547       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22548       MachineInstrBuilder MIB =
22549         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
22550         .addOperand(MI->getOperand(0))
22551         .addOperand(MI->getOperand(3))
22552         .addOperand(MI->getOperand(2))
22553         .addOperand(MI->getOperand(1));
22554       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
22555       MI->eraseFromParent();
22556     }
22557   }
22558
22559   return MBB;
22560 }
22561
22562 MachineBasicBlock *
22563 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
22564                                                MachineBasicBlock *BB) const {
22565   switch (MI->getOpcode()) {
22566   default: llvm_unreachable("Unexpected instr type to insert");
22567   case X86::TAILJMPd64:
22568   case X86::TAILJMPr64:
22569   case X86::TAILJMPm64:
22570   case X86::TAILJMPd64_REX:
22571   case X86::TAILJMPr64_REX:
22572   case X86::TAILJMPm64_REX:
22573     llvm_unreachable("TAILJMP64 would not be touched here.");
22574   case X86::TCRETURNdi64:
22575   case X86::TCRETURNri64:
22576   case X86::TCRETURNmi64:
22577     return BB;
22578   case X86::WIN_ALLOCA:
22579     return EmitLoweredWinAlloca(MI, BB);
22580   case X86::CATCHRET:
22581     return EmitLoweredCatchRet(MI, BB);
22582   case X86::CATCHPAD:
22583     return EmitLoweredCatchPad(MI, BB);
22584   case X86::SEG_ALLOCA_32:
22585   case X86::SEG_ALLOCA_64:
22586     return EmitLoweredSegAlloca(MI, BB);
22587   case X86::TLSCall_32:
22588   case X86::TLSCall_64:
22589     return EmitLoweredTLSCall(MI, BB);
22590   case X86::CMOV_FR32:
22591   case X86::CMOV_FR64:
22592   case X86::CMOV_FR128:
22593   case X86::CMOV_GR8:
22594   case X86::CMOV_GR16:
22595   case X86::CMOV_GR32:
22596   case X86::CMOV_RFP32:
22597   case X86::CMOV_RFP64:
22598   case X86::CMOV_RFP80:
22599   case X86::CMOV_V2F64:
22600   case X86::CMOV_V2I64:
22601   case X86::CMOV_V4F32:
22602   case X86::CMOV_V4F64:
22603   case X86::CMOV_V4I64:
22604   case X86::CMOV_V16F32:
22605   case X86::CMOV_V8F32:
22606   case X86::CMOV_V8F64:
22607   case X86::CMOV_V8I64:
22608   case X86::CMOV_V8I1:
22609   case X86::CMOV_V16I1:
22610   case X86::CMOV_V32I1:
22611   case X86::CMOV_V64I1:
22612     return EmitLoweredSelect(MI, BB);
22613
22614   case X86::RDFLAGS32:
22615   case X86::RDFLAGS64: {
22616     DebugLoc DL = MI->getDebugLoc();
22617     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22618     unsigned PushF =
22619         MI->getOpcode() == X86::RDFLAGS32 ? X86::PUSHF32 : X86::PUSHF64;
22620     unsigned Pop =
22621         MI->getOpcode() == X86::RDFLAGS32 ? X86::POP32r : X86::POP64r;
22622     BuildMI(*BB, MI, DL, TII->get(PushF));
22623     BuildMI(*BB, MI, DL, TII->get(Pop), MI->getOperand(0).getReg());
22624
22625     MI->eraseFromParent(); // The pseudo is gone now.
22626     return BB;
22627   }
22628
22629   case X86::WRFLAGS32:
22630   case X86::WRFLAGS64: {
22631     DebugLoc DL = MI->getDebugLoc();
22632     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22633     unsigned Push =
22634         MI->getOpcode() == X86::WRFLAGS32 ? X86::PUSH32r : X86::PUSH64r;
22635     unsigned PopF =
22636         MI->getOpcode() == X86::WRFLAGS32 ? X86::POPF32 : X86::POPF64;
22637     BuildMI(*BB, MI, DL, TII->get(Push)).addReg(MI->getOperand(0).getReg());
22638     BuildMI(*BB, MI, DL, TII->get(PopF));
22639
22640     MI->eraseFromParent(); // The pseudo is gone now.
22641     return BB;
22642   }
22643
22644   case X86::RELEASE_FADD32mr:
22645   case X86::RELEASE_FADD64mr:
22646     return EmitLoweredAtomicFP(MI, BB);
22647
22648   case X86::FP32_TO_INT16_IN_MEM:
22649   case X86::FP32_TO_INT32_IN_MEM:
22650   case X86::FP32_TO_INT64_IN_MEM:
22651   case X86::FP64_TO_INT16_IN_MEM:
22652   case X86::FP64_TO_INT32_IN_MEM:
22653   case X86::FP64_TO_INT64_IN_MEM:
22654   case X86::FP80_TO_INT16_IN_MEM:
22655   case X86::FP80_TO_INT32_IN_MEM:
22656   case X86::FP80_TO_INT64_IN_MEM: {
22657     MachineFunction *F = BB->getParent();
22658     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22659     DebugLoc DL = MI->getDebugLoc();
22660
22661     // Change the floating point control register to use "round towards zero"
22662     // mode when truncating to an integer value.
22663     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
22664     addFrameReference(BuildMI(*BB, MI, DL,
22665                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
22666
22667     // Load the old value of the high byte of the control word...
22668     unsigned OldCW =
22669       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
22670     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
22671                       CWFrameIdx);
22672
22673     // Set the high part to be round to zero...
22674     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
22675       .addImm(0xC7F);
22676
22677     // Reload the modified control word now...
22678     addFrameReference(BuildMI(*BB, MI, DL,
22679                               TII->get(X86::FLDCW16m)), CWFrameIdx);
22680
22681     // Restore the memory image of control word to original value
22682     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
22683       .addReg(OldCW);
22684
22685     // Get the X86 opcode to use.
22686     unsigned Opc;
22687     switch (MI->getOpcode()) {
22688     default: llvm_unreachable("illegal opcode!");
22689     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
22690     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
22691     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
22692     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
22693     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
22694     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
22695     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
22696     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
22697     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
22698     }
22699
22700     X86AddressMode AM;
22701     MachineOperand &Op = MI->getOperand(0);
22702     if (Op.isReg()) {
22703       AM.BaseType = X86AddressMode::RegBase;
22704       AM.Base.Reg = Op.getReg();
22705     } else {
22706       AM.BaseType = X86AddressMode::FrameIndexBase;
22707       AM.Base.FrameIndex = Op.getIndex();
22708     }
22709     Op = MI->getOperand(1);
22710     if (Op.isImm())
22711       AM.Scale = Op.getImm();
22712     Op = MI->getOperand(2);
22713     if (Op.isImm())
22714       AM.IndexReg = Op.getImm();
22715     Op = MI->getOperand(3);
22716     if (Op.isGlobal()) {
22717       AM.GV = Op.getGlobal();
22718     } else {
22719       AM.Disp = Op.getImm();
22720     }
22721     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
22722                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
22723
22724     // Reload the original control word now.
22725     addFrameReference(BuildMI(*BB, MI, DL,
22726                               TII->get(X86::FLDCW16m)), CWFrameIdx);
22727
22728     MI->eraseFromParent();   // The pseudo instruction is gone now.
22729     return BB;
22730   }
22731     // String/text processing lowering.
22732   case X86::PCMPISTRM128REG:
22733   case X86::VPCMPISTRM128REG:
22734   case X86::PCMPISTRM128MEM:
22735   case X86::VPCMPISTRM128MEM:
22736   case X86::PCMPESTRM128REG:
22737   case X86::VPCMPESTRM128REG:
22738   case X86::PCMPESTRM128MEM:
22739   case X86::VPCMPESTRM128MEM:
22740     assert(Subtarget->hasSSE42() &&
22741            "Target must have SSE4.2 or AVX features enabled");
22742     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
22743
22744   // String/text processing lowering.
22745   case X86::PCMPISTRIREG:
22746   case X86::VPCMPISTRIREG:
22747   case X86::PCMPISTRIMEM:
22748   case X86::VPCMPISTRIMEM:
22749   case X86::PCMPESTRIREG:
22750   case X86::VPCMPESTRIREG:
22751   case X86::PCMPESTRIMEM:
22752   case X86::VPCMPESTRIMEM:
22753     assert(Subtarget->hasSSE42() &&
22754            "Target must have SSE4.2 or AVX features enabled");
22755     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
22756
22757   // Thread synchronization.
22758   case X86::MONITOR:
22759     return EmitMonitor(MI, BB, Subtarget);
22760   // PKU feature
22761   case X86::WRPKRU:
22762     return EmitWRPKRU(MI, BB, Subtarget);
22763   case X86::RDPKRU:
22764     return EmitRDPKRU(MI, BB, Subtarget);
22765   // xbegin
22766   case X86::XBEGIN:
22767     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
22768
22769   case X86::VASTART_SAVE_XMM_REGS:
22770     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
22771
22772   case X86::VAARG_64:
22773     return EmitVAARG64WithCustomInserter(MI, BB);
22774
22775   case X86::EH_SjLj_SetJmp32:
22776   case X86::EH_SjLj_SetJmp64:
22777     return emitEHSjLjSetJmp(MI, BB);
22778
22779   case X86::EH_SjLj_LongJmp32:
22780   case X86::EH_SjLj_LongJmp64:
22781     return emitEHSjLjLongJmp(MI, BB);
22782
22783   case TargetOpcode::STATEPOINT:
22784     // As an implementation detail, STATEPOINT shares the STACKMAP format at
22785     // this point in the process.  We diverge later.
22786     return emitPatchPoint(MI, BB);
22787
22788   case TargetOpcode::STACKMAP:
22789   case TargetOpcode::PATCHPOINT:
22790     return emitPatchPoint(MI, BB);
22791
22792   case X86::VFMADDPDr213r:
22793   case X86::VFMADDPSr213r:
22794   case X86::VFMADDSDr213r:
22795   case X86::VFMADDSSr213r:
22796   case X86::VFMSUBPDr213r:
22797   case X86::VFMSUBPSr213r:
22798   case X86::VFMSUBSDr213r:
22799   case X86::VFMSUBSSr213r:
22800   case X86::VFNMADDPDr213r:
22801   case X86::VFNMADDPSr213r:
22802   case X86::VFNMADDSDr213r:
22803   case X86::VFNMADDSSr213r:
22804   case X86::VFNMSUBPDr213r:
22805   case X86::VFNMSUBPSr213r:
22806   case X86::VFNMSUBSDr213r:
22807   case X86::VFNMSUBSSr213r:
22808   case X86::VFMADDSUBPDr213r:
22809   case X86::VFMADDSUBPSr213r:
22810   case X86::VFMSUBADDPDr213r:
22811   case X86::VFMSUBADDPSr213r:
22812   case X86::VFMADDPDr213rY:
22813   case X86::VFMADDPSr213rY:
22814   case X86::VFMSUBPDr213rY:
22815   case X86::VFMSUBPSr213rY:
22816   case X86::VFNMADDPDr213rY:
22817   case X86::VFNMADDPSr213rY:
22818   case X86::VFNMSUBPDr213rY:
22819   case X86::VFNMSUBPSr213rY:
22820   case X86::VFMADDSUBPDr213rY:
22821   case X86::VFMADDSUBPSr213rY:
22822   case X86::VFMSUBADDPDr213rY:
22823   case X86::VFMSUBADDPSr213rY:
22824     return emitFMA3Instr(MI, BB);
22825   }
22826 }
22827
22828 //===----------------------------------------------------------------------===//
22829 //                           X86 Optimization Hooks
22830 //===----------------------------------------------------------------------===//
22831
22832 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
22833                                                       APInt &KnownZero,
22834                                                       APInt &KnownOne,
22835                                                       const SelectionDAG &DAG,
22836                                                       unsigned Depth) const {
22837   unsigned BitWidth = KnownZero.getBitWidth();
22838   unsigned Opc = Op.getOpcode();
22839   assert((Opc >= ISD::BUILTIN_OP_END ||
22840           Opc == ISD::INTRINSIC_WO_CHAIN ||
22841           Opc == ISD::INTRINSIC_W_CHAIN ||
22842           Opc == ISD::INTRINSIC_VOID) &&
22843          "Should use MaskedValueIsZero if you don't know whether Op"
22844          " is a target node!");
22845
22846   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
22847   switch (Opc) {
22848   default: break;
22849   case X86ISD::ADD:
22850   case X86ISD::SUB:
22851   case X86ISD::ADC:
22852   case X86ISD::SBB:
22853   case X86ISD::SMUL:
22854   case X86ISD::UMUL:
22855   case X86ISD::INC:
22856   case X86ISD::DEC:
22857   case X86ISD::OR:
22858   case X86ISD::XOR:
22859   case X86ISD::AND:
22860     // These nodes' second result is a boolean.
22861     if (Op.getResNo() == 0)
22862       break;
22863     // Fallthrough
22864   case X86ISD::SETCC:
22865     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
22866     break;
22867   case ISD::INTRINSIC_WO_CHAIN: {
22868     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22869     unsigned NumLoBits = 0;
22870     switch (IntId) {
22871     default: break;
22872     case Intrinsic::x86_sse_movmsk_ps:
22873     case Intrinsic::x86_avx_movmsk_ps_256:
22874     case Intrinsic::x86_sse2_movmsk_pd:
22875     case Intrinsic::x86_avx_movmsk_pd_256:
22876     case Intrinsic::x86_mmx_pmovmskb:
22877     case Intrinsic::x86_sse2_pmovmskb_128:
22878     case Intrinsic::x86_avx2_pmovmskb: {
22879       // High bits of movmskp{s|d}, pmovmskb are known zero.
22880       switch (IntId) {
22881         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
22882         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
22883         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
22884         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
22885         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
22886         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
22887         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
22888         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
22889       }
22890       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22891       break;
22892     }
22893     }
22894     break;
22895   }
22896   }
22897 }
22898
22899 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22900   SDValue Op,
22901   const SelectionDAG &,
22902   unsigned Depth) const {
22903   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22904   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22905     return Op.getValueType().getScalarSizeInBits();
22906
22907   // Fallback case.
22908   return 1;
22909 }
22910
22911 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22912 /// node is a GlobalAddress + offset.
22913 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22914                                        const GlobalValue* &GA,
22915                                        int64_t &Offset) const {
22916   if (N->getOpcode() == X86ISD::Wrapper) {
22917     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22918       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22919       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22920       return true;
22921     }
22922   }
22923   return TargetLowering::isGAPlusOffset(N, GA, Offset);
22924 }
22925
22926 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22927 /// FIXME: This could be expanded to support 512 bit vectors as well.
22928 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22929                                         TargetLowering::DAGCombinerInfo &DCI,
22930                                         const X86Subtarget* Subtarget) {
22931   SDLoc dl(N);
22932   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22933   SDValue V1 = SVOp->getOperand(0);
22934   SDValue V2 = SVOp->getOperand(1);
22935   MVT VT = SVOp->getSimpleValueType(0);
22936   unsigned NumElems = VT.getVectorNumElements();
22937
22938   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22939       V2.getOpcode() == ISD::CONCAT_VECTORS) {
22940     //
22941     //                   0,0,0,...
22942     //                      |
22943     //    V      UNDEF    BUILD_VECTOR    UNDEF
22944     //     \      /           \           /
22945     //  CONCAT_VECTOR         CONCAT_VECTOR
22946     //         \                  /
22947     //          \                /
22948     //          RESULT: V + zero extended
22949     //
22950     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22951         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22952         V1.getOperand(1).getOpcode() != ISD::UNDEF)
22953       return SDValue();
22954
22955     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
22956       return SDValue();
22957
22958     // To match the shuffle mask, the first half of the mask should
22959     // be exactly the first vector, and all the rest a splat with the
22960     // first element of the second one.
22961     for (unsigned i = 0; i != NumElems/2; ++i)
22962       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
22963           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
22964         return SDValue();
22965
22966     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
22967     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
22968       if (Ld->hasNUsesOfValue(1, 0)) {
22969         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
22970         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
22971         SDValue ResNode =
22972           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
22973                                   Ld->getMemoryVT(),
22974                                   Ld->getPointerInfo(),
22975                                   Ld->getAlignment(),
22976                                   false/*isVolatile*/, true/*ReadMem*/,
22977                                   false/*WriteMem*/);
22978
22979         // Make sure the newly-created LOAD is in the same position as Ld in
22980         // terms of dependency. We create a TokenFactor for Ld and ResNode,
22981         // and update uses of Ld's output chain to use the TokenFactor.
22982         if (Ld->hasAnyUseOfValue(1)) {
22983           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22984                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
22985           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
22986           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
22987                                  SDValue(ResNode.getNode(), 1));
22988         }
22989
22990         return DAG.getBitcast(VT, ResNode);
22991       }
22992     }
22993
22994     // Emit a zeroed vector and insert the desired subvector on its
22995     // first half.
22996     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
22997     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
22998     return DCI.CombineTo(N, InsV);
22999   }
23000
23001   return SDValue();
23002 }
23003
23004 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
23005 /// possible.
23006 ///
23007 /// This is the leaf of the recursive combinine below. When we have found some
23008 /// chain of single-use x86 shuffle instructions and accumulated the combined
23009 /// shuffle mask represented by them, this will try to pattern match that mask
23010 /// into either a single instruction if there is a special purpose instruction
23011 /// for this operation, or into a PSHUFB instruction which is a fully general
23012 /// instruction but should only be used to replace chains over a certain depth.
23013 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
23014                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
23015                                    TargetLowering::DAGCombinerInfo &DCI,
23016                                    const X86Subtarget *Subtarget) {
23017   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
23018
23019   // Find the operand that enters the chain. Note that multiple uses are OK
23020   // here, we're not going to remove the operand we find.
23021   SDValue Input = Op.getOperand(0);
23022   while (Input.getOpcode() == ISD::BITCAST)
23023     Input = Input.getOperand(0);
23024
23025   MVT VT = Input.getSimpleValueType();
23026   MVT RootVT = Root.getSimpleValueType();
23027   SDLoc DL(Root);
23028
23029   if (Mask.size() == 1) {
23030     int Index = Mask[0];
23031     assert((Index >= 0 || Index == SM_SentinelUndef ||
23032             Index == SM_SentinelZero) &&
23033            "Invalid shuffle index found!");
23034
23035     // We may end up with an accumulated mask of size 1 as a result of
23036     // widening of shuffle operands (see function canWidenShuffleElements).
23037     // If the only shuffle index is equal to SM_SentinelZero then propagate
23038     // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
23039     // mask, and therefore the entire chain of shuffles can be folded away.
23040     if (Index == SM_SentinelZero)
23041       DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
23042     else
23043       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
23044                     /*AddTo*/ true);
23045     return true;
23046   }
23047
23048   // Use the float domain if the operand type is a floating point type.
23049   bool FloatDomain = VT.isFloatingPoint();
23050
23051   // For floating point shuffles, we don't have free copies in the shuffle
23052   // instructions or the ability to load as part of the instruction, so
23053   // canonicalize their shuffles to UNPCK or MOV variants.
23054   //
23055   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
23056   // vectors because it can have a load folded into it that UNPCK cannot. This
23057   // doesn't preclude something switching to the shorter encoding post-RA.
23058   //
23059   // FIXME: Should teach these routines about AVX vector widths.
23060   if (FloatDomain && VT.is128BitVector()) {
23061     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
23062       bool Lo = Mask.equals({0, 0});
23063       unsigned Shuffle;
23064       MVT ShuffleVT;
23065       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
23066       // is no slower than UNPCKLPD but has the option to fold the input operand
23067       // into even an unaligned memory load.
23068       if (Lo && Subtarget->hasSSE3()) {
23069         Shuffle = X86ISD::MOVDDUP;
23070         ShuffleVT = MVT::v2f64;
23071       } else {
23072         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
23073         // than the UNPCK variants.
23074         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
23075         ShuffleVT = MVT::v4f32;
23076       }
23077       if (Depth == 1 && Root->getOpcode() == Shuffle)
23078         return false; // Nothing to do!
23079       Op = DAG.getBitcast(ShuffleVT, Input);
23080       DCI.AddToWorklist(Op.getNode());
23081       if (Shuffle == X86ISD::MOVDDUP)
23082         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23083       else
23084         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23085       DCI.AddToWorklist(Op.getNode());
23086       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23087                     /*AddTo*/ true);
23088       return true;
23089     }
23090     if (Subtarget->hasSSE3() &&
23091         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
23092       bool Lo = Mask.equals({0, 0, 2, 2});
23093       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
23094       MVT ShuffleVT = MVT::v4f32;
23095       if (Depth == 1 && Root->getOpcode() == Shuffle)
23096         return false; // Nothing to do!
23097       Op = DAG.getBitcast(ShuffleVT, Input);
23098       DCI.AddToWorklist(Op.getNode());
23099       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23100       DCI.AddToWorklist(Op.getNode());
23101       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23102                     /*AddTo*/ true);
23103       return true;
23104     }
23105     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
23106       bool Lo = Mask.equals({0, 0, 1, 1});
23107       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23108       MVT ShuffleVT = MVT::v4f32;
23109       if (Depth == 1 && Root->getOpcode() == Shuffle)
23110         return false; // Nothing to do!
23111       Op = DAG.getBitcast(ShuffleVT, Input);
23112       DCI.AddToWorklist(Op.getNode());
23113       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23114       DCI.AddToWorklist(Op.getNode());
23115       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23116                     /*AddTo*/ true);
23117       return true;
23118     }
23119   }
23120
23121   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
23122   // variants as none of these have single-instruction variants that are
23123   // superior to the UNPCK formulation.
23124   if (!FloatDomain && VT.is128BitVector() &&
23125       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23126        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
23127        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
23128        Mask.equals(
23129            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
23130     bool Lo = Mask[0] == 0;
23131     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23132     if (Depth == 1 && Root->getOpcode() == Shuffle)
23133       return false; // Nothing to do!
23134     MVT ShuffleVT;
23135     switch (Mask.size()) {
23136     case 8:
23137       ShuffleVT = MVT::v8i16;
23138       break;
23139     case 16:
23140       ShuffleVT = MVT::v16i8;
23141       break;
23142     default:
23143       llvm_unreachable("Impossible mask size!");
23144     };
23145     Op = DAG.getBitcast(ShuffleVT, Input);
23146     DCI.AddToWorklist(Op.getNode());
23147     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23148     DCI.AddToWorklist(Op.getNode());
23149     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23150                   /*AddTo*/ true);
23151     return true;
23152   }
23153
23154   // Don't try to re-form single instruction chains under any circumstances now
23155   // that we've done encoding canonicalization for them.
23156   if (Depth < 2)
23157     return false;
23158
23159   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
23160   // can replace them with a single PSHUFB instruction profitably. Intel's
23161   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
23162   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
23163   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
23164     SmallVector<SDValue, 16> PSHUFBMask;
23165     int NumBytes = VT.getSizeInBits() / 8;
23166     int Ratio = NumBytes / Mask.size();
23167     for (int i = 0; i < NumBytes; ++i) {
23168       if (Mask[i / Ratio] == SM_SentinelUndef) {
23169         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
23170         continue;
23171       }
23172       int M = Mask[i / Ratio] != SM_SentinelZero
23173                   ? Ratio * Mask[i / Ratio] + i % Ratio
23174                   : 255;
23175       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
23176     }
23177     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
23178     Op = DAG.getBitcast(ByteVT, Input);
23179     DCI.AddToWorklist(Op.getNode());
23180     SDValue PSHUFBMaskOp =
23181         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
23182     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
23183     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
23184     DCI.AddToWorklist(Op.getNode());
23185     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23186                   /*AddTo*/ true);
23187     return true;
23188   }
23189
23190   // Failed to find any combines.
23191   return false;
23192 }
23193
23194 /// \brief Fully generic combining of x86 shuffle instructions.
23195 ///
23196 /// This should be the last combine run over the x86 shuffle instructions. Once
23197 /// they have been fully optimized, this will recursively consider all chains
23198 /// of single-use shuffle instructions, build a generic model of the cumulative
23199 /// shuffle operation, and check for simpler instructions which implement this
23200 /// operation. We use this primarily for two purposes:
23201 ///
23202 /// 1) Collapse generic shuffles to specialized single instructions when
23203 ///    equivalent. In most cases, this is just an encoding size win, but
23204 ///    sometimes we will collapse multiple generic shuffles into a single
23205 ///    special-purpose shuffle.
23206 /// 2) Look for sequences of shuffle instructions with 3 or more total
23207 ///    instructions, and replace them with the slightly more expensive SSSE3
23208 ///    PSHUFB instruction if available. We do this as the last combining step
23209 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
23210 ///    a suitable short sequence of other instructions. The PHUFB will either
23211 ///    use a register or have to read from memory and so is slightly (but only
23212 ///    slightly) more expensive than the other shuffle instructions.
23213 ///
23214 /// Because this is inherently a quadratic operation (for each shuffle in
23215 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
23216 /// This should never be an issue in practice as the shuffle lowering doesn't
23217 /// produce sequences of more than 8 instructions.
23218 ///
23219 /// FIXME: We will currently miss some cases where the redundant shuffling
23220 /// would simplify under the threshold for PSHUFB formation because of
23221 /// combine-ordering. To fix this, we should do the redundant instruction
23222 /// combining in this recursive walk.
23223 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
23224                                           ArrayRef<int> RootMask,
23225                                           int Depth, bool HasPSHUFB,
23226                                           SelectionDAG &DAG,
23227                                           TargetLowering::DAGCombinerInfo &DCI,
23228                                           const X86Subtarget *Subtarget) {
23229   // Bound the depth of our recursive combine because this is ultimately
23230   // quadratic in nature.
23231   if (Depth > 8)
23232     return false;
23233
23234   // Directly rip through bitcasts to find the underlying operand.
23235   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
23236     Op = Op.getOperand(0);
23237
23238   MVT VT = Op.getSimpleValueType();
23239   if (!VT.isVector())
23240     return false; // Bail if we hit a non-vector.
23241
23242   assert(Root.getSimpleValueType().isVector() &&
23243          "Shuffles operate on vector types!");
23244   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
23245          "Can only combine shuffles of the same vector register size.");
23246
23247   if (!isTargetShuffle(Op.getOpcode()))
23248     return false;
23249   SmallVector<int, 16> OpMask;
23250   bool IsUnary;
23251   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, true, OpMask, IsUnary);
23252   // We only can combine unary shuffles which we can decode the mask for.
23253   if (!HaveMask || !IsUnary)
23254     return false;
23255
23256   assert(VT.getVectorNumElements() == OpMask.size() &&
23257          "Different mask size from vector size!");
23258   assert(((RootMask.size() > OpMask.size() &&
23259            RootMask.size() % OpMask.size() == 0) ||
23260           (OpMask.size() > RootMask.size() &&
23261            OpMask.size() % RootMask.size() == 0) ||
23262           OpMask.size() == RootMask.size()) &&
23263          "The smaller number of elements must divide the larger.");
23264   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
23265   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
23266   assert(((RootRatio == 1 && OpRatio == 1) ||
23267           (RootRatio == 1) != (OpRatio == 1)) &&
23268          "Must not have a ratio for both incoming and op masks!");
23269
23270   SmallVector<int, 16> Mask;
23271   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
23272
23273   // Merge this shuffle operation's mask into our accumulated mask. Note that
23274   // this shuffle's mask will be the first applied to the input, followed by the
23275   // root mask to get us all the way to the root value arrangement. The reason
23276   // for this order is that we are recursing up the operation chain.
23277   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
23278     int RootIdx = i / RootRatio;
23279     if (RootMask[RootIdx] < 0) {
23280       // This is a zero or undef lane, we're done.
23281       Mask.push_back(RootMask[RootIdx]);
23282       continue;
23283     }
23284
23285     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
23286     int OpIdx = RootMaskedIdx / OpRatio;
23287     if (OpMask[OpIdx] < 0) {
23288       // The incoming lanes are zero or undef, it doesn't matter which ones we
23289       // are using.
23290       Mask.push_back(OpMask[OpIdx]);
23291       continue;
23292     }
23293
23294     // Ok, we have non-zero lanes, map them through.
23295     Mask.push_back(OpMask[OpIdx] * OpRatio +
23296                    RootMaskedIdx % OpRatio);
23297   }
23298
23299   // See if we can recurse into the operand to combine more things.
23300   switch (Op.getOpcode()) {
23301   case X86ISD::PSHUFB:
23302     HasPSHUFB = true;
23303   case X86ISD::PSHUFD:
23304   case X86ISD::PSHUFHW:
23305   case X86ISD::PSHUFLW:
23306     if (Op.getOperand(0).hasOneUse() &&
23307         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23308                                       HasPSHUFB, DAG, DCI, Subtarget))
23309       return true;
23310     break;
23311
23312   case X86ISD::UNPCKL:
23313   case X86ISD::UNPCKH:
23314     assert(Op.getOperand(0) == Op.getOperand(1) &&
23315            "We only combine unary shuffles!");
23316     // We can't check for single use, we have to check that this shuffle is the
23317     // only user.
23318     if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
23319         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23320                                       HasPSHUFB, DAG, DCI, Subtarget))
23321       return true;
23322     break;
23323   }
23324
23325   // Minor canonicalization of the accumulated shuffle mask to make it easier
23326   // to match below. All this does is detect masks with squential pairs of
23327   // elements, and shrink them to the half-width mask. It does this in a loop
23328   // so it will reduce the size of the mask to the minimal width mask which
23329   // performs an equivalent shuffle.
23330   SmallVector<int, 16> WidenedMask;
23331   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
23332     Mask = std::move(WidenedMask);
23333     WidenedMask.clear();
23334   }
23335
23336   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
23337                                 Subtarget);
23338 }
23339
23340 /// \brief Get the PSHUF-style mask from PSHUF node.
23341 ///
23342 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
23343 /// PSHUF-style masks that can be reused with such instructions.
23344 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
23345   MVT VT = N.getSimpleValueType();
23346   SmallVector<int, 4> Mask;
23347   bool IsUnary;
23348   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, false, Mask, IsUnary);
23349   (void)HaveMask;
23350   assert(HaveMask);
23351
23352   // If we have more than 128-bits, only the low 128-bits of shuffle mask
23353   // matter. Check that the upper masks are repeats and remove them.
23354   if (VT.getSizeInBits() > 128) {
23355     int LaneElts = 128 / VT.getScalarSizeInBits();
23356 #ifndef NDEBUG
23357     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
23358       for (int j = 0; j < LaneElts; ++j)
23359         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
23360                "Mask doesn't repeat in high 128-bit lanes!");
23361 #endif
23362     Mask.resize(LaneElts);
23363   }
23364
23365   switch (N.getOpcode()) {
23366   case X86ISD::PSHUFD:
23367     return Mask;
23368   case X86ISD::PSHUFLW:
23369     Mask.resize(4);
23370     return Mask;
23371   case X86ISD::PSHUFHW:
23372     Mask.erase(Mask.begin(), Mask.begin() + 4);
23373     for (int &M : Mask)
23374       M -= 4;
23375     return Mask;
23376   default:
23377     llvm_unreachable("No valid shuffle instruction found!");
23378   }
23379 }
23380
23381 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
23382 ///
23383 /// We walk up the chain and look for a combinable shuffle, skipping over
23384 /// shuffles that we could hoist this shuffle's transformation past without
23385 /// altering anything.
23386 static SDValue
23387 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
23388                              SelectionDAG &DAG,
23389                              TargetLowering::DAGCombinerInfo &DCI) {
23390   assert(N.getOpcode() == X86ISD::PSHUFD &&
23391          "Called with something other than an x86 128-bit half shuffle!");
23392   SDLoc DL(N);
23393
23394   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
23395   // of the shuffles in the chain so that we can form a fresh chain to replace
23396   // this one.
23397   SmallVector<SDValue, 8> Chain;
23398   SDValue V = N.getOperand(0);
23399   for (; V.hasOneUse(); V = V.getOperand(0)) {
23400     switch (V.getOpcode()) {
23401     default:
23402       return SDValue(); // Nothing combined!
23403
23404     case ISD::BITCAST:
23405       // Skip bitcasts as we always know the type for the target specific
23406       // instructions.
23407       continue;
23408
23409     case X86ISD::PSHUFD:
23410       // Found another dword shuffle.
23411       break;
23412
23413     case X86ISD::PSHUFLW:
23414       // Check that the low words (being shuffled) are the identity in the
23415       // dword shuffle, and the high words are self-contained.
23416       if (Mask[0] != 0 || Mask[1] != 1 ||
23417           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
23418         return SDValue();
23419
23420       Chain.push_back(V);
23421       continue;
23422
23423     case X86ISD::PSHUFHW:
23424       // Check that the high words (being shuffled) are the identity in the
23425       // dword shuffle, and the low words are self-contained.
23426       if (Mask[2] != 2 || Mask[3] != 3 ||
23427           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
23428         return SDValue();
23429
23430       Chain.push_back(V);
23431       continue;
23432
23433     case X86ISD::UNPCKL:
23434     case X86ISD::UNPCKH:
23435       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
23436       // shuffle into a preceding word shuffle.
23437       if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
23438           V.getSimpleValueType().getVectorElementType() != MVT::i16)
23439         return SDValue();
23440
23441       // Search for a half-shuffle which we can combine with.
23442       unsigned CombineOp =
23443           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
23444       if (V.getOperand(0) != V.getOperand(1) ||
23445           !V->isOnlyUserOf(V.getOperand(0).getNode()))
23446         return SDValue();
23447       Chain.push_back(V);
23448       V = V.getOperand(0);
23449       do {
23450         switch (V.getOpcode()) {
23451         default:
23452           return SDValue(); // Nothing to combine.
23453
23454         case X86ISD::PSHUFLW:
23455         case X86ISD::PSHUFHW:
23456           if (V.getOpcode() == CombineOp)
23457             break;
23458
23459           Chain.push_back(V);
23460
23461           // Fallthrough!
23462         case ISD::BITCAST:
23463           V = V.getOperand(0);
23464           continue;
23465         }
23466         break;
23467       } while (V.hasOneUse());
23468       break;
23469     }
23470     // Break out of the loop if we break out of the switch.
23471     break;
23472   }
23473
23474   if (!V.hasOneUse())
23475     // We fell out of the loop without finding a viable combining instruction.
23476     return SDValue();
23477
23478   // Merge this node's mask and our incoming mask.
23479   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23480   for (int &M : Mask)
23481     M = VMask[M];
23482   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
23483                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23484
23485   // Rebuild the chain around this new shuffle.
23486   while (!Chain.empty()) {
23487     SDValue W = Chain.pop_back_val();
23488
23489     if (V.getValueType() != W.getOperand(0).getValueType())
23490       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
23491
23492     switch (W.getOpcode()) {
23493     default:
23494       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
23495
23496     case X86ISD::UNPCKL:
23497     case X86ISD::UNPCKH:
23498       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
23499       break;
23500
23501     case X86ISD::PSHUFD:
23502     case X86ISD::PSHUFLW:
23503     case X86ISD::PSHUFHW:
23504       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
23505       break;
23506     }
23507   }
23508   if (V.getValueType() != N.getValueType())
23509     V = DAG.getBitcast(N.getValueType(), V);
23510
23511   // Return the new chain to replace N.
23512   return V;
23513 }
23514
23515 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
23516 /// pshufhw.
23517 ///
23518 /// We walk up the chain, skipping shuffles of the other half and looking
23519 /// through shuffles which switch halves trying to find a shuffle of the same
23520 /// pair of dwords.
23521 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
23522                                         SelectionDAG &DAG,
23523                                         TargetLowering::DAGCombinerInfo &DCI) {
23524   assert(
23525       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
23526       "Called with something other than an x86 128-bit half shuffle!");
23527   SDLoc DL(N);
23528   unsigned CombineOpcode = N.getOpcode();
23529
23530   // Walk up a single-use chain looking for a combinable shuffle.
23531   SDValue V = N.getOperand(0);
23532   for (; V.hasOneUse(); V = V.getOperand(0)) {
23533     switch (V.getOpcode()) {
23534     default:
23535       return false; // Nothing combined!
23536
23537     case ISD::BITCAST:
23538       // Skip bitcasts as we always know the type for the target specific
23539       // instructions.
23540       continue;
23541
23542     case X86ISD::PSHUFLW:
23543     case X86ISD::PSHUFHW:
23544       if (V.getOpcode() == CombineOpcode)
23545         break;
23546
23547       // Other-half shuffles are no-ops.
23548       continue;
23549     }
23550     // Break out of the loop if we break out of the switch.
23551     break;
23552   }
23553
23554   if (!V.hasOneUse())
23555     // We fell out of the loop without finding a viable combining instruction.
23556     return false;
23557
23558   // Combine away the bottom node as its shuffle will be accumulated into
23559   // a preceding shuffle.
23560   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23561
23562   // Record the old value.
23563   SDValue Old = V;
23564
23565   // Merge this node's mask and our incoming mask (adjusted to account for all
23566   // the pshufd instructions encountered).
23567   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23568   for (int &M : Mask)
23569     M = VMask[M];
23570   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
23571                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23572
23573   // Check that the shuffles didn't cancel each other out. If not, we need to
23574   // combine to the new one.
23575   if (Old != V)
23576     // Replace the combinable shuffle with the combined one, updating all users
23577     // so that we re-evaluate the chain here.
23578     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
23579
23580   return true;
23581 }
23582
23583 /// \brief Try to combine x86 target specific shuffles.
23584 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
23585                                            TargetLowering::DAGCombinerInfo &DCI,
23586                                            const X86Subtarget *Subtarget) {
23587   SDLoc DL(N);
23588   MVT VT = N.getSimpleValueType();
23589   SmallVector<int, 4> Mask;
23590
23591   switch (N.getOpcode()) {
23592   case X86ISD::PSHUFD:
23593   case X86ISD::PSHUFLW:
23594   case X86ISD::PSHUFHW:
23595     Mask = getPSHUFShuffleMask(N);
23596     assert(Mask.size() == 4);
23597     break;
23598   case X86ISD::UNPCKL: {
23599     // Combine X86ISD::UNPCKL and ISD::VECTOR_SHUFFLE into X86ISD::UNPCKH, in
23600     // which X86ISD::UNPCKL has a ISD::UNDEF operand, and ISD::VECTOR_SHUFFLE
23601     // moves upper half elements into the lower half part. For example:
23602     //
23603     // t2: v16i8 = vector_shuffle<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> t1,
23604     //     undef:v16i8
23605     // t3: v16i8 = X86ISD::UNPCKL undef:v16i8, t2
23606     //
23607     // will be combined to:
23608     //
23609     // t3: v16i8 = X86ISD::UNPCKH undef:v16i8, t1
23610
23611     // This is only for 128-bit vectors. From SSE4.1 onward this combine may not
23612     // happen due to advanced instructions.
23613     if (!VT.is128BitVector())
23614       return SDValue();
23615
23616     auto Op0 = N.getOperand(0);
23617     auto Op1 = N.getOperand(1);
23618     if (Op0.getOpcode() == ISD::UNDEF &&
23619         Op1.getNode()->getOpcode() == ISD::VECTOR_SHUFFLE) {
23620       ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op1.getNode())->getMask();
23621
23622       unsigned NumElts = VT.getVectorNumElements();
23623       SmallVector<int, 8> ExpectedMask(NumElts, -1);
23624       std::iota(ExpectedMask.begin(), ExpectedMask.begin() + NumElts / 2,
23625                 NumElts / 2);
23626
23627       auto ShufOp = Op1.getOperand(0);
23628       if (isShuffleEquivalent(Op1, ShufOp, Mask, ExpectedMask))
23629         return DAG.getNode(X86ISD::UNPCKH, DL, VT, N.getOperand(0), ShufOp);
23630     }
23631     return SDValue();
23632   }
23633   case X86ISD::BLENDI: {
23634     SDValue V0 = N->getOperand(0);
23635     SDValue V1 = N->getOperand(1);
23636     assert(VT == V0.getSimpleValueType() && VT == V1.getSimpleValueType() &&
23637            "Unexpected input vector types");
23638
23639     // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23640     // operands and changing the mask to 1. This saves us a bunch of
23641     // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23642     // x86InstrInfo knows how to commute this back after instruction selection
23643     // if it would help register allocation.
23644
23645     // TODO: If optimizing for size or a processor that doesn't suffer from
23646     // partial register update stalls, this should be transformed into a MOVSD
23647     // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23648
23649     if (VT == MVT::v2f64)
23650       if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23651         if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23652           SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23653           return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23654         }
23655
23656     return SDValue();
23657   }
23658   default:
23659     return SDValue();
23660   }
23661
23662   // Nuke no-op shuffles that show up after combining.
23663   if (isNoopShuffleMask(Mask))
23664     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23665
23666   // Look for simplifications involving one or two shuffle instructions.
23667   SDValue V = N.getOperand(0);
23668   switch (N.getOpcode()) {
23669   default:
23670     break;
23671   case X86ISD::PSHUFLW:
23672   case X86ISD::PSHUFHW:
23673     assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
23674
23675     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
23676       return SDValue(); // We combined away this shuffle, so we're done.
23677
23678     // See if this reduces to a PSHUFD which is no more expensive and can
23679     // combine with more operations. Note that it has to at least flip the
23680     // dwords as otherwise it would have been removed as a no-op.
23681     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
23682       int DMask[] = {0, 1, 2, 3};
23683       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
23684       DMask[DOffset + 0] = DOffset + 1;
23685       DMask[DOffset + 1] = DOffset + 0;
23686       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
23687       V = DAG.getBitcast(DVT, V);
23688       DCI.AddToWorklist(V.getNode());
23689       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
23690                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
23691       DCI.AddToWorklist(V.getNode());
23692       return DAG.getBitcast(VT, V);
23693     }
23694
23695     // Look for shuffle patterns which can be implemented as a single unpack.
23696     // FIXME: This doesn't handle the location of the PSHUFD generically, and
23697     // only works when we have a PSHUFD followed by two half-shuffles.
23698     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
23699         (V.getOpcode() == X86ISD::PSHUFLW ||
23700          V.getOpcode() == X86ISD::PSHUFHW) &&
23701         V.getOpcode() != N.getOpcode() &&
23702         V.hasOneUse()) {
23703       SDValue D = V.getOperand(0);
23704       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
23705         D = D.getOperand(0);
23706       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
23707         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23708         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
23709         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23710         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23711         int WordMask[8];
23712         for (int i = 0; i < 4; ++i) {
23713           WordMask[i + NOffset] = Mask[i] + NOffset;
23714           WordMask[i + VOffset] = VMask[i] + VOffset;
23715         }
23716         // Map the word mask through the DWord mask.
23717         int MappedMask[8];
23718         for (int i = 0; i < 8; ++i)
23719           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
23720         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23721             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
23722           // We can replace all three shuffles with an unpack.
23723           V = DAG.getBitcast(VT, D.getOperand(0));
23724           DCI.AddToWorklist(V.getNode());
23725           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
23726                                                 : X86ISD::UNPCKH,
23727                              DL, VT, V, V);
23728         }
23729       }
23730     }
23731
23732     break;
23733
23734   case X86ISD::PSHUFD:
23735     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
23736       return NewN;
23737
23738     break;
23739   }
23740
23741   return SDValue();
23742 }
23743
23744 /// \brief Try to combine a shuffle into a target-specific add-sub node.
23745 ///
23746 /// We combine this directly on the abstract vector shuffle nodes so it is
23747 /// easier to generically match. We also insert dummy vector shuffle nodes for
23748 /// the operands which explicitly discard the lanes which are unused by this
23749 /// operation to try to flow through the rest of the combiner the fact that
23750 /// they're unused.
23751 static SDValue combineShuffleToAddSub(SDNode *N, const X86Subtarget *Subtarget,
23752                                       SelectionDAG &DAG) {
23753   SDLoc DL(N);
23754   EVT VT = N->getValueType(0);
23755   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
23756       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
23757     return SDValue();
23758
23759   // We only handle target-independent shuffles.
23760   // FIXME: It would be easy and harmless to use the target shuffle mask
23761   // extraction tool to support more.
23762   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
23763     return SDValue();
23764
23765   auto *SVN = cast<ShuffleVectorSDNode>(N);
23766   SmallVector<int, 8> Mask;
23767   for (int M : SVN->getMask())
23768     Mask.push_back(M);
23769
23770   SDValue V1 = N->getOperand(0);
23771   SDValue V2 = N->getOperand(1);
23772
23773   // We require the first shuffle operand to be the FSUB node, and the second to
23774   // be the FADD node.
23775   if (V1.getOpcode() == ISD::FADD && V2.getOpcode() == ISD::FSUB) {
23776     ShuffleVectorSDNode::commuteMask(Mask);
23777     std::swap(V1, V2);
23778   } else if (V1.getOpcode() != ISD::FSUB || V2.getOpcode() != ISD::FADD)
23779     return SDValue();
23780
23781   // If there are other uses of these operations we can't fold them.
23782   if (!V1->hasOneUse() || !V2->hasOneUse())
23783     return SDValue();
23784
23785   // Ensure that both operations have the same operands. Note that we can
23786   // commute the FADD operands.
23787   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
23788   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
23789       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
23790     return SDValue();
23791
23792   // We're looking for blends between FADD and FSUB nodes. We insist on these
23793   // nodes being lined up in a specific expected pattern.
23794   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
23795         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
23796         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
23797     return SDValue();
23798
23799   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
23800 }
23801
23802 /// PerformShuffleCombine - Performs several different shuffle combines.
23803 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
23804                                      TargetLowering::DAGCombinerInfo &DCI,
23805                                      const X86Subtarget *Subtarget) {
23806   SDLoc dl(N);
23807   SDValue N0 = N->getOperand(0);
23808   SDValue N1 = N->getOperand(1);
23809   EVT VT = N->getValueType(0);
23810
23811   // Don't create instructions with illegal types after legalize types has run.
23812   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23813   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
23814     return SDValue();
23815
23816   // If we have legalized the vector types, look for blends of FADD and FSUB
23817   // nodes that we can fuse into an ADDSUB node.
23818   if (TLI.isTypeLegal(VT))
23819     if (SDValue AddSub = combineShuffleToAddSub(N, Subtarget, DAG))
23820       return AddSub;
23821
23822   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
23823   if (TLI.isTypeLegal(VT) && Subtarget->hasFp256() && VT.is256BitVector() &&
23824       N->getOpcode() == ISD::VECTOR_SHUFFLE)
23825     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
23826
23827   // During Type Legalization, when promoting illegal vector types,
23828   // the backend might introduce new shuffle dag nodes and bitcasts.
23829   //
23830   // This code performs the following transformation:
23831   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
23832   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
23833   //
23834   // We do this only if both the bitcast and the BINOP dag nodes have
23835   // one use. Also, perform this transformation only if the new binary
23836   // operation is legal. This is to avoid introducing dag nodes that
23837   // potentially need to be further expanded (or custom lowered) into a
23838   // less optimal sequence of dag nodes.
23839   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
23840       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
23841       N0.getOpcode() == ISD::BITCAST) {
23842     SDValue BC0 = N0.getOperand(0);
23843     EVT SVT = BC0.getValueType();
23844     unsigned Opcode = BC0.getOpcode();
23845     unsigned NumElts = VT.getVectorNumElements();
23846
23847     if (BC0.hasOneUse() && SVT.isVector() &&
23848         SVT.getVectorNumElements() * 2 == NumElts &&
23849         TLI.isOperationLegal(Opcode, VT)) {
23850       bool CanFold = false;
23851       switch (Opcode) {
23852       default : break;
23853       case ISD::ADD :
23854       case ISD::FADD :
23855       case ISD::SUB :
23856       case ISD::FSUB :
23857       case ISD::MUL :
23858       case ISD::FMUL :
23859         CanFold = true;
23860       }
23861
23862       unsigned SVTNumElts = SVT.getVectorNumElements();
23863       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
23864       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
23865         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
23866       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
23867         CanFold = SVOp->getMaskElt(i) < 0;
23868
23869       if (CanFold) {
23870         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
23871         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
23872         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
23873         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
23874       }
23875     }
23876   }
23877
23878   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
23879   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
23880   // consecutive, non-overlapping, and in the right order.
23881   SmallVector<SDValue, 16> Elts;
23882   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23883     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23884
23885   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23886     return LD;
23887
23888   if (isTargetShuffle(N->getOpcode())) {
23889     SDValue Shuffle =
23890         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23891     if (Shuffle.getNode())
23892       return Shuffle;
23893
23894     // Try recursively combining arbitrary sequences of x86 shuffle
23895     // instructions into higher-order shuffles. We do this after combining
23896     // specific PSHUF instruction sequences into their minimal form so that we
23897     // can evaluate how many specialized shuffle instructions are involved in
23898     // a particular chain.
23899     SmallVector<int, 1> NonceMask; // Just a placeholder.
23900     NonceMask.push_back(0);
23901     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23902                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23903                                       DCI, Subtarget))
23904       return SDValue(); // This routine will use CombineTo to replace N.
23905   }
23906
23907   return SDValue();
23908 }
23909
23910 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23911 /// specific shuffle of a load can be folded into a single element load.
23912 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23913 /// shuffles have been custom lowered so we need to handle those here.
23914 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23915                                          TargetLowering::DAGCombinerInfo &DCI) {
23916   if (DCI.isBeforeLegalizeOps())
23917     return SDValue();
23918
23919   SDValue InVec = N->getOperand(0);
23920   SDValue EltNo = N->getOperand(1);
23921   EVT EltVT = N->getValueType(0);
23922
23923   if (!isa<ConstantSDNode>(EltNo))
23924     return SDValue();
23925
23926   EVT OriginalVT = InVec.getValueType();
23927
23928   if (InVec.getOpcode() == ISD::BITCAST) {
23929     // Don't duplicate a load with other uses.
23930     if (!InVec.hasOneUse())
23931       return SDValue();
23932     EVT BCVT = InVec.getOperand(0).getValueType();
23933     if (!BCVT.isVector() ||
23934         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23935       return SDValue();
23936     InVec = InVec.getOperand(0);
23937   }
23938
23939   EVT CurrentVT = InVec.getValueType();
23940
23941   if (!isTargetShuffle(InVec.getOpcode()))
23942     return SDValue();
23943
23944   // Don't duplicate a load with other uses.
23945   if (!InVec.hasOneUse())
23946     return SDValue();
23947
23948   SmallVector<int, 16> ShuffleMask;
23949   bool UnaryShuffle;
23950   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(), true,
23951                             ShuffleMask, UnaryShuffle))
23952     return SDValue();
23953
23954   // Select the input vector, guarding against out of range extract vector.
23955   unsigned NumElems = CurrentVT.getVectorNumElements();
23956   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
23957   int Idx = (Elt > (int)NumElems) ? SM_SentinelUndef : ShuffleMask[Elt];
23958
23959   if (Idx == SM_SentinelZero)
23960     return EltVT.isInteger() ? DAG.getConstant(0, SDLoc(N), EltVT)
23961                              : DAG.getConstantFP(+0.0, SDLoc(N), EltVT);
23962   if (Idx == SM_SentinelUndef)
23963     return DAG.getUNDEF(EltVT);
23964
23965   assert(0 <= Idx && Idx < (int)(2 * NumElems) && "Shuffle index out of range");
23966   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
23967                                          : InVec.getOperand(1);
23968
23969   // If inputs to shuffle are the same for both ops, then allow 2 uses
23970   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
23971                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
23972
23973   if (LdNode.getOpcode() == ISD::BITCAST) {
23974     // Don't duplicate a load with other uses.
23975     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
23976       return SDValue();
23977
23978     AllowedUses = 1; // only allow 1 load use if we have a bitcast
23979     LdNode = LdNode.getOperand(0);
23980   }
23981
23982   if (!ISD::isNormalLoad(LdNode.getNode()))
23983     return SDValue();
23984
23985   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
23986
23987   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
23988     return SDValue();
23989
23990   // If there's a bitcast before the shuffle, check if the load type and
23991   // alignment is valid.
23992   unsigned Align = LN0->getAlignment();
23993   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23994   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
23995       EltVT.getTypeForEVT(*DAG.getContext()));
23996
23997   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
23998     return SDValue();
23999
24000   // All checks match so transform back to vector_shuffle so that DAG combiner
24001   // can finish the job
24002   SDLoc dl(N);
24003
24004   // Create shuffle node taking into account the case that its a unary shuffle
24005   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
24006                                    : InVec.getOperand(1);
24007   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
24008                                  InVec.getOperand(0), Shuffle,
24009                                  &ShuffleMask[0]);
24010   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
24011   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
24012                      EltNo);
24013 }
24014
24015 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
24016                                      const X86Subtarget *Subtarget) {
24017   SDValue N0 = N->getOperand(0);
24018   EVT VT = N->getValueType(0);
24019
24020   // Detect bitcasts between i32 to x86mmx low word. Since MMX types are
24021   // special and don't usually play with other vector types, it's better to
24022   // handle them early to be sure we emit efficient code by avoiding
24023   // store-load conversions.
24024   if (VT == MVT::x86mmx && N0.getOpcode() == ISD::BUILD_VECTOR &&
24025       N0.getValueType() == MVT::v2i32 &&
24026       isNullConstant(N0.getOperand(1))) {
24027     SDValue N00 = N0->getOperand(0);
24028     if (N00.getValueType() == MVT::i32)
24029       return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(N00), VT, N00);
24030   }
24031
24032   // Convert a bitcasted integer logic operation that has one bitcasted
24033   // floating-point operand and one constant operand into a floating-point
24034   // logic operation. This may create a load of the constant, but that is
24035   // cheaper than materializing the constant in an integer register and
24036   // transferring it to an SSE register or transferring the SSE operand to
24037   // integer register and back.
24038   unsigned FPOpcode;
24039   switch (N0.getOpcode()) {
24040     case ISD::AND: FPOpcode = X86ISD::FAND; break;
24041     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
24042     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
24043     default: return SDValue();
24044   }
24045   if (((Subtarget->hasSSE1() && VT == MVT::f32) ||
24046        (Subtarget->hasSSE2() && VT == MVT::f64)) &&
24047       isa<ConstantSDNode>(N0.getOperand(1)) &&
24048       N0.getOperand(0).getOpcode() == ISD::BITCAST &&
24049       N0.getOperand(0).getOperand(0).getValueType() == VT) {
24050     SDValue N000 = N0.getOperand(0).getOperand(0);
24051     SDValue FPConst = DAG.getBitcast(VT, N0.getOperand(1));
24052     return DAG.getNode(FPOpcode, SDLoc(N0), VT, N000, FPConst);
24053   }
24054
24055   return SDValue();
24056 }
24057
24058 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
24059 /// generation and convert it from being a bunch of shuffles and extracts
24060 /// into a somewhat faster sequence. For i686, the best sequence is apparently
24061 /// storing the value and loading scalars back, while for x64 we should
24062 /// use 64-bit extracts and shifts.
24063 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
24064                                          TargetLowering::DAGCombinerInfo &DCI) {
24065   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
24066     return NewOp;
24067
24068   SDValue InputVector = N->getOperand(0);
24069   SDLoc dl(InputVector);
24070   // Detect mmx to i32 conversion through a v2i32 elt extract.
24071   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
24072       N->getValueType(0) == MVT::i32 &&
24073       InputVector.getValueType() == MVT::v2i32) {
24074
24075     // The bitcast source is a direct mmx result.
24076     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
24077     if (MMXSrc.getValueType() == MVT::x86mmx)
24078       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
24079                          N->getValueType(0),
24080                          InputVector.getNode()->getOperand(0));
24081
24082     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
24083     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
24084         MMXSrc.getValueType() == MVT::i64) {
24085       SDValue MMXSrcOp = MMXSrc.getOperand(0);
24086       if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
24087           MMXSrcOp.getValueType() == MVT::v1i64 &&
24088           MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
24089         return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
24090                            N->getValueType(0), MMXSrcOp.getOperand(0));
24091     }
24092   }
24093
24094   EVT VT = N->getValueType(0);
24095
24096   if (VT == MVT::i1 && isa<ConstantSDNode>(N->getOperand(1)) &&
24097       InputVector.getOpcode() == ISD::BITCAST &&
24098       isa<ConstantSDNode>(InputVector.getOperand(0))) {
24099     uint64_t ExtractedElt =
24100         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
24101     uint64_t InputValue =
24102         cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
24103     uint64_t Res = (InputValue >> ExtractedElt) & 1;
24104     return DAG.getConstant(Res, dl, MVT::i1);
24105   }
24106   // Only operate on vectors of 4 elements, where the alternative shuffling
24107   // gets to be more expensive.
24108   if (InputVector.getValueType() != MVT::v4i32)
24109     return SDValue();
24110
24111   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
24112   // single use which is a sign-extend or zero-extend, and all elements are
24113   // used.
24114   SmallVector<SDNode *, 4> Uses;
24115   unsigned ExtractedElements = 0;
24116   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
24117        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
24118     if (UI.getUse().getResNo() != InputVector.getResNo())
24119       return SDValue();
24120
24121     SDNode *Extract = *UI;
24122     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
24123       return SDValue();
24124
24125     if (Extract->getValueType(0) != MVT::i32)
24126       return SDValue();
24127     if (!Extract->hasOneUse())
24128       return SDValue();
24129     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
24130         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
24131       return SDValue();
24132     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
24133       return SDValue();
24134
24135     // Record which element was extracted.
24136     ExtractedElements |=
24137       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
24138
24139     Uses.push_back(Extract);
24140   }
24141
24142   // If not all the elements were used, this may not be worthwhile.
24143   if (ExtractedElements != 15)
24144     return SDValue();
24145
24146   // Ok, we've now decided to do the transformation.
24147   // If 64-bit shifts are legal, use the extract-shift sequence,
24148   // otherwise bounce the vector off the cache.
24149   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24150   SDValue Vals[4];
24151
24152   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
24153     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
24154     auto &DL = DAG.getDataLayout();
24155     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
24156     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24157       DAG.getConstant(0, dl, VecIdxTy));
24158     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24159       DAG.getConstant(1, dl, VecIdxTy));
24160
24161     SDValue ShAmt = DAG.getConstant(
24162         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
24163     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
24164     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24165       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
24166     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
24167     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24168       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
24169   } else {
24170     // Store the value to a temporary stack slot.
24171     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
24172     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
24173       MachinePointerInfo(), false, false, 0);
24174
24175     EVT ElementType = InputVector.getValueType().getVectorElementType();
24176     unsigned EltSize = ElementType.getSizeInBits() / 8;
24177
24178     // Replace each use (extract) with a load of the appropriate element.
24179     for (unsigned i = 0; i < 4; ++i) {
24180       uint64_t Offset = EltSize * i;
24181       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
24182       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
24183
24184       SDValue ScalarAddr =
24185           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
24186
24187       // Load the scalar.
24188       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
24189                             ScalarAddr, MachinePointerInfo(),
24190                             false, false, false, 0);
24191
24192     }
24193   }
24194
24195   // Replace the extracts
24196   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
24197     UE = Uses.end(); UI != UE; ++UI) {
24198     SDNode *Extract = *UI;
24199
24200     SDValue Idx = Extract->getOperand(1);
24201     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
24202     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
24203   }
24204
24205   // The replacement was made in place; don't return anything.
24206   return SDValue();
24207 }
24208
24209 static SDValue
24210 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
24211                                       const X86Subtarget *Subtarget) {
24212   SDLoc dl(N);
24213   SDValue Cond = N->getOperand(0);
24214   SDValue LHS = N->getOperand(1);
24215   SDValue RHS = N->getOperand(2);
24216
24217   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
24218     SDValue CondSrc = Cond->getOperand(0);
24219     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
24220       Cond = CondSrc->getOperand(0);
24221   }
24222
24223   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
24224     return SDValue();
24225
24226   // A vselect where all conditions and data are constants can be optimized into
24227   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
24228   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
24229       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
24230     return SDValue();
24231
24232   unsigned MaskValue = 0;
24233   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
24234     return SDValue();
24235
24236   MVT VT = N->getSimpleValueType(0);
24237   unsigned NumElems = VT.getVectorNumElements();
24238   SmallVector<int, 8> ShuffleMask(NumElems, -1);
24239   for (unsigned i = 0; i < NumElems; ++i) {
24240     // Be sure we emit undef where we can.
24241     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
24242       ShuffleMask[i] = -1;
24243     else
24244       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
24245   }
24246
24247   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24248   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
24249     return SDValue();
24250   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
24251 }
24252
24253 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
24254 /// nodes.
24255 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
24256                                     TargetLowering::DAGCombinerInfo &DCI,
24257                                     const X86Subtarget *Subtarget) {
24258   SDLoc DL(N);
24259   SDValue Cond = N->getOperand(0);
24260   // Get the LHS/RHS of the select.
24261   SDValue LHS = N->getOperand(1);
24262   SDValue RHS = N->getOperand(2);
24263   EVT VT = LHS.getValueType();
24264   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24265
24266   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
24267   // instructions match the semantics of the common C idiom x<y?x:y but not
24268   // x<=y?x:y, because of how they handle negative zero (which can be
24269   // ignored in unsafe-math mode).
24270   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
24271   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
24272       VT != MVT::f80 && VT != MVT::f128 &&
24273       (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
24274       (Subtarget->hasSSE2() ||
24275        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
24276     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24277
24278     unsigned Opcode = 0;
24279     // Check for x CC y ? x : y.
24280     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24281         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24282       switch (CC) {
24283       default: break;
24284       case ISD::SETULT:
24285         // Converting this to a min would handle NaNs incorrectly, and swapping
24286         // the operands would cause it to handle comparisons between positive
24287         // and negative zero incorrectly.
24288         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24289           if (!DAG.getTarget().Options.UnsafeFPMath &&
24290               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24291             break;
24292           std::swap(LHS, RHS);
24293         }
24294         Opcode = X86ISD::FMIN;
24295         break;
24296       case ISD::SETOLE:
24297         // Converting this to a min would handle comparisons between positive
24298         // and negative zero incorrectly.
24299         if (!DAG.getTarget().Options.UnsafeFPMath &&
24300             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24301           break;
24302         Opcode = X86ISD::FMIN;
24303         break;
24304       case ISD::SETULE:
24305         // Converting this to a min would handle both negative zeros and NaNs
24306         // incorrectly, but we can swap the operands to fix both.
24307         std::swap(LHS, RHS);
24308       case ISD::SETOLT:
24309       case ISD::SETLT:
24310       case ISD::SETLE:
24311         Opcode = X86ISD::FMIN;
24312         break;
24313
24314       case ISD::SETOGE:
24315         // Converting this to a max would handle comparisons between positive
24316         // and negative zero incorrectly.
24317         if (!DAG.getTarget().Options.UnsafeFPMath &&
24318             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24319           break;
24320         Opcode = X86ISD::FMAX;
24321         break;
24322       case ISD::SETUGT:
24323         // Converting this to a max would handle NaNs incorrectly, and swapping
24324         // the operands would cause it to handle comparisons between positive
24325         // and negative zero incorrectly.
24326         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24327           if (!DAG.getTarget().Options.UnsafeFPMath &&
24328               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24329             break;
24330           std::swap(LHS, RHS);
24331         }
24332         Opcode = X86ISD::FMAX;
24333         break;
24334       case ISD::SETUGE:
24335         // Converting this to a max would handle both negative zeros and NaNs
24336         // incorrectly, but we can swap the operands to fix both.
24337         std::swap(LHS, RHS);
24338       case ISD::SETOGT:
24339       case ISD::SETGT:
24340       case ISD::SETGE:
24341         Opcode = X86ISD::FMAX;
24342         break;
24343       }
24344     // Check for x CC y ? y : x -- a min/max with reversed arms.
24345     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
24346                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
24347       switch (CC) {
24348       default: break;
24349       case ISD::SETOGE:
24350         // Converting this to a min would handle comparisons between positive
24351         // and negative zero incorrectly, and swapping the operands would
24352         // cause it to handle NaNs incorrectly.
24353         if (!DAG.getTarget().Options.UnsafeFPMath &&
24354             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
24355           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24356             break;
24357           std::swap(LHS, RHS);
24358         }
24359         Opcode = X86ISD::FMIN;
24360         break;
24361       case ISD::SETUGT:
24362         // Converting this to a min would handle NaNs incorrectly.
24363         if (!DAG.getTarget().Options.UnsafeFPMath &&
24364             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
24365           break;
24366         Opcode = X86ISD::FMIN;
24367         break;
24368       case ISD::SETUGE:
24369         // Converting this to a min would handle both negative zeros and NaNs
24370         // incorrectly, but we can swap the operands to fix both.
24371         std::swap(LHS, RHS);
24372       case ISD::SETOGT:
24373       case ISD::SETGT:
24374       case ISD::SETGE:
24375         Opcode = X86ISD::FMIN;
24376         break;
24377
24378       case ISD::SETULT:
24379         // Converting this to a max would handle NaNs incorrectly.
24380         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24381           break;
24382         Opcode = X86ISD::FMAX;
24383         break;
24384       case ISD::SETOLE:
24385         // Converting this to a max would handle comparisons between positive
24386         // and negative zero incorrectly, and swapping the operands would
24387         // cause it to handle NaNs incorrectly.
24388         if (!DAG.getTarget().Options.UnsafeFPMath &&
24389             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
24390           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24391             break;
24392           std::swap(LHS, RHS);
24393         }
24394         Opcode = X86ISD::FMAX;
24395         break;
24396       case ISD::SETULE:
24397         // Converting this to a max would handle both negative zeros and NaNs
24398         // incorrectly, but we can swap the operands to fix both.
24399         std::swap(LHS, RHS);
24400       case ISD::SETOLT:
24401       case ISD::SETLT:
24402       case ISD::SETLE:
24403         Opcode = X86ISD::FMAX;
24404         break;
24405       }
24406     }
24407
24408     if (Opcode)
24409       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
24410   }
24411
24412   EVT CondVT = Cond.getValueType();
24413   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
24414       CondVT.getVectorElementType() == MVT::i1) {
24415     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
24416     // lowering on KNL. In this case we convert it to
24417     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
24418     // The same situation for all 128 and 256-bit vectors of i8 and i16.
24419     // Since SKX these selects have a proper lowering.
24420     EVT OpVT = LHS.getValueType();
24421     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
24422         (OpVT.getVectorElementType() == MVT::i8 ||
24423          OpVT.getVectorElementType() == MVT::i16) &&
24424         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
24425       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
24426       DCI.AddToWorklist(Cond.getNode());
24427       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
24428     }
24429   }
24430   // If this is a select between two integer constants, try to do some
24431   // optimizations.
24432   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
24433     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
24434       // Don't do this for crazy integer types.
24435       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
24436         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
24437         // so that TrueC (the true value) is larger than FalseC.
24438         bool NeedsCondInvert = false;
24439
24440         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
24441             // Efficiently invertible.
24442             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
24443              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
24444               isa<ConstantSDNode>(Cond.getOperand(1))))) {
24445           NeedsCondInvert = true;
24446           std::swap(TrueC, FalseC);
24447         }
24448
24449         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
24450         if (FalseC->getAPIntValue() == 0 &&
24451             TrueC->getAPIntValue().isPowerOf2()) {
24452           if (NeedsCondInvert) // Invert the condition if needed.
24453             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24454                                DAG.getConstant(1, DL, Cond.getValueType()));
24455
24456           // Zero extend the condition if needed.
24457           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
24458
24459           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24460           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
24461                              DAG.getConstant(ShAmt, DL, MVT::i8));
24462         }
24463
24464         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
24465         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24466           if (NeedsCondInvert) // Invert the condition if needed.
24467             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24468                                DAG.getConstant(1, DL, Cond.getValueType()));
24469
24470           // Zero extend the condition if needed.
24471           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24472                              FalseC->getValueType(0), Cond);
24473           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24474                              SDValue(FalseC, 0));
24475         }
24476
24477         // Optimize cases that will turn into an LEA instruction.  This requires
24478         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24479         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24480           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24481           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24482
24483           bool isFastMultiplier = false;
24484           if (Diff < 10) {
24485             switch ((unsigned char)Diff) {
24486               default: break;
24487               case 1:  // result = add base, cond
24488               case 2:  // result = lea base(    , cond*2)
24489               case 3:  // result = lea base(cond, cond*2)
24490               case 4:  // result = lea base(    , cond*4)
24491               case 5:  // result = lea base(cond, cond*4)
24492               case 8:  // result = lea base(    , cond*8)
24493               case 9:  // result = lea base(cond, cond*8)
24494                 isFastMultiplier = true;
24495                 break;
24496             }
24497           }
24498
24499           if (isFastMultiplier) {
24500             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24501             if (NeedsCondInvert) // Invert the condition if needed.
24502               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24503                                  DAG.getConstant(1, DL, Cond.getValueType()));
24504
24505             // Zero extend the condition if needed.
24506             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24507                                Cond);
24508             // Scale the condition by the difference.
24509             if (Diff != 1)
24510               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24511                                  DAG.getConstant(Diff, DL,
24512                                                  Cond.getValueType()));
24513
24514             // Add the base if non-zero.
24515             if (FalseC->getAPIntValue() != 0)
24516               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24517                                  SDValue(FalseC, 0));
24518             return Cond;
24519           }
24520         }
24521       }
24522   }
24523
24524   // Canonicalize max and min:
24525   // (x > y) ? x : y -> (x >= y) ? x : y
24526   // (x < y) ? x : y -> (x <= y) ? x : y
24527   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
24528   // the need for an extra compare
24529   // against zero. e.g.
24530   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
24531   // subl   %esi, %edi
24532   // testl  %edi, %edi
24533   // movl   $0, %eax
24534   // cmovgl %edi, %eax
24535   // =>
24536   // xorl   %eax, %eax
24537   // subl   %esi, $edi
24538   // cmovsl %eax, %edi
24539   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
24540       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24541       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24542     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24543     switch (CC) {
24544     default: break;
24545     case ISD::SETLT:
24546     case ISD::SETGT: {
24547       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
24548       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
24549                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
24550       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
24551     }
24552     }
24553   }
24554
24555   // Early exit check
24556   if (!TLI.isTypeLegal(VT))
24557     return SDValue();
24558
24559   // Match VSELECTs into subs with unsigned saturation.
24560   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
24561       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
24562       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
24563        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
24564     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24565
24566     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
24567     // left side invert the predicate to simplify logic below.
24568     SDValue Other;
24569     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
24570       Other = RHS;
24571       CC = ISD::getSetCCInverse(CC, true);
24572     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
24573       Other = LHS;
24574     }
24575
24576     if (Other.getNode() && Other->getNumOperands() == 2 &&
24577         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
24578       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
24579       SDValue CondRHS = Cond->getOperand(1);
24580
24581       // Look for a general sub with unsigned saturation first.
24582       // x >= y ? x-y : 0 --> subus x, y
24583       // x >  y ? x-y : 0 --> subus x, y
24584       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
24585           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
24586         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
24587
24588       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
24589         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
24590           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
24591             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
24592               // If the RHS is a constant we have to reverse the const
24593               // canonicalization.
24594               // x > C-1 ? x+-C : 0 --> subus x, C
24595               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
24596                   CondRHSConst->getAPIntValue() ==
24597                       (-OpRHSConst->getAPIntValue() - 1))
24598                 return DAG.getNode(
24599                     X86ISD::SUBUS, DL, VT, OpLHS,
24600                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
24601
24602           // Another special case: If C was a sign bit, the sub has been
24603           // canonicalized into a xor.
24604           // FIXME: Would it be better to use computeKnownBits to determine
24605           //        whether it's safe to decanonicalize the xor?
24606           // x s< 0 ? x^C : 0 --> subus x, C
24607           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
24608               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
24609               OpRHSConst->getAPIntValue().isSignBit())
24610             // Note that we have to rebuild the RHS constant here to ensure we
24611             // don't rely on particular values of undef lanes.
24612             return DAG.getNode(
24613                 X86ISD::SUBUS, DL, VT, OpLHS,
24614                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
24615         }
24616     }
24617   }
24618
24619   // Simplify vector selection if condition value type matches vselect
24620   // operand type
24621   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
24622     assert(Cond.getValueType().isVector() &&
24623            "vector select expects a vector selector!");
24624
24625     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
24626     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
24627
24628     // Try invert the condition if true value is not all 1s and false value
24629     // is not all 0s.
24630     if (!TValIsAllOnes && !FValIsAllZeros &&
24631         // Check if the selector will be produced by CMPP*/PCMP*
24632         Cond.getOpcode() == ISD::SETCC &&
24633         // Check if SETCC has already been promoted
24634         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
24635             CondVT) {
24636       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
24637       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
24638
24639       if (TValIsAllZeros || FValIsAllOnes) {
24640         SDValue CC = Cond.getOperand(2);
24641         ISD::CondCode NewCC =
24642           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
24643                                Cond.getOperand(0).getValueType().isInteger());
24644         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
24645         std::swap(LHS, RHS);
24646         TValIsAllOnes = FValIsAllOnes;
24647         FValIsAllZeros = TValIsAllZeros;
24648       }
24649     }
24650
24651     if (TValIsAllOnes || FValIsAllZeros) {
24652       SDValue Ret;
24653
24654       if (TValIsAllOnes && FValIsAllZeros)
24655         Ret = Cond;
24656       else if (TValIsAllOnes)
24657         Ret =
24658             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
24659       else if (FValIsAllZeros)
24660         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
24661                           DAG.getBitcast(CondVT, LHS));
24662
24663       return DAG.getBitcast(VT, Ret);
24664     }
24665   }
24666
24667   // We should generate an X86ISD::BLENDI from a vselect if its argument
24668   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
24669   // constants. This specific pattern gets generated when we split a
24670   // selector for a 512 bit vector in a machine without AVX512 (but with
24671   // 256-bit vectors), during legalization:
24672   //
24673   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
24674   //
24675   // Iff we find this pattern and the build_vectors are built from
24676   // constants, we translate the vselect into a shuffle_vector that we
24677   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
24678   if ((N->getOpcode() == ISD::VSELECT ||
24679        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
24680       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
24681     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
24682     if (Shuffle.getNode())
24683       return Shuffle;
24684   }
24685
24686   // If this is a *dynamic* select (non-constant condition) and we can match
24687   // this node with one of the variable blend instructions, restructure the
24688   // condition so that the blends can use the high bit of each element and use
24689   // SimplifyDemandedBits to simplify the condition operand.
24690   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
24691       !DCI.isBeforeLegalize() &&
24692       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
24693     unsigned BitWidth = Cond.getValueType().getScalarSizeInBits();
24694
24695     // Don't optimize vector selects that map to mask-registers.
24696     if (BitWidth == 1)
24697       return SDValue();
24698
24699     // We can only handle the cases where VSELECT is directly legal on the
24700     // subtarget. We custom lower VSELECT nodes with constant conditions and
24701     // this makes it hard to see whether a dynamic VSELECT will correctly
24702     // lower, so we both check the operation's status and explicitly handle the
24703     // cases where a *dynamic* blend will fail even though a constant-condition
24704     // blend could be custom lowered.
24705     // FIXME: We should find a better way to handle this class of problems.
24706     // Potentially, we should combine constant-condition vselect nodes
24707     // pre-legalization into shuffles and not mark as many types as custom
24708     // lowered.
24709     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
24710       return SDValue();
24711     // FIXME: We don't support i16-element blends currently. We could and
24712     // should support them by making *all* the bits in the condition be set
24713     // rather than just the high bit and using an i8-element blend.
24714     if (VT.getVectorElementType() == MVT::i16)
24715       return SDValue();
24716     // Dynamic blending was only available from SSE4.1 onward.
24717     if (VT.is128BitVector() && !Subtarget->hasSSE41())
24718       return SDValue();
24719     // Byte blends are only available in AVX2
24720     if (VT == MVT::v32i8 && !Subtarget->hasAVX2())
24721       return SDValue();
24722
24723     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
24724     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
24725
24726     APInt KnownZero, KnownOne;
24727     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
24728                                           DCI.isBeforeLegalizeOps());
24729     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
24730         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
24731                                  TLO)) {
24732       // If we changed the computation somewhere in the DAG, this change
24733       // will affect all users of Cond.
24734       // Make sure it is fine and update all the nodes so that we do not
24735       // use the generic VSELECT anymore. Otherwise, we may perform
24736       // wrong optimizations as we messed up with the actual expectation
24737       // for the vector boolean values.
24738       if (Cond != TLO.Old) {
24739         // Check all uses of that condition operand to check whether it will be
24740         // consumed by non-BLEND instructions, which may depend on all bits are
24741         // set properly.
24742         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24743              I != E; ++I)
24744           if (I->getOpcode() != ISD::VSELECT)
24745             // TODO: Add other opcodes eventually lowered into BLEND.
24746             return SDValue();
24747
24748         // Update all the users of the condition, before committing the change,
24749         // so that the VSELECT optimizations that expect the correct vector
24750         // boolean value will not be triggered.
24751         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24752              I != E; ++I)
24753           DAG.ReplaceAllUsesOfValueWith(
24754               SDValue(*I, 0),
24755               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
24756                           Cond, I->getOperand(1), I->getOperand(2)));
24757         DCI.CommitTargetLoweringOpt(TLO);
24758         return SDValue();
24759       }
24760       // At this point, only Cond is changed. Change the condition
24761       // just for N to keep the opportunity to optimize all other
24762       // users their own way.
24763       DAG.ReplaceAllUsesOfValueWith(
24764           SDValue(N, 0),
24765           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
24766                       TLO.New, N->getOperand(1), N->getOperand(2)));
24767       return SDValue();
24768     }
24769   }
24770
24771   return SDValue();
24772 }
24773
24774 // Check whether a boolean test is testing a boolean value generated by
24775 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
24776 // code.
24777 //
24778 // Simplify the following patterns:
24779 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
24780 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
24781 // to (Op EFLAGS Cond)
24782 //
24783 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
24784 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
24785 // to (Op EFLAGS !Cond)
24786 //
24787 // where Op could be BRCOND or CMOV.
24788 //
24789 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
24790   // Quit if not CMP and SUB with its value result used.
24791   if (Cmp.getOpcode() != X86ISD::CMP &&
24792       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
24793       return SDValue();
24794
24795   // Quit if not used as a boolean value.
24796   if (CC != X86::COND_E && CC != X86::COND_NE)
24797     return SDValue();
24798
24799   // Check CMP operands. One of them should be 0 or 1 and the other should be
24800   // an SetCC or extended from it.
24801   SDValue Op1 = Cmp.getOperand(0);
24802   SDValue Op2 = Cmp.getOperand(1);
24803
24804   SDValue SetCC;
24805   const ConstantSDNode* C = nullptr;
24806   bool needOppositeCond = (CC == X86::COND_E);
24807   bool checkAgainstTrue = false; // Is it a comparison against 1?
24808
24809   if ((C = dyn_cast<ConstantSDNode>(Op1)))
24810     SetCC = Op2;
24811   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
24812     SetCC = Op1;
24813   else // Quit if all operands are not constants.
24814     return SDValue();
24815
24816   if (C->getZExtValue() == 1) {
24817     needOppositeCond = !needOppositeCond;
24818     checkAgainstTrue = true;
24819   } else if (C->getZExtValue() != 0)
24820     // Quit if the constant is neither 0 or 1.
24821     return SDValue();
24822
24823   bool truncatedToBoolWithAnd = false;
24824   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
24825   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
24826          SetCC.getOpcode() == ISD::TRUNCATE ||
24827          SetCC.getOpcode() == ISD::AND) {
24828     if (SetCC.getOpcode() == ISD::AND) {
24829       int OpIdx = -1;
24830       if (isOneConstant(SetCC.getOperand(0)))
24831         OpIdx = 1;
24832       if (isOneConstant(SetCC.getOperand(1)))
24833         OpIdx = 0;
24834       if (OpIdx == -1)
24835         break;
24836       SetCC = SetCC.getOperand(OpIdx);
24837       truncatedToBoolWithAnd = true;
24838     } else
24839       SetCC = SetCC.getOperand(0);
24840   }
24841
24842   switch (SetCC.getOpcode()) {
24843   case X86ISD::SETCC_CARRY:
24844     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
24845     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
24846     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
24847     // truncated to i1 using 'and'.
24848     if (checkAgainstTrue && !truncatedToBoolWithAnd)
24849       break;
24850     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
24851            "Invalid use of SETCC_CARRY!");
24852     // FALL THROUGH
24853   case X86ISD::SETCC:
24854     // Set the condition code or opposite one if necessary.
24855     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
24856     if (needOppositeCond)
24857       CC = X86::GetOppositeBranchCondition(CC);
24858     return SetCC.getOperand(1);
24859   case X86ISD::CMOV: {
24860     // Check whether false/true value has canonical one, i.e. 0 or 1.
24861     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
24862     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
24863     // Quit if true value is not a constant.
24864     if (!TVal)
24865       return SDValue();
24866     // Quit if false value is not a constant.
24867     if (!FVal) {
24868       SDValue Op = SetCC.getOperand(0);
24869       // Skip 'zext' or 'trunc' node.
24870       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
24871           Op.getOpcode() == ISD::TRUNCATE)
24872         Op = Op.getOperand(0);
24873       // A special case for rdrand/rdseed, where 0 is set if false cond is
24874       // found.
24875       if ((Op.getOpcode() != X86ISD::RDRAND &&
24876            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
24877         return SDValue();
24878     }
24879     // Quit if false value is not the constant 0 or 1.
24880     bool FValIsFalse = true;
24881     if (FVal && FVal->getZExtValue() != 0) {
24882       if (FVal->getZExtValue() != 1)
24883         return SDValue();
24884       // If FVal is 1, opposite cond is needed.
24885       needOppositeCond = !needOppositeCond;
24886       FValIsFalse = false;
24887     }
24888     // Quit if TVal is not the constant opposite of FVal.
24889     if (FValIsFalse && TVal->getZExtValue() != 1)
24890       return SDValue();
24891     if (!FValIsFalse && TVal->getZExtValue() != 0)
24892       return SDValue();
24893     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
24894     if (needOppositeCond)
24895       CC = X86::GetOppositeBranchCondition(CC);
24896     return SetCC.getOperand(3);
24897   }
24898   }
24899
24900   return SDValue();
24901 }
24902
24903 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
24904 /// Match:
24905 ///   (X86or (X86setcc) (X86setcc))
24906 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
24907 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
24908                                            X86::CondCode &CC1, SDValue &Flags,
24909                                            bool &isAnd) {
24910   if (Cond->getOpcode() == X86ISD::CMP) {
24911     if (!isNullConstant(Cond->getOperand(1)))
24912       return false;
24913
24914     Cond = Cond->getOperand(0);
24915   }
24916
24917   isAnd = false;
24918
24919   SDValue SetCC0, SetCC1;
24920   switch (Cond->getOpcode()) {
24921   default: return false;
24922   case ISD::AND:
24923   case X86ISD::AND:
24924     isAnd = true;
24925     // fallthru
24926   case ISD::OR:
24927   case X86ISD::OR:
24928     SetCC0 = Cond->getOperand(0);
24929     SetCC1 = Cond->getOperand(1);
24930     break;
24931   };
24932
24933   // Make sure we have SETCC nodes, using the same flags value.
24934   if (SetCC0.getOpcode() != X86ISD::SETCC ||
24935       SetCC1.getOpcode() != X86ISD::SETCC ||
24936       SetCC0->getOperand(1) != SetCC1->getOperand(1))
24937     return false;
24938
24939   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
24940   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
24941   Flags = SetCC0->getOperand(1);
24942   return true;
24943 }
24944
24945 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24946 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
24947                                   TargetLowering::DAGCombinerInfo &DCI,
24948                                   const X86Subtarget *Subtarget) {
24949   SDLoc DL(N);
24950
24951   // If the flag operand isn't dead, don't touch this CMOV.
24952   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
24953     return SDValue();
24954
24955   SDValue FalseOp = N->getOperand(0);
24956   SDValue TrueOp = N->getOperand(1);
24957   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
24958   SDValue Cond = N->getOperand(3);
24959
24960   if (CC == X86::COND_E || CC == X86::COND_NE) {
24961     switch (Cond.getOpcode()) {
24962     default: break;
24963     case X86ISD::BSR:
24964     case X86ISD::BSF:
24965       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
24966       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
24967         return (CC == X86::COND_E) ? FalseOp : TrueOp;
24968     }
24969   }
24970
24971   SDValue Flags;
24972
24973   Flags = checkBoolTestSetCCCombine(Cond, CC);
24974   if (Flags.getNode() &&
24975       // Extra check as FCMOV only supports a subset of X86 cond.
24976       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
24977     SDValue Ops[] = { FalseOp, TrueOp,
24978                       DAG.getConstant(CC, DL, MVT::i8), Flags };
24979     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24980   }
24981
24982   // If this is a select between two integer constants, try to do some
24983   // optimizations.  Note that the operands are ordered the opposite of SELECT
24984   // operands.
24985   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
24986     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
24987       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
24988       // larger than FalseC (the false value).
24989       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
24990         CC = X86::GetOppositeBranchCondition(CC);
24991         std::swap(TrueC, FalseC);
24992         std::swap(TrueOp, FalseOp);
24993       }
24994
24995       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
24996       // This is efficient for any integer data type (including i8/i16) and
24997       // shift amount.
24998       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
24999         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
25000                            DAG.getConstant(CC, DL, MVT::i8), Cond);
25001
25002         // Zero extend the condition if needed.
25003         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
25004
25005         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
25006         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
25007                            DAG.getConstant(ShAmt, DL, MVT::i8));
25008         if (N->getNumValues() == 2)  // Dead flag value?
25009           return DCI.CombineTo(N, Cond, SDValue());
25010         return Cond;
25011       }
25012
25013       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
25014       // for any integer data type, including i8/i16.
25015       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
25016         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
25017                            DAG.getConstant(CC, DL, MVT::i8), Cond);
25018
25019         // Zero extend the condition if needed.
25020         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
25021                            FalseC->getValueType(0), Cond);
25022         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
25023                            SDValue(FalseC, 0));
25024
25025         if (N->getNumValues() == 2)  // Dead flag value?
25026           return DCI.CombineTo(N, Cond, SDValue());
25027         return Cond;
25028       }
25029
25030       // Optimize cases that will turn into an LEA instruction.  This requires
25031       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
25032       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
25033         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
25034         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
25035
25036         bool isFastMultiplier = false;
25037         if (Diff < 10) {
25038           switch ((unsigned char)Diff) {
25039           default: break;
25040           case 1:  // result = add base, cond
25041           case 2:  // result = lea base(    , cond*2)
25042           case 3:  // result = lea base(cond, cond*2)
25043           case 4:  // result = lea base(    , cond*4)
25044           case 5:  // result = lea base(cond, cond*4)
25045           case 8:  // result = lea base(    , cond*8)
25046           case 9:  // result = lea base(cond, cond*8)
25047             isFastMultiplier = true;
25048             break;
25049           }
25050         }
25051
25052         if (isFastMultiplier) {
25053           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
25054           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
25055                              DAG.getConstant(CC, DL, MVT::i8), Cond);
25056           // Zero extend the condition if needed.
25057           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
25058                              Cond);
25059           // Scale the condition by the difference.
25060           if (Diff != 1)
25061             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
25062                                DAG.getConstant(Diff, DL, Cond.getValueType()));
25063
25064           // Add the base if non-zero.
25065           if (FalseC->getAPIntValue() != 0)
25066             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
25067                                SDValue(FalseC, 0));
25068           if (N->getNumValues() == 2)  // Dead flag value?
25069             return DCI.CombineTo(N, Cond, SDValue());
25070           return Cond;
25071         }
25072       }
25073     }
25074   }
25075
25076   // Handle these cases:
25077   //   (select (x != c), e, c) -> select (x != c), e, x),
25078   //   (select (x == c), c, e) -> select (x == c), x, e)
25079   // where the c is an integer constant, and the "select" is the combination
25080   // of CMOV and CMP.
25081   //
25082   // The rationale for this change is that the conditional-move from a constant
25083   // needs two instructions, however, conditional-move from a register needs
25084   // only one instruction.
25085   //
25086   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
25087   //  some instruction-combining opportunities. This opt needs to be
25088   //  postponed as late as possible.
25089   //
25090   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
25091     // the DCI.xxxx conditions are provided to postpone the optimization as
25092     // late as possible.
25093
25094     ConstantSDNode *CmpAgainst = nullptr;
25095     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
25096         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
25097         !isa<ConstantSDNode>(Cond.getOperand(0))) {
25098
25099       if (CC == X86::COND_NE &&
25100           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
25101         CC = X86::GetOppositeBranchCondition(CC);
25102         std::swap(TrueOp, FalseOp);
25103       }
25104
25105       if (CC == X86::COND_E &&
25106           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
25107         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
25108                           DAG.getConstant(CC, DL, MVT::i8), Cond };
25109         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
25110       }
25111     }
25112   }
25113
25114   // Fold and/or of setcc's to double CMOV:
25115   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
25116   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
25117   //
25118   // This combine lets us generate:
25119   //   cmovcc1 (jcc1 if we don't have CMOV)
25120   //   cmovcc2 (same)
25121   // instead of:
25122   //   setcc1
25123   //   setcc2
25124   //   and/or
25125   //   cmovne (jne if we don't have CMOV)
25126   // When we can't use the CMOV instruction, it might increase branch
25127   // mispredicts.
25128   // When we can use CMOV, or when there is no mispredict, this improves
25129   // throughput and reduces register pressure.
25130   //
25131   if (CC == X86::COND_NE) {
25132     SDValue Flags;
25133     X86::CondCode CC0, CC1;
25134     bool isAndSetCC;
25135     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
25136       if (isAndSetCC) {
25137         std::swap(FalseOp, TrueOp);
25138         CC0 = X86::GetOppositeBranchCondition(CC0);
25139         CC1 = X86::GetOppositeBranchCondition(CC1);
25140       }
25141
25142       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
25143         Flags};
25144       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
25145       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
25146       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
25147       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
25148       return CMOV;
25149     }
25150   }
25151
25152   return SDValue();
25153 }
25154
25155 /// PerformMulCombine - Optimize a single multiply with constant into two
25156 /// in order to implement it with two cheaper instructions, e.g.
25157 /// LEA + SHL, LEA + LEA.
25158 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
25159                                  TargetLowering::DAGCombinerInfo &DCI) {
25160   // An imul is usually smaller than the alternative sequence.
25161   if (DAG.getMachineFunction().getFunction()->optForMinSize())
25162     return SDValue();
25163
25164   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
25165     return SDValue();
25166
25167   EVT VT = N->getValueType(0);
25168   if (VT != MVT::i64 && VT != MVT::i32)
25169     return SDValue();
25170
25171   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
25172   if (!C)
25173     return SDValue();
25174   uint64_t MulAmt = C->getZExtValue();
25175   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
25176     return SDValue();
25177
25178   uint64_t MulAmt1 = 0;
25179   uint64_t MulAmt2 = 0;
25180   if ((MulAmt % 9) == 0) {
25181     MulAmt1 = 9;
25182     MulAmt2 = MulAmt / 9;
25183   } else if ((MulAmt % 5) == 0) {
25184     MulAmt1 = 5;
25185     MulAmt2 = MulAmt / 5;
25186   } else if ((MulAmt % 3) == 0) {
25187     MulAmt1 = 3;
25188     MulAmt2 = MulAmt / 3;
25189   }
25190
25191   SDLoc DL(N);
25192   SDValue NewMul;
25193   if (MulAmt2 &&
25194       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
25195
25196     if (isPowerOf2_64(MulAmt2) &&
25197         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
25198       // If second multiplifer is pow2, issue it first. We want the multiply by
25199       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
25200       // is an add.
25201       std::swap(MulAmt1, MulAmt2);
25202
25203     if (isPowerOf2_64(MulAmt1))
25204       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25205                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
25206     else
25207       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
25208                            DAG.getConstant(MulAmt1, DL, VT));
25209
25210     if (isPowerOf2_64(MulAmt2))
25211       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
25212                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
25213     else
25214       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
25215                            DAG.getConstant(MulAmt2, DL, VT));
25216   }
25217
25218   if (!NewMul) {
25219     assert(MulAmt != 0 && MulAmt != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX)
25220            && "Both cases that could cause potential overflows should have "
25221               "already been handled.");
25222     if (isPowerOf2_64(MulAmt - 1))
25223       // (mul x, 2^N + 1) => (add (shl x, N), x)
25224       NewMul = DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
25225                                 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25226                                 DAG.getConstant(Log2_64(MulAmt - 1), DL,
25227                                 MVT::i8)));
25228
25229     else if (isPowerOf2_64(MulAmt + 1))
25230       // (mul x, 2^N - 1) => (sub (shl x, N), x)
25231       NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getNode(ISD::SHL, DL, VT,
25232                                 N->getOperand(0),
25233                                 DAG.getConstant(Log2_64(MulAmt + 1),
25234                                 DL, MVT::i8)), N->getOperand(0));
25235   }
25236
25237   if (NewMul)
25238     // Do not add new nodes to DAG combiner worklist.
25239     DCI.CombineTo(N, NewMul, false);
25240
25241   return SDValue();
25242 }
25243
25244 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
25245   SDValue N0 = N->getOperand(0);
25246   SDValue N1 = N->getOperand(1);
25247   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
25248   EVT VT = N0.getValueType();
25249
25250   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
25251   // since the result of setcc_c is all zero's or all ones.
25252   if (VT.isInteger() && !VT.isVector() &&
25253       N1C && N0.getOpcode() == ISD::AND &&
25254       N0.getOperand(1).getOpcode() == ISD::Constant) {
25255     SDValue N00 = N0.getOperand(0);
25256     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
25257     APInt ShAmt = N1C->getAPIntValue();
25258     Mask = Mask.shl(ShAmt);
25259     bool MaskOK = false;
25260     // We can handle cases concerning bit-widening nodes containing setcc_c if
25261     // we carefully interrogate the mask to make sure we are semantics
25262     // preserving.
25263     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
25264     // of the underlying setcc_c operation if the setcc_c was zero extended.
25265     // Consider the following example:
25266     //   zext(setcc_c)                 -> i32 0x0000FFFF
25267     //   c1                            -> i32 0x0000FFFF
25268     //   c2                            -> i32 0x00000001
25269     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
25270     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
25271     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25272       MaskOK = true;
25273     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
25274                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25275       MaskOK = true;
25276     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
25277                 N00.getOpcode() == ISD::ANY_EXTEND) &&
25278                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25279       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
25280     }
25281     if (MaskOK && Mask != 0) {
25282       SDLoc DL(N);
25283       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
25284     }
25285   }
25286
25287   // Hardware support for vector shifts is sparse which makes us scalarize the
25288   // vector operations in many cases. Also, on sandybridge ADD is faster than
25289   // shl.
25290   // (shl V, 1) -> add V,V
25291   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
25292     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
25293       assert(N0.getValueType().isVector() && "Invalid vector shift type");
25294       // We shift all of the values by one. In many cases we do not have
25295       // hardware support for this operation. This is better expressed as an ADD
25296       // of two values.
25297       if (N1SplatC->getAPIntValue() == 1)
25298         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
25299     }
25300
25301   return SDValue();
25302 }
25303
25304 static SDValue PerformSRACombine(SDNode *N, SelectionDAG &DAG) {
25305   SDValue N0 = N->getOperand(0);
25306   SDValue N1 = N->getOperand(1);
25307   EVT VT = N0.getValueType();
25308   unsigned Size = VT.getSizeInBits();
25309
25310   // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
25311   // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
25312   // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
25313   // depending on sign of (SarConst - [56,48,32,24,16])
25314
25315   // sexts in X86 are MOVs. The MOVs have the same code size
25316   // as above SHIFTs (only SHIFT on 1 has lower code size).
25317   // However the MOVs have 2 advantages to a SHIFT:
25318   // 1. MOVs can write to a register that differs from source
25319   // 2. MOVs accept memory operands
25320
25321   if (!VT.isInteger() || VT.isVector() || N1.getOpcode() != ISD::Constant ||
25322       N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
25323       N0.getOperand(1).getOpcode() != ISD::Constant)
25324     return SDValue();
25325
25326   SDValue N00 = N0.getOperand(0);
25327   SDValue N01 = N0.getOperand(1);
25328   APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
25329   APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
25330   EVT CVT = N1.getValueType();
25331
25332   if (SarConst.isNegative())
25333     return SDValue();
25334
25335   for (MVT SVT : MVT::integer_valuetypes()) {
25336     unsigned ShiftSize = SVT.getSizeInBits();
25337     // skipping types without corresponding sext/zext and
25338     // ShlConst that is not one of [56,48,32,24,16]
25339     if (ShiftSize < 8 || ShiftSize > 64 || ShlConst != Size - ShiftSize)
25340       continue;
25341     SDLoc DL(N);
25342     SDValue NN =
25343         DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
25344     SarConst = SarConst - (Size - ShiftSize);
25345     if (SarConst == 0)
25346       return NN;
25347     else if (SarConst.isNegative())
25348       return DAG.getNode(ISD::SHL, DL, VT, NN,
25349                          DAG.getConstant(-SarConst, DL, CVT));
25350     else
25351       return DAG.getNode(ISD::SRA, DL, VT, NN,
25352                          DAG.getConstant(SarConst, DL, CVT));
25353   }
25354   return SDValue();
25355 }
25356
25357 /// \brief Returns a vector of 0s if the node in input is a vector logical
25358 /// shift by a constant amount which is known to be bigger than or equal
25359 /// to the vector element size in bits.
25360 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
25361                                       const X86Subtarget *Subtarget) {
25362   EVT VT = N->getValueType(0);
25363
25364   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
25365       (!Subtarget->hasInt256() ||
25366        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
25367     return SDValue();
25368
25369   SDValue Amt = N->getOperand(1);
25370   SDLoc DL(N);
25371   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
25372     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
25373       APInt ShiftAmt = AmtSplat->getAPIntValue();
25374       unsigned MaxAmount =
25375         VT.getSimpleVT().getVectorElementType().getSizeInBits();
25376
25377       // SSE2/AVX2 logical shifts always return a vector of 0s
25378       // if the shift amount is bigger than or equal to
25379       // the element size. The constant shift amount will be
25380       // encoded as a 8-bit immediate.
25381       if (ShiftAmt.trunc(8).uge(MaxAmount))
25382         return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, DL);
25383     }
25384
25385   return SDValue();
25386 }
25387
25388 /// PerformShiftCombine - Combine shifts.
25389 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
25390                                    TargetLowering::DAGCombinerInfo &DCI,
25391                                    const X86Subtarget *Subtarget) {
25392   if (N->getOpcode() == ISD::SHL)
25393     if (SDValue V = PerformSHLCombine(N, DAG))
25394       return V;
25395
25396   if (N->getOpcode() == ISD::SRA)
25397     if (SDValue V = PerformSRACombine(N, DAG))
25398       return V;
25399
25400   // Try to fold this logical shift into a zero vector.
25401   if (N->getOpcode() != ISD::SRA)
25402     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
25403       return V;
25404
25405   return SDValue();
25406 }
25407
25408 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
25409 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
25410 // and friends.  Likewise for OR -> CMPNEQSS.
25411 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
25412                             TargetLowering::DAGCombinerInfo &DCI,
25413                             const X86Subtarget *Subtarget) {
25414   unsigned opcode;
25415
25416   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
25417   // we're requiring SSE2 for both.
25418   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
25419     SDValue N0 = N->getOperand(0);
25420     SDValue N1 = N->getOperand(1);
25421     SDValue CMP0 = N0->getOperand(1);
25422     SDValue CMP1 = N1->getOperand(1);
25423     SDLoc DL(N);
25424
25425     // The SETCCs should both refer to the same CMP.
25426     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
25427       return SDValue();
25428
25429     SDValue CMP00 = CMP0->getOperand(0);
25430     SDValue CMP01 = CMP0->getOperand(1);
25431     EVT     VT    = CMP00.getValueType();
25432
25433     if (VT == MVT::f32 || VT == MVT::f64) {
25434       bool ExpectingFlags = false;
25435       // Check for any users that want flags:
25436       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
25437            !ExpectingFlags && UI != UE; ++UI)
25438         switch (UI->getOpcode()) {
25439         default:
25440         case ISD::BR_CC:
25441         case ISD::BRCOND:
25442         case ISD::SELECT:
25443           ExpectingFlags = true;
25444           break;
25445         case ISD::CopyToReg:
25446         case ISD::SIGN_EXTEND:
25447         case ISD::ZERO_EXTEND:
25448         case ISD::ANY_EXTEND:
25449           break;
25450         }
25451
25452       if (!ExpectingFlags) {
25453         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
25454         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
25455
25456         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
25457           X86::CondCode tmp = cc0;
25458           cc0 = cc1;
25459           cc1 = tmp;
25460         }
25461
25462         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
25463             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
25464           // FIXME: need symbolic constants for these magic numbers.
25465           // See X86ATTInstPrinter.cpp:printSSECC().
25466           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
25467           if (Subtarget->hasAVX512()) {
25468             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
25469                                          CMP01,
25470                                          DAG.getConstant(x86cc, DL, MVT::i8));
25471             if (N->getValueType(0) != MVT::i1)
25472               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
25473                                  FSetCC);
25474             return FSetCC;
25475           }
25476           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
25477                                               CMP00.getValueType(), CMP00, CMP01,
25478                                               DAG.getConstant(x86cc, DL,
25479                                                               MVT::i8));
25480
25481           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
25482           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
25483
25484           if (is64BitFP && !Subtarget->is64Bit()) {
25485             // On a 32-bit target, we cannot bitcast the 64-bit float to a
25486             // 64-bit integer, since that's not a legal type. Since
25487             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
25488             // bits, but can do this little dance to extract the lowest 32 bits
25489             // and work with those going forward.
25490             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
25491                                            OnesOrZeroesF);
25492             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
25493             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
25494                                         Vector32, DAG.getIntPtrConstant(0, DL));
25495             IntVT = MVT::i32;
25496           }
25497
25498           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
25499           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
25500                                       DAG.getConstant(1, DL, IntVT));
25501           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
25502                                               ANDed);
25503           return OneBitOfTruth;
25504         }
25505       }
25506     }
25507   }
25508   return SDValue();
25509 }
25510
25511 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
25512 /// so it can be folded inside ANDNP.
25513 static bool CanFoldXORWithAllOnes(const SDNode *N) {
25514   EVT VT = N->getValueType(0);
25515
25516   // Match direct AllOnes for 128 and 256-bit vectors
25517   if (ISD::isBuildVectorAllOnes(N))
25518     return true;
25519
25520   // Look through a bit convert.
25521   if (N->getOpcode() == ISD::BITCAST)
25522     N = N->getOperand(0).getNode();
25523
25524   // Sometimes the operand may come from a insert_subvector building a 256-bit
25525   // allones vector
25526   if (VT.is256BitVector() &&
25527       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
25528     SDValue V1 = N->getOperand(0);
25529     SDValue V2 = N->getOperand(1);
25530
25531     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
25532         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
25533         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
25534         ISD::isBuildVectorAllOnes(V2.getNode()))
25535       return true;
25536   }
25537
25538   return false;
25539 }
25540
25541 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
25542 // register. In most cases we actually compare or select YMM-sized registers
25543 // and mixing the two types creates horrible code. This method optimizes
25544 // some of the transition sequences.
25545 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
25546                                  TargetLowering::DAGCombinerInfo &DCI,
25547                                  const X86Subtarget *Subtarget) {
25548   EVT VT = N->getValueType(0);
25549   if (!VT.is256BitVector())
25550     return SDValue();
25551
25552   assert((N->getOpcode() == ISD::ANY_EXTEND ||
25553           N->getOpcode() == ISD::ZERO_EXTEND ||
25554           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
25555
25556   SDValue Narrow = N->getOperand(0);
25557   EVT NarrowVT = Narrow->getValueType(0);
25558   if (!NarrowVT.is128BitVector())
25559     return SDValue();
25560
25561   if (Narrow->getOpcode() != ISD::XOR &&
25562       Narrow->getOpcode() != ISD::AND &&
25563       Narrow->getOpcode() != ISD::OR)
25564     return SDValue();
25565
25566   SDValue N0  = Narrow->getOperand(0);
25567   SDValue N1  = Narrow->getOperand(1);
25568   SDLoc DL(Narrow);
25569
25570   // The Left side has to be a trunc.
25571   if (N0.getOpcode() != ISD::TRUNCATE)
25572     return SDValue();
25573
25574   // The type of the truncated inputs.
25575   EVT WideVT = N0->getOperand(0)->getValueType(0);
25576   if (WideVT != VT)
25577     return SDValue();
25578
25579   // The right side has to be a 'trunc' or a constant vector.
25580   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
25581   ConstantSDNode *RHSConstSplat = nullptr;
25582   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
25583     RHSConstSplat = RHSBV->getConstantSplatNode();
25584   if (!RHSTrunc && !RHSConstSplat)
25585     return SDValue();
25586
25587   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25588
25589   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
25590     return SDValue();
25591
25592   // Set N0 and N1 to hold the inputs to the new wide operation.
25593   N0 = N0->getOperand(0);
25594   if (RHSConstSplat) {
25595     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getVectorElementType(),
25596                      SDValue(RHSConstSplat, 0));
25597     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
25598     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
25599   } else if (RHSTrunc) {
25600     N1 = N1->getOperand(0);
25601   }
25602
25603   // Generate the wide operation.
25604   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
25605   unsigned Opcode = N->getOpcode();
25606   switch (Opcode) {
25607   case ISD::ANY_EXTEND:
25608     return Op;
25609   case ISD::ZERO_EXTEND: {
25610     unsigned InBits = NarrowVT.getScalarSizeInBits();
25611     APInt Mask = APInt::getAllOnesValue(InBits);
25612     Mask = Mask.zext(VT.getScalarSizeInBits());
25613     return DAG.getNode(ISD::AND, DL, VT,
25614                        Op, DAG.getConstant(Mask, DL, VT));
25615   }
25616   case ISD::SIGN_EXTEND:
25617     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
25618                        Op, DAG.getValueType(NarrowVT));
25619   default:
25620     llvm_unreachable("Unexpected opcode");
25621   }
25622 }
25623
25624 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
25625                                  TargetLowering::DAGCombinerInfo &DCI,
25626                                  const X86Subtarget *Subtarget) {
25627   SDValue N0 = N->getOperand(0);
25628   SDValue N1 = N->getOperand(1);
25629   SDLoc DL(N);
25630
25631   // A vector zext_in_reg may be represented as a shuffle,
25632   // feeding into a bitcast (this represents anyext) feeding into
25633   // an and with a mask.
25634   // We'd like to try to combine that into a shuffle with zero
25635   // plus a bitcast, removing the and.
25636   if (N0.getOpcode() != ISD::BITCAST ||
25637       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
25638     return SDValue();
25639
25640   // The other side of the AND should be a splat of 2^C, where C
25641   // is the number of bits in the source type.
25642   if (N1.getOpcode() == ISD::BITCAST)
25643     N1 = N1.getOperand(0);
25644   if (N1.getOpcode() != ISD::BUILD_VECTOR)
25645     return SDValue();
25646   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
25647
25648   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
25649   EVT SrcType = Shuffle->getValueType(0);
25650
25651   // We expect a single-source shuffle
25652   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
25653     return SDValue();
25654
25655   unsigned SrcSize = SrcType.getScalarSizeInBits();
25656
25657   APInt SplatValue, SplatUndef;
25658   unsigned SplatBitSize;
25659   bool HasAnyUndefs;
25660   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
25661                                 SplatBitSize, HasAnyUndefs))
25662     return SDValue();
25663
25664   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
25665   // Make sure the splat matches the mask we expect
25666   if (SplatBitSize > ResSize ||
25667       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
25668     return SDValue();
25669
25670   // Make sure the input and output size make sense
25671   if (SrcSize >= ResSize || ResSize % SrcSize)
25672     return SDValue();
25673
25674   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
25675   // The number of u's between each two values depends on the ratio between
25676   // the source and dest type.
25677   unsigned ZextRatio = ResSize / SrcSize;
25678   bool IsZext = true;
25679   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
25680     if (i % ZextRatio) {
25681       if (Shuffle->getMaskElt(i) > 0) {
25682         // Expected undef
25683         IsZext = false;
25684         break;
25685       }
25686     } else {
25687       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
25688         // Expected element number
25689         IsZext = false;
25690         break;
25691       }
25692     }
25693   }
25694
25695   if (!IsZext)
25696     return SDValue();
25697
25698   // Ok, perform the transformation - replace the shuffle with
25699   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
25700   // (instead of undef) where the k elements come from the zero vector.
25701   SmallVector<int, 8> Mask;
25702   unsigned NumElems = SrcType.getVectorNumElements();
25703   for (unsigned i = 0; i < NumElems; ++i)
25704     if (i % ZextRatio)
25705       Mask.push_back(NumElems);
25706     else
25707       Mask.push_back(i / ZextRatio);
25708
25709   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
25710     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
25711   return DAG.getBitcast(N0.getValueType(), NewShuffle);
25712 }
25713
25714 /// If both input operands of a logic op are being cast from floating point
25715 /// types, try to convert this into a floating point logic node to avoid
25716 /// unnecessary moves from SSE to integer registers.
25717 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
25718                                         const X86Subtarget *Subtarget) {
25719   unsigned FPOpcode = ISD::DELETED_NODE;
25720   if (N->getOpcode() == ISD::AND)
25721     FPOpcode = X86ISD::FAND;
25722   else if (N->getOpcode() == ISD::OR)
25723     FPOpcode = X86ISD::FOR;
25724   else if (N->getOpcode() == ISD::XOR)
25725     FPOpcode = X86ISD::FXOR;
25726
25727   assert(FPOpcode != ISD::DELETED_NODE &&
25728          "Unexpected input node for FP logic conversion");
25729
25730   EVT VT = N->getValueType(0);
25731   SDValue N0 = N->getOperand(0);
25732   SDValue N1 = N->getOperand(1);
25733   SDLoc DL(N);
25734   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
25735       ((Subtarget->hasSSE1() && VT == MVT::i32) ||
25736        (Subtarget->hasSSE2() && VT == MVT::i64))) {
25737     SDValue N00 = N0.getOperand(0);
25738     SDValue N10 = N1.getOperand(0);
25739     EVT N00Type = N00.getValueType();
25740     EVT N10Type = N10.getValueType();
25741     if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
25742       SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
25743       return DAG.getBitcast(VT, FPLogic);
25744     }
25745   }
25746   return SDValue();
25747 }
25748
25749 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
25750                                  TargetLowering::DAGCombinerInfo &DCI,
25751                                  const X86Subtarget *Subtarget) {
25752   if (DCI.isBeforeLegalizeOps())
25753     return SDValue();
25754
25755   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
25756     return Zext;
25757
25758   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25759     return R;
25760
25761   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25762     return FPLogic;
25763
25764   EVT VT = N->getValueType(0);
25765   SDValue N0 = N->getOperand(0);
25766   SDValue N1 = N->getOperand(1);
25767   SDLoc DL(N);
25768
25769   // Create BEXTR instructions
25770   // BEXTR is ((X >> imm) & (2**size-1))
25771   if (VT == MVT::i32 || VT == MVT::i64) {
25772     // Check for BEXTR.
25773     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
25774         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
25775       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
25776       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25777       if (MaskNode && ShiftNode) {
25778         uint64_t Mask = MaskNode->getZExtValue();
25779         uint64_t Shift = ShiftNode->getZExtValue();
25780         if (isMask_64(Mask)) {
25781           uint64_t MaskSize = countPopulation(Mask);
25782           if (Shift + MaskSize <= VT.getSizeInBits())
25783             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
25784                                DAG.getConstant(Shift | (MaskSize << 8), DL,
25785                                                VT));
25786         }
25787       }
25788     } // BEXTR
25789
25790     return SDValue();
25791   }
25792
25793   // Want to form ANDNP nodes:
25794   // 1) In the hopes of then easily combining them with OR and AND nodes
25795   //    to form PBLEND/PSIGN.
25796   // 2) To match ANDN packed intrinsics
25797   if (VT != MVT::v2i64 && VT != MVT::v4i64)
25798     return SDValue();
25799
25800   // Check LHS for vnot
25801   if (N0.getOpcode() == ISD::XOR &&
25802       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
25803       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
25804     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
25805
25806   // Check RHS for vnot
25807   if (N1.getOpcode() == ISD::XOR &&
25808       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
25809       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
25810     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
25811
25812   return SDValue();
25813 }
25814
25815 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
25816                                 TargetLowering::DAGCombinerInfo &DCI,
25817                                 const X86Subtarget *Subtarget) {
25818   if (DCI.isBeforeLegalizeOps())
25819     return SDValue();
25820
25821   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25822     return R;
25823
25824   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25825     return FPLogic;
25826
25827   SDValue N0 = N->getOperand(0);
25828   SDValue N1 = N->getOperand(1);
25829   EVT VT = N->getValueType(0);
25830
25831   // look for psign/blend
25832   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
25833     if (!Subtarget->hasSSSE3() ||
25834         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
25835       return SDValue();
25836
25837     // Canonicalize pandn to RHS
25838     if (N0.getOpcode() == X86ISD::ANDNP)
25839       std::swap(N0, N1);
25840     // or (and (m, y), (pandn m, x))
25841     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
25842       SDValue Mask = N1.getOperand(0);
25843       SDValue X    = N1.getOperand(1);
25844       SDValue Y;
25845       if (N0.getOperand(0) == Mask)
25846         Y = N0.getOperand(1);
25847       if (N0.getOperand(1) == Mask)
25848         Y = N0.getOperand(0);
25849
25850       // Check to see if the mask appeared in both the AND and ANDNP and
25851       if (!Y.getNode())
25852         return SDValue();
25853
25854       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
25855       // Look through mask bitcast.
25856       if (Mask.getOpcode() == ISD::BITCAST)
25857         Mask = Mask.getOperand(0);
25858       if (X.getOpcode() == ISD::BITCAST)
25859         X = X.getOperand(0);
25860       if (Y.getOpcode() == ISD::BITCAST)
25861         Y = Y.getOperand(0);
25862
25863       EVT MaskVT = Mask.getValueType();
25864
25865       // Validate that the Mask operand is a vector sra node.
25866       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
25867       // there is no psrai.b
25868       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
25869       unsigned SraAmt = ~0;
25870       if (Mask.getOpcode() == ISD::SRA) {
25871         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
25872           if (auto *AmtConst = AmtBV->getConstantSplatNode())
25873             SraAmt = AmtConst->getZExtValue();
25874       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
25875         SDValue SraC = Mask.getOperand(1);
25876         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
25877       }
25878       if ((SraAmt + 1) != EltBits)
25879         return SDValue();
25880
25881       SDLoc DL(N);
25882
25883       // Now we know we at least have a plendvb with the mask val.  See if
25884       // we can form a psignb/w/d.
25885       // psign = x.type == y.type == mask.type && y = sub(0, x);
25886       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
25887           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
25888           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
25889         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
25890                "Unsupported VT for PSIGN");
25891         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
25892         return DAG.getBitcast(VT, Mask);
25893       }
25894       // PBLENDVB only available on SSE 4.1
25895       if (!Subtarget->hasSSE41())
25896         return SDValue();
25897
25898       MVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
25899
25900       X = DAG.getBitcast(BlendVT, X);
25901       Y = DAG.getBitcast(BlendVT, Y);
25902       Mask = DAG.getBitcast(BlendVT, Mask);
25903       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
25904       return DAG.getBitcast(VT, Mask);
25905     }
25906   }
25907
25908   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
25909     return SDValue();
25910
25911   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
25912   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
25913
25914   // SHLD/SHRD instructions have lower register pressure, but on some
25915   // platforms they have higher latency than the equivalent
25916   // series of shifts/or that would otherwise be generated.
25917   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
25918   // have higher latencies and we are not optimizing for size.
25919   if (!OptForSize && Subtarget->isSHLDSlow())
25920     return SDValue();
25921
25922   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
25923     std::swap(N0, N1);
25924   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
25925     return SDValue();
25926   if (!N0.hasOneUse() || !N1.hasOneUse())
25927     return SDValue();
25928
25929   SDValue ShAmt0 = N0.getOperand(1);
25930   if (ShAmt0.getValueType() != MVT::i8)
25931     return SDValue();
25932   SDValue ShAmt1 = N1.getOperand(1);
25933   if (ShAmt1.getValueType() != MVT::i8)
25934     return SDValue();
25935   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
25936     ShAmt0 = ShAmt0.getOperand(0);
25937   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
25938     ShAmt1 = ShAmt1.getOperand(0);
25939
25940   SDLoc DL(N);
25941   unsigned Opc = X86ISD::SHLD;
25942   SDValue Op0 = N0.getOperand(0);
25943   SDValue Op1 = N1.getOperand(0);
25944   if (ShAmt0.getOpcode() == ISD::SUB) {
25945     Opc = X86ISD::SHRD;
25946     std::swap(Op0, Op1);
25947     std::swap(ShAmt0, ShAmt1);
25948   }
25949
25950   unsigned Bits = VT.getSizeInBits();
25951   if (ShAmt1.getOpcode() == ISD::SUB) {
25952     SDValue Sum = ShAmt1.getOperand(0);
25953     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
25954       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
25955       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
25956         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
25957       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
25958         return DAG.getNode(Opc, DL, VT,
25959                            Op0, Op1,
25960                            DAG.getNode(ISD::TRUNCATE, DL,
25961                                        MVT::i8, ShAmt0));
25962     }
25963   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
25964     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
25965     if (ShAmt0C &&
25966         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
25967       return DAG.getNode(Opc, DL, VT,
25968                          N0.getOperand(0), N1.getOperand(0),
25969                          DAG.getNode(ISD::TRUNCATE, DL,
25970                                        MVT::i8, ShAmt0));
25971   }
25972
25973   return SDValue();
25974 }
25975
25976 // Generate NEG and CMOV for integer abs.
25977 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
25978   EVT VT = N->getValueType(0);
25979
25980   // Since X86 does not have CMOV for 8-bit integer, we don't convert
25981   // 8-bit integer abs to NEG and CMOV.
25982   if (VT.isInteger() && VT.getSizeInBits() == 8)
25983     return SDValue();
25984
25985   SDValue N0 = N->getOperand(0);
25986   SDValue N1 = N->getOperand(1);
25987   SDLoc DL(N);
25988
25989   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
25990   // and change it to SUB and CMOV.
25991   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
25992       N0.getOpcode() == ISD::ADD &&
25993       N0.getOperand(1) == N1 &&
25994       N1.getOpcode() == ISD::SRA &&
25995       N1.getOperand(0) == N0.getOperand(0))
25996     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
25997       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
25998         // Generate SUB & CMOV.
25999         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
26000                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
26001
26002         SDValue Ops[] = { N0.getOperand(0), Neg,
26003                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
26004                           SDValue(Neg.getNode(), 1) };
26005         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
26006       }
26007   return SDValue();
26008 }
26009
26010 // Try to turn tests against the signbit in the form of:
26011 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
26012 // into:
26013 //   SETGT(X, -1)
26014 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
26015   // This is only worth doing if the output type is i8.
26016   if (N->getValueType(0) != MVT::i8)
26017     return SDValue();
26018
26019   SDValue N0 = N->getOperand(0);
26020   SDValue N1 = N->getOperand(1);
26021
26022   // We should be performing an xor against a truncated shift.
26023   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
26024     return SDValue();
26025
26026   // Make sure we are performing an xor against one.
26027   if (!isOneConstant(N1))
26028     return SDValue();
26029
26030   // SetCC on x86 zero extends so only act on this if it's a logical shift.
26031   SDValue Shift = N0.getOperand(0);
26032   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
26033     return SDValue();
26034
26035   // Make sure we are truncating from one of i16, i32 or i64.
26036   EVT ShiftTy = Shift.getValueType();
26037   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
26038     return SDValue();
26039
26040   // Make sure the shift amount extracts the sign bit.
26041   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
26042       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
26043     return SDValue();
26044
26045   // Create a greater-than comparison against -1.
26046   // N.B. Using SETGE against 0 works but we want a canonical looking
26047   // comparison, using SETGT matches up with what TranslateX86CC.
26048   SDLoc DL(N);
26049   SDValue ShiftOp = Shift.getOperand(0);
26050   EVT ShiftOpTy = ShiftOp.getValueType();
26051   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
26052                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
26053   return Cond;
26054 }
26055
26056 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
26057                                  TargetLowering::DAGCombinerInfo &DCI,
26058                                  const X86Subtarget *Subtarget) {
26059   if (DCI.isBeforeLegalizeOps())
26060     return SDValue();
26061
26062   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
26063     return RV;
26064
26065   if (Subtarget->hasCMov())
26066     if (SDValue RV = performIntegerAbsCombine(N, DAG))
26067       return RV;
26068
26069   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
26070     return FPLogic;
26071
26072   return SDValue();
26073 }
26074
26075 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
26076 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
26077 /// X86ISD::AVG instruction.
26078 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
26079                                 const X86Subtarget *Subtarget, SDLoc DL) {
26080   if (!VT.isVector() || !VT.isSimple())
26081     return SDValue();
26082   EVT InVT = In.getValueType();
26083   unsigned NumElems = VT.getVectorNumElements();
26084
26085   EVT ScalarVT = VT.getVectorElementType();
26086   if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) &&
26087         isPowerOf2_32(NumElems)))
26088     return SDValue();
26089
26090   // InScalarVT is the intermediate type in AVG pattern and it should be greater
26091   // than the original input type (i8/i16).
26092   EVT InScalarVT = InVT.getVectorElementType();
26093   if (InScalarVT.getSizeInBits() <= ScalarVT.getSizeInBits())
26094     return SDValue();
26095
26096   if (Subtarget->hasAVX512()) {
26097     if (VT.getSizeInBits() > 512)
26098       return SDValue();
26099   } else if (Subtarget->hasAVX2()) {
26100     if (VT.getSizeInBits() > 256)
26101       return SDValue();
26102   } else {
26103     if (VT.getSizeInBits() > 128)
26104       return SDValue();
26105   }
26106
26107   // Detect the following pattern:
26108   //
26109   //   %1 = zext <N x i8> %a to <N x i32>
26110   //   %2 = zext <N x i8> %b to <N x i32>
26111   //   %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
26112   //   %4 = add nuw nsw <N x i32> %3, %2
26113   //   %5 = lshr <N x i32> %N, <i32 1 x N>
26114   //   %6 = trunc <N x i32> %5 to <N x i8>
26115   //
26116   // In AVX512, the last instruction can also be a trunc store.
26117
26118   if (In.getOpcode() != ISD::SRL)
26119     return SDValue();
26120
26121   // A lambda checking the given SDValue is a constant vector and each element
26122   // is in the range [Min, Max].
26123   auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
26124     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(V);
26125     if (!BV || !BV->isConstant())
26126       return false;
26127     for (unsigned i = 0, e = V.getNumOperands(); i < e; i++) {
26128       ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(i));
26129       if (!C)
26130         return false;
26131       uint64_t Val = C->getZExtValue();
26132       if (Val < Min || Val > Max)
26133         return false;
26134     }
26135     return true;
26136   };
26137
26138   // Check if each element of the vector is left-shifted by one.
26139   auto LHS = In.getOperand(0);
26140   auto RHS = In.getOperand(1);
26141   if (!IsConstVectorInRange(RHS, 1, 1))
26142     return SDValue();
26143   if (LHS.getOpcode() != ISD::ADD)
26144     return SDValue();
26145
26146   // Detect a pattern of a + b + 1 where the order doesn't matter.
26147   SDValue Operands[3];
26148   Operands[0] = LHS.getOperand(0);
26149   Operands[1] = LHS.getOperand(1);
26150
26151   // Take care of the case when one of the operands is a constant vector whose
26152   // element is in the range [1, 256].
26153   if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
26154       Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
26155       Operands[0].getOperand(0).getValueType() == VT) {
26156     // The pattern is detected. Subtract one from the constant vector, then
26157     // demote it and emit X86ISD::AVG instruction.
26158     SDValue One = DAG.getConstant(1, DL, InScalarVT);
26159     SDValue Ones = DAG.getNode(ISD::BUILD_VECTOR, DL, InVT,
26160                                SmallVector<SDValue, 8>(NumElems, One));
26161     Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], Ones);
26162     Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
26163     return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26164                        Operands[1]);
26165   }
26166
26167   if (Operands[0].getOpcode() == ISD::ADD)
26168     std::swap(Operands[0], Operands[1]);
26169   else if (Operands[1].getOpcode() != ISD::ADD)
26170     return SDValue();
26171   Operands[2] = Operands[1].getOperand(0);
26172   Operands[1] = Operands[1].getOperand(1);
26173
26174   // Now we have three operands of two additions. Check that one of them is a
26175   // constant vector with ones, and the other two are promoted from i8/i16.
26176   for (int i = 0; i < 3; ++i) {
26177     if (!IsConstVectorInRange(Operands[i], 1, 1))
26178       continue;
26179     std::swap(Operands[i], Operands[2]);
26180
26181     // Check if Operands[0] and Operands[1] are results of type promotion.
26182     for (int j = 0; j < 2; ++j)
26183       if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
26184           Operands[j].getOperand(0).getValueType() != VT)
26185         return SDValue();
26186
26187     // The pattern is detected, emit X86ISD::AVG instruction.
26188     return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26189                        Operands[1].getOperand(0));
26190   }
26191
26192   return SDValue();
26193 }
26194
26195 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
26196 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
26197                                   TargetLowering::DAGCombinerInfo &DCI,
26198                                   const X86Subtarget *Subtarget) {
26199   LoadSDNode *Ld = cast<LoadSDNode>(N);
26200   EVT RegVT = Ld->getValueType(0);
26201   EVT MemVT = Ld->getMemoryVT();
26202   SDLoc dl(Ld);
26203   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26204
26205   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
26206   // into two 16-byte operations.
26207   ISD::LoadExtType Ext = Ld->getExtensionType();
26208   bool Fast;
26209   unsigned AddressSpace = Ld->getAddressSpace();
26210   unsigned Alignment = Ld->getAlignment();
26211   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
26212       Ext == ISD::NON_EXTLOAD &&
26213       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
26214                              AddressSpace, Alignment, &Fast) && !Fast) {
26215     unsigned NumElems = RegVT.getVectorNumElements();
26216     if (NumElems < 2)
26217       return SDValue();
26218
26219     SDValue Ptr = Ld->getBasePtr();
26220     SDValue Increment =
26221         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26222
26223     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
26224                                   NumElems/2);
26225     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26226                                 Ld->getPointerInfo(), Ld->isVolatile(),
26227                                 Ld->isNonTemporal(), Ld->isInvariant(),
26228                                 Alignment);
26229     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26230     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26231                                 Ld->getPointerInfo(), Ld->isVolatile(),
26232                                 Ld->isNonTemporal(), Ld->isInvariant(),
26233                                 std::min(16U, Alignment));
26234     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
26235                              Load1.getValue(1),
26236                              Load2.getValue(1));
26237
26238     SDValue NewVec = DAG.getUNDEF(RegVT);
26239     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
26240     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
26241     return DCI.CombineTo(N, NewVec, TF, true);
26242   }
26243
26244   return SDValue();
26245 }
26246
26247 /// PerformMLOADCombine - Resolve extending loads
26248 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
26249                                    TargetLowering::DAGCombinerInfo &DCI,
26250                                    const X86Subtarget *Subtarget) {
26251   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
26252   if (Mld->getExtensionType() != ISD::SEXTLOAD)
26253     return SDValue();
26254
26255   EVT VT = Mld->getValueType(0);
26256   unsigned NumElems = VT.getVectorNumElements();
26257   EVT LdVT = Mld->getMemoryVT();
26258   SDLoc dl(Mld);
26259
26260   assert(LdVT != VT && "Cannot extend to the same type");
26261   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
26262   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
26263   // From, To sizes and ElemCount must be pow of two
26264   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26265     "Unexpected size for extending masked load");
26266
26267   unsigned SizeRatio  = ToSz / FromSz;
26268   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
26269
26270   // Create a type on which we perform the shuffle
26271   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26272           LdVT.getScalarType(), NumElems*SizeRatio);
26273   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26274
26275   // Convert Src0 value
26276   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
26277   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
26278     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26279     for (unsigned i = 0; i != NumElems; ++i)
26280       ShuffleVec[i] = i * SizeRatio;
26281
26282     // Can't shuffle using an illegal type.
26283     assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26284            "WideVecVT should be legal");
26285     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
26286                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
26287   }
26288   // Prepare the new mask
26289   SDValue NewMask;
26290   SDValue Mask = Mld->getMask();
26291   if (Mask.getValueType() == VT) {
26292     // Mask and original value have the same type
26293     NewMask = DAG.getBitcast(WideVecVT, Mask);
26294     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26295     for (unsigned i = 0; i != NumElems; ++i)
26296       ShuffleVec[i] = i * SizeRatio;
26297     for (unsigned i = NumElems; i != NumElems * SizeRatio; ++i)
26298       ShuffleVec[i] = NumElems * SizeRatio;
26299     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26300                                    DAG.getConstant(0, dl, WideVecVT),
26301                                    &ShuffleVec[0]);
26302   }
26303   else {
26304     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26305     unsigned WidenNumElts = NumElems*SizeRatio;
26306     unsigned MaskNumElts = VT.getVectorNumElements();
26307     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
26308                                      WidenNumElts);
26309
26310     unsigned NumConcat = WidenNumElts / MaskNumElts;
26311     SmallVector<SDValue, 16> Ops(NumConcat);
26312     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26313     Ops[0] = Mask;
26314     for (unsigned i = 1; i != NumConcat; ++i)
26315       Ops[i] = ZeroVal;
26316
26317     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26318   }
26319
26320   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
26321                                      Mld->getBasePtr(), NewMask, WideSrc0,
26322                                      Mld->getMemoryVT(), Mld->getMemOperand(),
26323                                      ISD::NON_EXTLOAD);
26324   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
26325   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
26326 }
26327 /// PerformMSTORECombine - Resolve truncating stores
26328 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
26329                                     const X86Subtarget *Subtarget) {
26330   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
26331   if (!Mst->isTruncatingStore())
26332     return SDValue();
26333
26334   EVT VT = Mst->getValue().getValueType();
26335   unsigned NumElems = VT.getVectorNumElements();
26336   EVT StVT = Mst->getMemoryVT();
26337   SDLoc dl(Mst);
26338
26339   assert(StVT != VT && "Cannot truncate to the same type");
26340   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26341   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26342
26343   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26344
26345   // The truncating store is legal in some cases. For example
26346   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26347   // are designated for truncate store.
26348   // In this case we don't need any further transformations.
26349   if (TLI.isTruncStoreLegal(VT, StVT))
26350     return SDValue();
26351
26352   // From, To sizes and ElemCount must be pow of two
26353   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26354     "Unexpected size for truncating masked store");
26355   // We are going to use the original vector elt for storing.
26356   // Accumulated smaller vector elements must be a multiple of the store size.
26357   assert (((NumElems * FromSz) % ToSz) == 0 &&
26358           "Unexpected ratio for truncating masked store");
26359
26360   unsigned SizeRatio  = FromSz / ToSz;
26361   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26362
26363   // Create a type on which we perform the shuffle
26364   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26365           StVT.getScalarType(), NumElems*SizeRatio);
26366
26367   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26368
26369   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
26370   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26371   for (unsigned i = 0; i != NumElems; ++i)
26372     ShuffleVec[i] = i * SizeRatio;
26373
26374   // Can't shuffle using an illegal type.
26375   assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26376          "WideVecVT should be legal");
26377
26378   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26379                                               DAG.getUNDEF(WideVecVT),
26380                                               &ShuffleVec[0]);
26381
26382   SDValue NewMask;
26383   SDValue Mask = Mst->getMask();
26384   if (Mask.getValueType() == VT) {
26385     // Mask and original value have the same type
26386     NewMask = DAG.getBitcast(WideVecVT, Mask);
26387     for (unsigned i = 0; i != NumElems; ++i)
26388       ShuffleVec[i] = i * SizeRatio;
26389     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
26390       ShuffleVec[i] = NumElems*SizeRatio;
26391     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26392                                    DAG.getConstant(0, dl, WideVecVT),
26393                                    &ShuffleVec[0]);
26394   }
26395   else {
26396     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26397     unsigned WidenNumElts = NumElems*SizeRatio;
26398     unsigned MaskNumElts = VT.getVectorNumElements();
26399     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
26400                                      WidenNumElts);
26401
26402     unsigned NumConcat = WidenNumElts / MaskNumElts;
26403     SmallVector<SDValue, 16> Ops(NumConcat);
26404     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26405     Ops[0] = Mask;
26406     for (unsigned i = 1; i != NumConcat; ++i)
26407       Ops[i] = ZeroVal;
26408
26409     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26410   }
26411
26412   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal,
26413                             Mst->getBasePtr(), NewMask, StVT,
26414                             Mst->getMemOperand(), false);
26415 }
26416 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
26417 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
26418                                    const X86Subtarget *Subtarget) {
26419   StoreSDNode *St = cast<StoreSDNode>(N);
26420   EVT VT = St->getValue().getValueType();
26421   EVT StVT = St->getMemoryVT();
26422   SDLoc dl(St);
26423   SDValue StoredVal = St->getOperand(1);
26424   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26425
26426   // If we are saving a concatenation of two XMM registers and 32-byte stores
26427   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
26428   bool Fast;
26429   unsigned AddressSpace = St->getAddressSpace();
26430   unsigned Alignment = St->getAlignment();
26431   if (VT.is256BitVector() && StVT == VT &&
26432       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
26433                              AddressSpace, Alignment, &Fast) && !Fast) {
26434     unsigned NumElems = VT.getVectorNumElements();
26435     if (NumElems < 2)
26436       return SDValue();
26437
26438     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
26439     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
26440
26441     SDValue Stride =
26442         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26443     SDValue Ptr0 = St->getBasePtr();
26444     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
26445
26446     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
26447                                 St->getPointerInfo(), St->isVolatile(),
26448                                 St->isNonTemporal(), Alignment);
26449     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
26450                                 St->getPointerInfo(), St->isVolatile(),
26451                                 St->isNonTemporal(),
26452                                 std::min(16U, Alignment));
26453     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
26454   }
26455
26456   // Optimize trunc store (of multiple scalars) to shuffle and store.
26457   // First, pack all of the elements in one place. Next, store to memory
26458   // in fewer chunks.
26459   if (St->isTruncatingStore() && VT.isVector()) {
26460     // Check if we can detect an AVG pattern from the truncation. If yes,
26461     // replace the trunc store by a normal store with the result of X86ISD::AVG
26462     // instruction.
26463     SDValue Avg =
26464         detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG, Subtarget, dl);
26465     if (Avg.getNode())
26466       return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
26467                           St->getPointerInfo(), St->isVolatile(),
26468                           St->isNonTemporal(), St->getAlignment());
26469
26470     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26471     unsigned NumElems = VT.getVectorNumElements();
26472     assert(StVT != VT && "Cannot truncate to the same type");
26473     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26474     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26475
26476     // The truncating store is legal in some cases. For example
26477     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26478     // are designated for truncate store.
26479     // In this case we don't need any further transformations.
26480     if (TLI.isTruncStoreLegal(VT, StVT))
26481       return SDValue();
26482
26483     // From, To sizes and ElemCount must be pow of two
26484     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
26485     // We are going to use the original vector elt for storing.
26486     // Accumulated smaller vector elements must be a multiple of the store size.
26487     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
26488
26489     unsigned SizeRatio  = FromSz / ToSz;
26490
26491     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26492
26493     // Create a type on which we perform the shuffle
26494     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26495             StVT.getScalarType(), NumElems*SizeRatio);
26496
26497     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26498
26499     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
26500     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
26501     for (unsigned i = 0; i != NumElems; ++i)
26502       ShuffleVec[i] = i * SizeRatio;
26503
26504     // Can't shuffle using an illegal type.
26505     if (!TLI.isTypeLegal(WideVecVT))
26506       return SDValue();
26507
26508     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26509                                          DAG.getUNDEF(WideVecVT),
26510                                          &ShuffleVec[0]);
26511     // At this point all of the data is stored at the bottom of the
26512     // register. We now need to save it to mem.
26513
26514     // Find the largest store unit
26515     MVT StoreType = MVT::i8;
26516     for (MVT Tp : MVT::integer_valuetypes()) {
26517       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
26518         StoreType = Tp;
26519     }
26520
26521     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
26522     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
26523         (64 <= NumElems * ToSz))
26524       StoreType = MVT::f64;
26525
26526     // Bitcast the original vector into a vector of store-size units
26527     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
26528             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
26529     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
26530     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
26531     SmallVector<SDValue, 8> Chains;
26532     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
26533                                         TLI.getPointerTy(DAG.getDataLayout()));
26534     SDValue Ptr = St->getBasePtr();
26535
26536     // Perform one or more big stores into memory.
26537     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
26538       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
26539                                    StoreType, ShuffWide,
26540                                    DAG.getIntPtrConstant(i, dl));
26541       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
26542                                 St->getPointerInfo(), St->isVolatile(),
26543                                 St->isNonTemporal(), St->getAlignment());
26544       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26545       Chains.push_back(Ch);
26546     }
26547
26548     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
26549   }
26550
26551   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
26552   // the FP state in cases where an emms may be missing.
26553   // A preferable solution to the general problem is to figure out the right
26554   // places to insert EMMS.  This qualifies as a quick hack.
26555
26556   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
26557   if (VT.getSizeInBits() != 64)
26558     return SDValue();
26559
26560   const Function *F = DAG.getMachineFunction().getFunction();
26561   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
26562   bool F64IsLegal =
26563       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
26564   if ((VT.isVector() ||
26565        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
26566       isa<LoadSDNode>(St->getValue()) &&
26567       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
26568       St->getChain().hasOneUse() && !St->isVolatile()) {
26569     SDNode* LdVal = St->getValue().getNode();
26570     LoadSDNode *Ld = nullptr;
26571     int TokenFactorIndex = -1;
26572     SmallVector<SDValue, 8> Ops;
26573     SDNode* ChainVal = St->getChain().getNode();
26574     // Must be a store of a load.  We currently handle two cases:  the load
26575     // is a direct child, and it's under an intervening TokenFactor.  It is
26576     // possible to dig deeper under nested TokenFactors.
26577     if (ChainVal == LdVal)
26578       Ld = cast<LoadSDNode>(St->getChain());
26579     else if (St->getValue().hasOneUse() &&
26580              ChainVal->getOpcode() == ISD::TokenFactor) {
26581       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
26582         if (ChainVal->getOperand(i).getNode() == LdVal) {
26583           TokenFactorIndex = i;
26584           Ld = cast<LoadSDNode>(St->getValue());
26585         } else
26586           Ops.push_back(ChainVal->getOperand(i));
26587       }
26588     }
26589
26590     if (!Ld || !ISD::isNormalLoad(Ld))
26591       return SDValue();
26592
26593     // If this is not the MMX case, i.e. we are just turning i64 load/store
26594     // into f64 load/store, avoid the transformation if there are multiple
26595     // uses of the loaded value.
26596     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
26597       return SDValue();
26598
26599     SDLoc LdDL(Ld);
26600     SDLoc StDL(N);
26601     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
26602     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
26603     // pair instead.
26604     if (Subtarget->is64Bit() || F64IsLegal) {
26605       MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
26606       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
26607                                   Ld->getPointerInfo(), Ld->isVolatile(),
26608                                   Ld->isNonTemporal(), Ld->isInvariant(),
26609                                   Ld->getAlignment());
26610       SDValue NewChain = NewLd.getValue(1);
26611       if (TokenFactorIndex != -1) {
26612         Ops.push_back(NewChain);
26613         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26614       }
26615       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
26616                           St->getPointerInfo(),
26617                           St->isVolatile(), St->isNonTemporal(),
26618                           St->getAlignment());
26619     }
26620
26621     // Otherwise, lower to two pairs of 32-bit loads / stores.
26622     SDValue LoAddr = Ld->getBasePtr();
26623     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
26624                                  DAG.getConstant(4, LdDL, MVT::i32));
26625
26626     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
26627                                Ld->getPointerInfo(),
26628                                Ld->isVolatile(), Ld->isNonTemporal(),
26629                                Ld->isInvariant(), Ld->getAlignment());
26630     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
26631                                Ld->getPointerInfo().getWithOffset(4),
26632                                Ld->isVolatile(), Ld->isNonTemporal(),
26633                                Ld->isInvariant(),
26634                                MinAlign(Ld->getAlignment(), 4));
26635
26636     SDValue NewChain = LoLd.getValue(1);
26637     if (TokenFactorIndex != -1) {
26638       Ops.push_back(LoLd);
26639       Ops.push_back(HiLd);
26640       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26641     }
26642
26643     LoAddr = St->getBasePtr();
26644     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
26645                          DAG.getConstant(4, StDL, MVT::i32));
26646
26647     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
26648                                 St->getPointerInfo(),
26649                                 St->isVolatile(), St->isNonTemporal(),
26650                                 St->getAlignment());
26651     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
26652                                 St->getPointerInfo().getWithOffset(4),
26653                                 St->isVolatile(),
26654                                 St->isNonTemporal(),
26655                                 MinAlign(St->getAlignment(), 4));
26656     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
26657   }
26658
26659   // This is similar to the above case, but here we handle a scalar 64-bit
26660   // integer store that is extracted from a vector on a 32-bit target.
26661   // If we have SSE2, then we can treat it like a floating-point double
26662   // to get past legalization. The execution dependencies fixup pass will
26663   // choose the optimal machine instruction for the store if this really is
26664   // an integer or v2f32 rather than an f64.
26665   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
26666       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
26667     SDValue OldExtract = St->getOperand(1);
26668     SDValue ExtOp0 = OldExtract.getOperand(0);
26669     unsigned VecSize = ExtOp0.getValueSizeInBits();
26670     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
26671     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
26672     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
26673                                      BitCast, OldExtract.getOperand(1));
26674     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
26675                         St->getPointerInfo(), St->isVolatile(),
26676                         St->isNonTemporal(), St->getAlignment());
26677   }
26678
26679   return SDValue();
26680 }
26681
26682 /// Return 'true' if this vector operation is "horizontal"
26683 /// and return the operands for the horizontal operation in LHS and RHS.  A
26684 /// horizontal operation performs the binary operation on successive elements
26685 /// of its first operand, then on successive elements of its second operand,
26686 /// returning the resulting values in a vector.  For example, if
26687 ///   A = < float a0, float a1, float a2, float a3 >
26688 /// and
26689 ///   B = < float b0, float b1, float b2, float b3 >
26690 /// then the result of doing a horizontal operation on A and B is
26691 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
26692 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
26693 /// A horizontal-op B, for some already available A and B, and if so then LHS is
26694 /// set to A, RHS to B, and the routine returns 'true'.
26695 /// Note that the binary operation should have the property that if one of the
26696 /// operands is UNDEF then the result is UNDEF.
26697 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
26698   // Look for the following pattern: if
26699   //   A = < float a0, float a1, float a2, float a3 >
26700   //   B = < float b0, float b1, float b2, float b3 >
26701   // and
26702   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
26703   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
26704   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
26705   // which is A horizontal-op B.
26706
26707   // At least one of the operands should be a vector shuffle.
26708   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
26709       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
26710     return false;
26711
26712   MVT VT = LHS.getSimpleValueType();
26713
26714   assert((VT.is128BitVector() || VT.is256BitVector()) &&
26715          "Unsupported vector type for horizontal add/sub");
26716
26717   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
26718   // operate independently on 128-bit lanes.
26719   unsigned NumElts = VT.getVectorNumElements();
26720   unsigned NumLanes = VT.getSizeInBits()/128;
26721   unsigned NumLaneElts = NumElts / NumLanes;
26722   assert((NumLaneElts % 2 == 0) &&
26723          "Vector type should have an even number of elements in each lane");
26724   unsigned HalfLaneElts = NumLaneElts/2;
26725
26726   // View LHS in the form
26727   //   LHS = VECTOR_SHUFFLE A, B, LMask
26728   // If LHS is not a shuffle then pretend it is the shuffle
26729   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
26730   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
26731   // type VT.
26732   SDValue A, B;
26733   SmallVector<int, 16> LMask(NumElts);
26734   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26735     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
26736       A = LHS.getOperand(0);
26737     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
26738       B = LHS.getOperand(1);
26739     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
26740     std::copy(Mask.begin(), Mask.end(), LMask.begin());
26741   } else {
26742     if (LHS.getOpcode() != ISD::UNDEF)
26743       A = LHS;
26744     for (unsigned i = 0; i != NumElts; ++i)
26745       LMask[i] = i;
26746   }
26747
26748   // Likewise, view RHS in the form
26749   //   RHS = VECTOR_SHUFFLE C, D, RMask
26750   SDValue C, D;
26751   SmallVector<int, 16> RMask(NumElts);
26752   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26753     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
26754       C = RHS.getOperand(0);
26755     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
26756       D = RHS.getOperand(1);
26757     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
26758     std::copy(Mask.begin(), Mask.end(), RMask.begin());
26759   } else {
26760     if (RHS.getOpcode() != ISD::UNDEF)
26761       C = RHS;
26762     for (unsigned i = 0; i != NumElts; ++i)
26763       RMask[i] = i;
26764   }
26765
26766   // Check that the shuffles are both shuffling the same vectors.
26767   if (!(A == C && B == D) && !(A == D && B == C))
26768     return false;
26769
26770   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
26771   if (!A.getNode() && !B.getNode())
26772     return false;
26773
26774   // If A and B occur in reverse order in RHS, then "swap" them (which means
26775   // rewriting the mask).
26776   if (A != C)
26777     ShuffleVectorSDNode::commuteMask(RMask);
26778
26779   // At this point LHS and RHS are equivalent to
26780   //   LHS = VECTOR_SHUFFLE A, B, LMask
26781   //   RHS = VECTOR_SHUFFLE A, B, RMask
26782   // Check that the masks correspond to performing a horizontal operation.
26783   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
26784     for (unsigned i = 0; i != NumLaneElts; ++i) {
26785       int LIdx = LMask[i+l], RIdx = RMask[i+l];
26786
26787       // Ignore any UNDEF components.
26788       if (LIdx < 0 || RIdx < 0 ||
26789           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
26790           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
26791         continue;
26792
26793       // Check that successive elements are being operated on.  If not, this is
26794       // not a horizontal operation.
26795       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
26796       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
26797       if (!(LIdx == Index && RIdx == Index + 1) &&
26798           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
26799         return false;
26800     }
26801   }
26802
26803   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
26804   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
26805   return true;
26806 }
26807
26808 /// Do target-specific dag combines on floating point adds.
26809 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
26810                                   const X86Subtarget *Subtarget) {
26811   EVT VT = N->getValueType(0);
26812   SDValue LHS = N->getOperand(0);
26813   SDValue RHS = N->getOperand(1);
26814
26815   // Try to synthesize horizontal adds from adds of shuffles.
26816   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26817        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26818       isHorizontalBinOp(LHS, RHS, true))
26819     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
26820   return SDValue();
26821 }
26822
26823 /// Do target-specific dag combines on floating point subs.
26824 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
26825                                   const X86Subtarget *Subtarget) {
26826   EVT VT = N->getValueType(0);
26827   SDValue LHS = N->getOperand(0);
26828   SDValue RHS = N->getOperand(1);
26829
26830   // Try to synthesize horizontal subs from subs of shuffles.
26831   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26832        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26833       isHorizontalBinOp(LHS, RHS, false))
26834     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
26835   return SDValue();
26836 }
26837
26838 /// Truncate a group of v4i32 into v16i8/v8i16 using X86ISD::PACKUS.
26839 static SDValue
26840 combineVectorTruncationWithPACKUS(SDNode *N, SelectionDAG &DAG,
26841                                   SmallVector<SDValue, 8> &Regs) {
26842   assert(Regs.size() > 0 && (Regs[0].getValueType() == MVT::v4i32 ||
26843                              Regs[0].getValueType() == MVT::v2i64));
26844   EVT OutVT = N->getValueType(0);
26845   EVT OutSVT = OutVT.getVectorElementType();
26846   EVT InVT = Regs[0].getValueType();
26847   EVT InSVT = InVT.getVectorElementType();
26848   SDLoc DL(N);
26849
26850   // First, use mask to unset all bits that won't appear in the result.
26851   assert((OutSVT == MVT::i8 || OutSVT == MVT::i16) &&
26852          "OutSVT can only be either i8 or i16.");
26853   SDValue MaskVal =
26854       DAG.getConstant(OutSVT == MVT::i8 ? 0xFF : 0xFFFF, DL, InSVT);
26855   SDValue MaskVec = DAG.getNode(
26856       ISD::BUILD_VECTOR, DL, InVT,
26857       SmallVector<SDValue, 8>(InVT.getVectorNumElements(), MaskVal));
26858   for (auto &Reg : Regs)
26859     Reg = DAG.getNode(ISD::AND, DL, InVT, MaskVec, Reg);
26860
26861   MVT UnpackedVT, PackedVT;
26862   if (OutSVT == MVT::i8) {
26863     UnpackedVT = MVT::v8i16;
26864     PackedVT = MVT::v16i8;
26865   } else {
26866     UnpackedVT = MVT::v4i32;
26867     PackedVT = MVT::v8i16;
26868   }
26869
26870   // In each iteration, truncate the type by a half size.
26871   auto RegNum = Regs.size();
26872   for (unsigned j = 1, e = InSVT.getSizeInBits() / OutSVT.getSizeInBits();
26873        j < e; j *= 2, RegNum /= 2) {
26874     for (unsigned i = 0; i < RegNum; i++)
26875       Regs[i] = DAG.getNode(ISD::BITCAST, DL, UnpackedVT, Regs[i]);
26876     for (unsigned i = 0; i < RegNum / 2; i++)
26877       Regs[i] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[i * 2],
26878                             Regs[i * 2 + 1]);
26879   }
26880
26881   // If the type of the result is v8i8, we need do one more X86ISD::PACKUS, and
26882   // then extract a subvector as the result since v8i8 is not a legal type.
26883   if (OutVT == MVT::v8i8) {
26884     Regs[0] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[0], Regs[0]);
26885     Regs[0] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, Regs[0],
26886                           DAG.getIntPtrConstant(0, DL));
26887     return Regs[0];
26888   } else if (RegNum > 1) {
26889     Regs.resize(RegNum);
26890     return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26891   } else
26892     return Regs[0];
26893 }
26894
26895 /// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
26896 static SDValue
26897 combineVectorTruncationWithPACKSS(SDNode *N, SelectionDAG &DAG,
26898                                   SmallVector<SDValue, 8> &Regs) {
26899   assert(Regs.size() > 0 && Regs[0].getValueType() == MVT::v4i32);
26900   EVT OutVT = N->getValueType(0);
26901   SDLoc DL(N);
26902
26903   // Shift left by 16 bits, then arithmetic-shift right by 16 bits.
26904   SDValue ShAmt = DAG.getConstant(16, DL, MVT::i32);
26905   for (auto &Reg : Regs) {
26906     Reg = getTargetVShiftNode(X86ISD::VSHLI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26907     Reg = getTargetVShiftNode(X86ISD::VSRAI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26908   }
26909
26910   for (unsigned i = 0, e = Regs.size() / 2; i < e; i++)
26911     Regs[i] = DAG.getNode(X86ISD::PACKSS, DL, MVT::v8i16, Regs[i * 2],
26912                           Regs[i * 2 + 1]);
26913
26914   if (Regs.size() > 2) {
26915     Regs.resize(Regs.size() / 2);
26916     return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26917   } else
26918     return Regs[0];
26919 }
26920
26921 /// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
26922 /// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
26923 /// legalization the truncation will be translated into a BUILD_VECTOR with each
26924 /// element that is extracted from a vector and then truncated, and it is
26925 /// diffcult to do this optimization based on them.
26926 static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
26927                                        const X86Subtarget *Subtarget) {
26928   EVT OutVT = N->getValueType(0);
26929   if (!OutVT.isVector())
26930     return SDValue();
26931
26932   SDValue In = N->getOperand(0);
26933   if (!In.getValueType().isSimple())
26934     return SDValue();
26935
26936   EVT InVT = In.getValueType();
26937   unsigned NumElems = OutVT.getVectorNumElements();
26938
26939   // TODO: On AVX2, the behavior of X86ISD::PACKUS is different from that on
26940   // SSE2, and we need to take care of it specially.
26941   // AVX512 provides vpmovdb.
26942   if (!Subtarget->hasSSE2() || Subtarget->hasAVX2())
26943     return SDValue();
26944
26945   EVT OutSVT = OutVT.getVectorElementType();
26946   EVT InSVT = InVT.getVectorElementType();
26947   if (!((InSVT == MVT::i32 || InSVT == MVT::i64) &&
26948         (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
26949         NumElems >= 8))
26950     return SDValue();
26951
26952   // SSSE3's pshufb results in less instructions in the cases below.
26953   if (Subtarget->hasSSSE3() && NumElems == 8 &&
26954       ((OutSVT == MVT::i8 && InSVT != MVT::i64) ||
26955        (InSVT == MVT::i32 && OutSVT == MVT::i16)))
26956     return SDValue();
26957
26958   SDLoc DL(N);
26959
26960   // Split a long vector into vectors of legal type.
26961   unsigned RegNum = InVT.getSizeInBits() / 128;
26962   SmallVector<SDValue, 8> SubVec(RegNum);
26963   if (InSVT == MVT::i32) {
26964     for (unsigned i = 0; i < RegNum; i++)
26965       SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
26966                               DAG.getIntPtrConstant(i * 4, DL));
26967   } else {
26968     for (unsigned i = 0; i < RegNum; i++)
26969       SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
26970                               DAG.getIntPtrConstant(i * 2, DL));
26971   }
26972
26973   // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PAKCUS
26974   // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
26975   // truncate 2 x v4i32 to v8i16.
26976   if (Subtarget->hasSSE41() || OutSVT == MVT::i8)
26977     return combineVectorTruncationWithPACKUS(N, DAG, SubVec);
26978   else if (InSVT == MVT::i32)
26979     return combineVectorTruncationWithPACKSS(N, DAG, SubVec);
26980   else
26981     return SDValue();
26982 }
26983
26984 static SDValue PerformTRUNCATECombine(SDNode *N, SelectionDAG &DAG,
26985                                       const X86Subtarget *Subtarget) {
26986   // Try to detect AVG pattern first.
26987   SDValue Avg = detectAVGPattern(N->getOperand(0), N->getValueType(0), DAG,
26988                                  Subtarget, SDLoc(N));
26989   if (Avg.getNode())
26990     return Avg;
26991
26992   return combineVectorTruncation(N, DAG, Subtarget);
26993 }
26994
26995 /// Do target-specific dag combines on floating point negations.
26996 static SDValue PerformFNEGCombine(SDNode *N, SelectionDAG &DAG,
26997                                   const X86Subtarget *Subtarget) {
26998   EVT VT = N->getValueType(0);
26999   EVT SVT = VT.getScalarType();
27000   SDValue Arg = N->getOperand(0);
27001   SDLoc DL(N);
27002
27003   // Let legalize expand this if it isn't a legal type yet.
27004   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
27005     return SDValue();
27006
27007   // If we're negating a FMUL node on a target with FMA, then we can avoid the
27008   // use of a constant by performing (-0 - A*B) instead.
27009   // FIXME: Check rounding control flags as well once it becomes available.
27010   if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
27011       Arg->getFlags()->hasNoSignedZeros() && Subtarget->hasAnyFMA()) {
27012     SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
27013     return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
27014                        Arg.getOperand(1), Zero);
27015   }
27016
27017   // If we're negating a FMA node, then we can adjust the
27018   // instruction to include the extra negation.
27019   if (Arg.hasOneUse()) {
27020     switch (Arg.getOpcode()) {
27021     case X86ISD::FMADD:
27022       return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
27023                          Arg.getOperand(1), Arg.getOperand(2));
27024     case X86ISD::FMSUB:
27025       return DAG.getNode(X86ISD::FNMADD, DL, VT, Arg.getOperand(0),
27026                          Arg.getOperand(1), Arg.getOperand(2));
27027     case X86ISD::FNMADD:
27028       return DAG.getNode(X86ISD::FMSUB, DL, VT, Arg.getOperand(0),
27029                          Arg.getOperand(1), Arg.getOperand(2));
27030     case X86ISD::FNMSUB:
27031       return DAG.getNode(X86ISD::FMADD, DL, VT, Arg.getOperand(0),
27032                          Arg.getOperand(1), Arg.getOperand(2));
27033     }
27034   }
27035   return SDValue();
27036 }
27037
27038 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
27039                               const X86Subtarget *Subtarget) {
27040   EVT VT = N->getValueType(0);
27041   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
27042     // VXORPS, VORPS, VANDPS, VANDNPS are supported only under DQ extention.
27043     // These logic operations may be executed in the integer domain.
27044     SDLoc dl(N);
27045     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
27046     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
27047
27048     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
27049     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
27050     unsigned IntOpcode = 0;
27051     switch (N->getOpcode()) {
27052       default: llvm_unreachable("Unexpected FP logic op");
27053       case X86ISD::FOR: IntOpcode = ISD::OR; break;
27054       case X86ISD::FXOR: IntOpcode = ISD::XOR; break;
27055       case X86ISD::FAND: IntOpcode = ISD::AND; break;
27056       case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
27057     }
27058     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
27059     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
27060   }
27061   return SDValue();
27062 }
27063 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
27064 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
27065                                  const X86Subtarget *Subtarget) {
27066   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
27067
27068   // F[X]OR(0.0, x) -> x
27069   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27070     if (C->getValueAPF().isPosZero())
27071       return N->getOperand(1);
27072
27073   // F[X]OR(x, 0.0) -> x
27074   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27075     if (C->getValueAPF().isPosZero())
27076       return N->getOperand(0);
27077
27078   return lowerX86FPLogicOp(N, DAG, Subtarget);
27079 }
27080
27081 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
27082 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
27083   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
27084
27085   // Only perform optimizations if UnsafeMath is used.
27086   if (!DAG.getTarget().Options.UnsafeFPMath)
27087     return SDValue();
27088
27089   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
27090   // into FMINC and FMAXC, which are Commutative operations.
27091   unsigned NewOp = 0;
27092   switch (N->getOpcode()) {
27093     default: llvm_unreachable("unknown opcode");
27094     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
27095     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
27096   }
27097
27098   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
27099                      N->getOperand(0), N->getOperand(1));
27100 }
27101
27102 static SDValue performFMinNumFMaxNumCombine(SDNode *N, SelectionDAG &DAG,
27103                                             const X86Subtarget *Subtarget) {
27104   if (Subtarget->useSoftFloat())
27105     return SDValue();
27106
27107   // TODO: Check for global or instruction-level "nnan". In that case, we
27108   //       should be able to lower to FMAX/FMIN alone.
27109   // TODO: If an operand is already known to be a NaN or not a NaN, this
27110   //       should be an optional swap and FMAX/FMIN.
27111
27112   EVT VT = N->getValueType(0);
27113   if (!((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
27114         (Subtarget->hasSSE2() && (VT == MVT::f64 || VT == MVT::v2f64)) ||
27115         (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))))
27116     return SDValue();
27117
27118   // This takes at least 3 instructions, so favor a library call when operating
27119   // on a scalar and minimizing code size.
27120   if (!VT.isVector() && DAG.getMachineFunction().getFunction()->optForMinSize())
27121     return SDValue();
27122
27123   SDValue Op0 = N->getOperand(0);
27124   SDValue Op1 = N->getOperand(1);
27125   SDLoc DL(N);
27126   EVT SetCCType = DAG.getTargetLoweringInfo().getSetCCResultType(
27127       DAG.getDataLayout(), *DAG.getContext(), VT);
27128
27129   // There are 4 possibilities involving NaN inputs, and these are the required
27130   // outputs:
27131   //                   Op1
27132   //               Num     NaN
27133   //            ----------------
27134   //       Num  |  Max  |  Op0 |
27135   // Op0        ----------------
27136   //       NaN  |  Op1  |  NaN |
27137   //            ----------------
27138   //
27139   // The SSE FP max/min instructions were not designed for this case, but rather
27140   // to implement:
27141   //   Min = Op1 < Op0 ? Op1 : Op0
27142   //   Max = Op1 > Op0 ? Op1 : Op0
27143   //
27144   // So they always return Op0 if either input is a NaN. However, we can still
27145   // use those instructions for fmaxnum by selecting away a NaN input.
27146
27147   // If either operand is NaN, the 2nd source operand (Op0) is passed through.
27148   auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
27149   SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
27150   SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType , Op0, Op0, ISD::SETUO);
27151
27152   // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
27153   // are NaN, the NaN value of Op1 is the result.
27154   auto SelectOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT;
27155   return DAG.getNode(SelectOpcode, DL, VT, IsOp0Nan, Op1, MinOrMax);
27156 }
27157
27158 /// Do target-specific dag combines on X86ISD::FAND nodes.
27159 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG,
27160                                   const X86Subtarget *Subtarget) {
27161   // FAND(0.0, x) -> 0.0
27162   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27163     if (C->getValueAPF().isPosZero())
27164       return N->getOperand(0);
27165
27166   // FAND(x, 0.0) -> 0.0
27167   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27168     if (C->getValueAPF().isPosZero())
27169       return N->getOperand(1);
27170
27171   return lowerX86FPLogicOp(N, DAG, Subtarget);
27172 }
27173
27174 /// Do target-specific dag combines on X86ISD::FANDN nodes
27175 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG,
27176                                    const X86Subtarget *Subtarget) {
27177   // FANDN(0.0, x) -> x
27178   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27179     if (C->getValueAPF().isPosZero())
27180       return N->getOperand(1);
27181
27182   // FANDN(x, 0.0) -> 0.0
27183   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27184     if (C->getValueAPF().isPosZero())
27185       return N->getOperand(1);
27186
27187   return lowerX86FPLogicOp(N, DAG, Subtarget);
27188 }
27189
27190 static SDValue PerformBTCombine(SDNode *N,
27191                                 SelectionDAG &DAG,
27192                                 TargetLowering::DAGCombinerInfo &DCI) {
27193   // BT ignores high bits in the bit index operand.
27194   SDValue Op1 = N->getOperand(1);
27195   if (Op1.hasOneUse()) {
27196     unsigned BitWidth = Op1.getValueSizeInBits();
27197     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
27198     APInt KnownZero, KnownOne;
27199     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
27200                                           !DCI.isBeforeLegalizeOps());
27201     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27202     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
27203         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
27204       DCI.CommitTargetLoweringOpt(TLO);
27205   }
27206   return SDValue();
27207 }
27208
27209 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
27210   SDValue Op = N->getOperand(0);
27211   if (Op.getOpcode() == ISD::BITCAST)
27212     Op = Op.getOperand(0);
27213   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
27214   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
27215       VT.getVectorElementType().getSizeInBits() ==
27216       OpVT.getVectorElementType().getSizeInBits()) {
27217     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
27218   }
27219   return SDValue();
27220 }
27221
27222 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
27223                                                const X86Subtarget *Subtarget) {
27224   EVT VT = N->getValueType(0);
27225   if (!VT.isVector())
27226     return SDValue();
27227
27228   SDValue N0 = N->getOperand(0);
27229   SDValue N1 = N->getOperand(1);
27230   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
27231   SDLoc dl(N);
27232
27233   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
27234   // both SSE and AVX2 since there is no sign-extended shift right
27235   // operation on a vector with 64-bit elements.
27236   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
27237   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
27238   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
27239       N0.getOpcode() == ISD::SIGN_EXTEND)) {
27240     SDValue N00 = N0.getOperand(0);
27241
27242     // EXTLOAD has a better solution on AVX2,
27243     // it may be replaced with X86ISD::VSEXT node.
27244     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
27245       if (!ISD::isNormalLoad(N00.getNode()))
27246         return SDValue();
27247
27248     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
27249         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
27250                                   N00, N1);
27251       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
27252     }
27253   }
27254   return SDValue();
27255 }
27256
27257 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
27258 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
27259 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
27260 /// eliminate extend, add, and shift instructions.
27261 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
27262                                        const X86Subtarget *Subtarget) {
27263   // TODO: This should be valid for other integer types.
27264   EVT VT = Sext->getValueType(0);
27265   if (VT != MVT::i64)
27266     return SDValue();
27267
27268   // We need an 'add nsw' feeding into the 'sext'.
27269   SDValue Add = Sext->getOperand(0);
27270   if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
27271     return SDValue();
27272
27273   // Having a constant operand to the 'add' ensures that we are not increasing
27274   // the instruction count because the constant is extended for free below.
27275   // A constant operand can also become the displacement field of an LEA.
27276   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
27277   if (!AddOp1)
27278     return SDValue();
27279
27280   // Don't make the 'add' bigger if there's no hope of combining it with some
27281   // other 'add' or 'shl' instruction.
27282   // TODO: It may be profitable to generate simpler LEA instructions in place
27283   // of single 'add' instructions, but the cost model for selecting an LEA
27284   // currently has a high threshold.
27285   bool HasLEAPotential = false;
27286   for (auto *User : Sext->uses()) {
27287     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
27288       HasLEAPotential = true;
27289       break;
27290     }
27291   }
27292   if (!HasLEAPotential)
27293     return SDValue();
27294
27295   // Everything looks good, so pull the 'sext' ahead of the 'add'.
27296   int64_t AddConstant = AddOp1->getSExtValue();
27297   SDValue AddOp0 = Add.getOperand(0);
27298   SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
27299   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
27300
27301   // The wider add is guaranteed to not wrap because both operands are
27302   // sign-extended.
27303   SDNodeFlags Flags;
27304   Flags.setNoSignedWrap(true);
27305   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
27306 }
27307
27308 /// (i8,i32 {s/z}ext ({s/u}divrem (i8 x, i8 y)) ->
27309 /// (i8,i32 ({s/u}divrem_sext_hreg (i8 x, i8 y)
27310 /// This exposes the {s/z}ext to the sdivrem lowering, so that it directly
27311 /// extends from AH (which we otherwise need to do contortions to access).
27312 static SDValue getDivRem8(SDNode *N, SelectionDAG &DAG) {
27313   SDValue N0 = N->getOperand(0);
27314   auto OpcodeN = N->getOpcode();
27315   auto OpcodeN0 = N0.getOpcode();
27316   if (!((OpcodeN == ISD::SIGN_EXTEND && OpcodeN0 == ISD::SDIVREM) ||
27317         (OpcodeN == ISD::ZERO_EXTEND && OpcodeN0 == ISD::UDIVREM)))
27318     return SDValue();
27319
27320   EVT VT = N->getValueType(0);
27321   EVT InVT = N0.getValueType();
27322   if (N0.getResNo() != 1 || InVT != MVT::i8 || VT != MVT::i32)
27323     return SDValue();
27324
27325   SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
27326   auto DivRemOpcode = OpcodeN0 == ISD::SDIVREM ? X86ISD::SDIVREM8_SEXT_HREG
27327                                                : X86ISD::UDIVREM8_ZEXT_HREG;
27328   SDValue R = DAG.getNode(DivRemOpcode, SDLoc(N), NodeTys, N0.getOperand(0),
27329                           N0.getOperand(1));
27330   DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
27331   return R.getValue(1);
27332 }
27333
27334 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
27335                                   TargetLowering::DAGCombinerInfo &DCI,
27336                                   const X86Subtarget *Subtarget) {
27337   SDValue N0 = N->getOperand(0);
27338   EVT VT = N->getValueType(0);
27339   EVT SVT = VT.getScalarType();
27340   EVT InVT = N0.getValueType();
27341   EVT InSVT = InVT.getScalarType();
27342   SDLoc DL(N);
27343
27344   if (SDValue DivRem8 = getDivRem8(N, DAG))
27345     return DivRem8;
27346
27347   if (!DCI.isBeforeLegalizeOps()) {
27348     if (InVT == MVT::i1) {
27349       SDValue Zero = DAG.getConstant(0, DL, VT);
27350       SDValue AllOnes =
27351         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
27352       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
27353     }
27354     return SDValue();
27355   }
27356
27357   if (VT.isVector() && Subtarget->hasSSE2()) {
27358     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
27359       EVT InVT = N.getValueType();
27360       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
27361                                    Size / InVT.getScalarSizeInBits());
27362       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
27363                                     DAG.getUNDEF(InVT));
27364       Opnds[0] = N;
27365       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
27366     };
27367
27368     // If target-size is less than 128-bits, extend to a type that would extend
27369     // to 128 bits, extend that and extract the original target vector.
27370     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
27371         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27372         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27373       unsigned Scale = 128 / VT.getSizeInBits();
27374       EVT ExVT =
27375           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
27376       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
27377       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
27378       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
27379                          DAG.getIntPtrConstant(0, DL));
27380     }
27381
27382     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
27383     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
27384     if (VT.getSizeInBits() == 128 &&
27385         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27386         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27387       SDValue ExOp = ExtendVecSize(DL, N0, 128);
27388       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
27389     }
27390
27391     // On pre-AVX2 targets, split into 128-bit nodes of
27392     // ISD::SIGN_EXTEND_VECTOR_INREG.
27393     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
27394         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27395         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27396       unsigned NumVecs = VT.getSizeInBits() / 128;
27397       unsigned NumSubElts = 128 / SVT.getSizeInBits();
27398       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
27399       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
27400
27401       SmallVector<SDValue, 8> Opnds;
27402       for (unsigned i = 0, Offset = 0; i != NumVecs;
27403            ++i, Offset += NumSubElts) {
27404         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
27405                                      DAG.getIntPtrConstant(Offset, DL));
27406         SrcVec = ExtendVecSize(DL, SrcVec, 128);
27407         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
27408         Opnds.push_back(SrcVec);
27409       }
27410       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
27411     }
27412   }
27413
27414   if (Subtarget->hasAVX() && VT.is256BitVector())
27415     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27416       return R;
27417
27418   if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
27419     return NewAdd;
27420
27421   return SDValue();
27422 }
27423
27424 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
27425                                  const X86Subtarget* Subtarget) {
27426   SDLoc dl(N);
27427   EVT VT = N->getValueType(0);
27428
27429   // Let legalize expand this if it isn't a legal type yet.
27430   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
27431     return SDValue();
27432
27433   EVT ScalarVT = VT.getScalarType();
27434   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget->hasAnyFMA())
27435     return SDValue();
27436
27437   SDValue A = N->getOperand(0);
27438   SDValue B = N->getOperand(1);
27439   SDValue C = N->getOperand(2);
27440
27441   bool NegA = (A.getOpcode() == ISD::FNEG);
27442   bool NegB = (B.getOpcode() == ISD::FNEG);
27443   bool NegC = (C.getOpcode() == ISD::FNEG);
27444
27445   // Negative multiplication when NegA xor NegB
27446   bool NegMul = (NegA != NegB);
27447   if (NegA)
27448     A = A.getOperand(0);
27449   if (NegB)
27450     B = B.getOperand(0);
27451   if (NegC)
27452     C = C.getOperand(0);
27453
27454   unsigned Opcode;
27455   if (!NegMul)
27456     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
27457   else
27458     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
27459
27460   return DAG.getNode(Opcode, dl, VT, A, B, C);
27461 }
27462
27463 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
27464                                   TargetLowering::DAGCombinerInfo &DCI,
27465                                   const X86Subtarget *Subtarget) {
27466   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
27467   //           (and (i32 x86isd::setcc_carry), 1)
27468   // This eliminates the zext. This transformation is necessary because
27469   // ISD::SETCC is always legalized to i8.
27470   SDLoc dl(N);
27471   SDValue N0 = N->getOperand(0);
27472   EVT VT = N->getValueType(0);
27473
27474   if (N0.getOpcode() == ISD::AND &&
27475       N0.hasOneUse() &&
27476       N0.getOperand(0).hasOneUse()) {
27477     SDValue N00 = N0.getOperand(0);
27478     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27479       if (!isOneConstant(N0.getOperand(1)))
27480         return SDValue();
27481       return DAG.getNode(ISD::AND, dl, VT,
27482                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27483                                      N00.getOperand(0), N00.getOperand(1)),
27484                          DAG.getConstant(1, dl, VT));
27485     }
27486   }
27487
27488   if (N0.getOpcode() == ISD::TRUNCATE &&
27489       N0.hasOneUse() &&
27490       N0.getOperand(0).hasOneUse()) {
27491     SDValue N00 = N0.getOperand(0);
27492     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27493       return DAG.getNode(ISD::AND, dl, VT,
27494                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27495                                      N00.getOperand(0), N00.getOperand(1)),
27496                          DAG.getConstant(1, dl, VT));
27497     }
27498   }
27499
27500   if (VT.is256BitVector())
27501     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27502       return R;
27503
27504   if (SDValue DivRem8 = getDivRem8(N, DAG))
27505     return DivRem8;
27506
27507   return SDValue();
27508 }
27509
27510 // Optimize x == -y --> x+y == 0
27511 //          x != -y --> x+y != 0
27512 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
27513                                       const X86Subtarget* Subtarget) {
27514   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
27515   SDValue LHS = N->getOperand(0);
27516   SDValue RHS = N->getOperand(1);
27517   EVT VT = N->getValueType(0);
27518   SDLoc DL(N);
27519
27520   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
27521     if (isNullConstant(LHS.getOperand(0)) && LHS.hasOneUse()) {
27522       SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
27523                                  LHS.getOperand(1));
27524       return DAG.getSetCC(DL, N->getValueType(0), addV,
27525                           DAG.getConstant(0, DL, addV.getValueType()), CC);
27526     }
27527   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
27528     if (isNullConstant(RHS.getOperand(0)) && RHS.hasOneUse()) {
27529       SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
27530                                  RHS.getOperand(1));
27531       return DAG.getSetCC(DL, N->getValueType(0), addV,
27532                           DAG.getConstant(0, DL, addV.getValueType()), CC);
27533     }
27534
27535   if (VT.getScalarType() == MVT::i1 &&
27536       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
27537     bool IsSEXT0 =
27538         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27539         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27540     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27541
27542     if (!IsSEXT0 || !IsVZero1) {
27543       // Swap the operands and update the condition code.
27544       std::swap(LHS, RHS);
27545       CC = ISD::getSetCCSwappedOperands(CC);
27546
27547       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27548                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27549       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27550     }
27551
27552     if (IsSEXT0 && IsVZero1) {
27553       assert(VT == LHS.getOperand(0).getValueType() &&
27554              "Uexpected operand type");
27555       if (CC == ISD::SETGT)
27556         return DAG.getConstant(0, DL, VT);
27557       if (CC == ISD::SETLE)
27558         return DAG.getConstant(1, DL, VT);
27559       if (CC == ISD::SETEQ || CC == ISD::SETGE)
27560         return DAG.getNOT(DL, LHS.getOperand(0), VT);
27561
27562       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
27563              "Unexpected condition code!");
27564       return LHS.getOperand(0);
27565     }
27566   }
27567
27568   return SDValue();
27569 }
27570
27571 static SDValue PerformGatherScatterCombine(SDNode *N, SelectionDAG &DAG) {
27572   SDLoc DL(N);
27573   // Gather and Scatter instructions use k-registers for masks. The type of
27574   // the masks is v*i1. So the mask will be truncated anyway.
27575   // The SIGN_EXTEND_INREG my be dropped.
27576   SDValue Mask = N->getOperand(2);
27577   if (Mask.getOpcode() == ISD::SIGN_EXTEND_INREG) {
27578     SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
27579     NewOps[2] = Mask.getOperand(0);
27580     DAG.UpdateNodeOperands(N, NewOps);
27581   }
27582   return SDValue();
27583 }
27584
27585 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
27586 // as "sbb reg,reg", since it can be extended without zext and produces
27587 // an all-ones bit which is more useful than 0/1 in some cases.
27588 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
27589                                MVT VT) {
27590   if (VT == MVT::i8)
27591     return DAG.getNode(ISD::AND, DL, VT,
27592                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27593                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
27594                                    EFLAGS),
27595                        DAG.getConstant(1, DL, VT));
27596   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
27597   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
27598                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27599                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
27600                                  EFLAGS));
27601 }
27602
27603 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
27604 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
27605                                    TargetLowering::DAGCombinerInfo &DCI,
27606                                    const X86Subtarget *Subtarget) {
27607   SDLoc DL(N);
27608   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
27609   SDValue EFLAGS = N->getOperand(1);
27610
27611   if (CC == X86::COND_A) {
27612     // Try to convert COND_A into COND_B in an attempt to facilitate
27613     // materializing "setb reg".
27614     //
27615     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
27616     // cannot take an immediate as its first operand.
27617     //
27618     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
27619         EFLAGS.getValueType().isInteger() &&
27620         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
27621       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
27622                                    EFLAGS.getNode()->getVTList(),
27623                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
27624       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
27625       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
27626     }
27627   }
27628
27629   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
27630   // a zext and produces an all-ones bit which is more useful than 0/1 in some
27631   // cases.
27632   if (CC == X86::COND_B)
27633     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
27634
27635   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27636     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27637     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
27638   }
27639
27640   return SDValue();
27641 }
27642
27643 // Optimize branch condition evaluation.
27644 //
27645 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
27646                                     TargetLowering::DAGCombinerInfo &DCI,
27647                                     const X86Subtarget *Subtarget) {
27648   SDLoc DL(N);
27649   SDValue Chain = N->getOperand(0);
27650   SDValue Dest = N->getOperand(1);
27651   SDValue EFLAGS = N->getOperand(3);
27652   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
27653
27654   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27655     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27656     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
27657                        Flags);
27658   }
27659
27660   return SDValue();
27661 }
27662
27663 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
27664                                                          SelectionDAG &DAG) {
27665   // Take advantage of vector comparisons producing 0 or -1 in each lane to
27666   // optimize away operation when it's from a constant.
27667   //
27668   // The general transformation is:
27669   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
27670   //       AND(VECTOR_CMP(x,y), constant2)
27671   //    constant2 = UNARYOP(constant)
27672
27673   // Early exit if this isn't a vector operation, the operand of the
27674   // unary operation isn't a bitwise AND, or if the sizes of the operations
27675   // aren't the same.
27676   EVT VT = N->getValueType(0);
27677   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
27678       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
27679       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
27680     return SDValue();
27681
27682   // Now check that the other operand of the AND is a constant. We could
27683   // make the transformation for non-constant splats as well, but it's unclear
27684   // that would be a benefit as it would not eliminate any operations, just
27685   // perform one more step in scalar code before moving to the vector unit.
27686   if (BuildVectorSDNode *BV =
27687           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
27688     // Bail out if the vector isn't a constant.
27689     if (!BV->isConstant())
27690       return SDValue();
27691
27692     // Everything checks out. Build up the new and improved node.
27693     SDLoc DL(N);
27694     EVT IntVT = BV->getValueType(0);
27695     // Create a new constant of the appropriate type for the transformed
27696     // DAG.
27697     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
27698     // The AND node needs bitcasts to/from an integer vector type around it.
27699     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
27700     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
27701                                  N->getOperand(0)->getOperand(0), MaskConst);
27702     SDValue Res = DAG.getBitcast(VT, NewAnd);
27703     return Res;
27704   }
27705
27706   return SDValue();
27707 }
27708
27709 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27710                                         const X86Subtarget *Subtarget) {
27711   SDValue Op0 = N->getOperand(0);
27712   EVT VT = N->getValueType(0);
27713   EVT InVT = Op0.getValueType();
27714   EVT InSVT = InVT.getScalarType();
27715   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27716
27717   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
27718   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
27719   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27720     SDLoc dl(N);
27721     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27722                                  InVT.getVectorNumElements());
27723     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
27724
27725     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
27726       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
27727
27728     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27729   }
27730
27731   return SDValue();
27732 }
27733
27734 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27735                                         const X86Subtarget *Subtarget) {
27736   // First try to optimize away the conversion entirely when it's
27737   // conditionally from a constant. Vectors only.
27738   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
27739     return Res;
27740
27741   // Now move on to more general possibilities.
27742   SDValue Op0 = N->getOperand(0);
27743   EVT VT = N->getValueType(0);
27744   EVT InVT = Op0.getValueType();
27745   EVT InSVT = InVT.getScalarType();
27746
27747   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
27748   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
27749   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27750     SDLoc dl(N);
27751     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27752                                  InVT.getVectorNumElements());
27753     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
27754     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27755   }
27756
27757   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
27758   // a 32-bit target where SSE doesn't support i64->FP operations.
27759   if (!Subtarget->useSoftFloat() && Op0.getOpcode() == ISD::LOAD) {
27760     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
27761     EVT LdVT = Ld->getValueType(0);
27762
27763     // This transformation is not supported if the result type is f16
27764     if (VT == MVT::f16)
27765       return SDValue();
27766
27767     if (!Ld->isVolatile() && !VT.isVector() &&
27768         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
27769         !Subtarget->is64Bit() && LdVT == MVT::i64) {
27770       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
27771           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
27772       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
27773       return FILDChain;
27774     }
27775   }
27776   return SDValue();
27777 }
27778
27779 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
27780 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
27781                                  X86TargetLowering::DAGCombinerInfo &DCI) {
27782   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
27783   // the result is either zero or one (depending on the input carry bit).
27784   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
27785   if (X86::isZeroNode(N->getOperand(0)) &&
27786       X86::isZeroNode(N->getOperand(1)) &&
27787       // We don't have a good way to replace an EFLAGS use, so only do this when
27788       // dead right now.
27789       SDValue(N, 1).use_empty()) {
27790     SDLoc DL(N);
27791     EVT VT = N->getValueType(0);
27792     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
27793     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
27794                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
27795                                            DAG.getConstant(X86::COND_B, DL,
27796                                                            MVT::i8),
27797                                            N->getOperand(2)),
27798                                DAG.getConstant(1, DL, VT));
27799     return DCI.CombineTo(N, Res1, CarryOut);
27800   }
27801
27802   return SDValue();
27803 }
27804
27805 // fold (add Y, (sete  X, 0)) -> adc  0, Y
27806 //      (add Y, (setne X, 0)) -> sbb -1, Y
27807 //      (sub (sete  X, 0), Y) -> sbb  0, Y
27808 //      (sub (setne X, 0), Y) -> adc -1, Y
27809 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
27810   SDLoc DL(N);
27811
27812   // Look through ZExts.
27813   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
27814   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
27815     return SDValue();
27816
27817   SDValue SetCC = Ext.getOperand(0);
27818   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
27819     return SDValue();
27820
27821   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
27822   if (CC != X86::COND_E && CC != X86::COND_NE)
27823     return SDValue();
27824
27825   SDValue Cmp = SetCC.getOperand(1);
27826   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
27827       !X86::isZeroNode(Cmp.getOperand(1)) ||
27828       !Cmp.getOperand(0).getValueType().isInteger())
27829     return SDValue();
27830
27831   SDValue CmpOp0 = Cmp.getOperand(0);
27832   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
27833                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
27834
27835   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
27836   if (CC == X86::COND_NE)
27837     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
27838                        DL, OtherVal.getValueType(), OtherVal,
27839                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
27840                        NewCmp);
27841   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
27842                      DL, OtherVal.getValueType(), OtherVal,
27843                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
27844 }
27845
27846 /// PerformADDCombine - Do target-specific dag combines on integer adds.
27847 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
27848                                  const X86Subtarget *Subtarget) {
27849   EVT VT = N->getValueType(0);
27850   SDValue Op0 = N->getOperand(0);
27851   SDValue Op1 = N->getOperand(1);
27852
27853   // Try to synthesize horizontal adds from adds of shuffles.
27854   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27855        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27856       isHorizontalBinOp(Op0, Op1, true))
27857     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
27858
27859   return OptimizeConditionalInDecrement(N, DAG);
27860 }
27861
27862 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
27863                                  const X86Subtarget *Subtarget) {
27864   SDValue Op0 = N->getOperand(0);
27865   SDValue Op1 = N->getOperand(1);
27866
27867   // X86 can't encode an immediate LHS of a sub. See if we can push the
27868   // negation into a preceding instruction.
27869   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
27870     // If the RHS of the sub is a XOR with one use and a constant, invert the
27871     // immediate. Then add one to the LHS of the sub so we can turn
27872     // X-Y -> X+~Y+1, saving one register.
27873     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
27874         isa<ConstantSDNode>(Op1.getOperand(1))) {
27875       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
27876       EVT VT = Op0.getValueType();
27877       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
27878                                    Op1.getOperand(0),
27879                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
27880       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
27881                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
27882     }
27883   }
27884
27885   // Try to synthesize horizontal adds from adds of shuffles.
27886   EVT VT = N->getValueType(0);
27887   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27888        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27889       isHorizontalBinOp(Op0, Op1, true))
27890     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
27891
27892   return OptimizeConditionalInDecrement(N, DAG);
27893 }
27894
27895 /// performVZEXTCombine - Performs build vector combines
27896 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
27897                                    TargetLowering::DAGCombinerInfo &DCI,
27898                                    const X86Subtarget *Subtarget) {
27899   SDLoc DL(N);
27900   MVT VT = N->getSimpleValueType(0);
27901   SDValue Op = N->getOperand(0);
27902   MVT OpVT = Op.getSimpleValueType();
27903   MVT OpEltVT = OpVT.getVectorElementType();
27904   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
27905
27906   // (vzext (bitcast (vzext (x)) -> (vzext x)
27907   SDValue V = Op;
27908   while (V.getOpcode() == ISD::BITCAST)
27909     V = V.getOperand(0);
27910
27911   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
27912     MVT InnerVT = V.getSimpleValueType();
27913     MVT InnerEltVT = InnerVT.getVectorElementType();
27914
27915     // If the element sizes match exactly, we can just do one larger vzext. This
27916     // is always an exact type match as vzext operates on integer types.
27917     if (OpEltVT == InnerEltVT) {
27918       assert(OpVT == InnerVT && "Types must match for vzext!");
27919       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
27920     }
27921
27922     // The only other way we can combine them is if only a single element of the
27923     // inner vzext is used in the input to the outer vzext.
27924     if (InnerEltVT.getSizeInBits() < InputBits)
27925       return SDValue();
27926
27927     // In this case, the inner vzext is completely dead because we're going to
27928     // only look at bits inside of the low element. Just do the outer vzext on
27929     // a bitcast of the input to the inner.
27930     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
27931   }
27932
27933   // Check if we can bypass extracting and re-inserting an element of an input
27934   // vector. Essentially:
27935   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
27936   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
27937       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
27938       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
27939     SDValue ExtractedV = V.getOperand(0);
27940     SDValue OrigV = ExtractedV.getOperand(0);
27941     if (isNullConstant(ExtractedV.getOperand(1))) {
27942         MVT OrigVT = OrigV.getSimpleValueType();
27943         // Extract a subvector if necessary...
27944         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
27945           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
27946           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
27947                                     OrigVT.getVectorNumElements() / Ratio);
27948           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
27949                               DAG.getIntPtrConstant(0, DL));
27950         }
27951         Op = DAG.getBitcast(OpVT, OrigV);
27952         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
27953       }
27954   }
27955
27956   return SDValue();
27957 }
27958
27959 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
27960                                              DAGCombinerInfo &DCI) const {
27961   SelectionDAG &DAG = DCI.DAG;
27962   switch (N->getOpcode()) {
27963   default: break;
27964   case ISD::EXTRACT_VECTOR_ELT:
27965     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
27966   case ISD::VSELECT:
27967   case ISD::SELECT:
27968   case X86ISD::SHRUNKBLEND:
27969     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
27970   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG, Subtarget);
27971   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
27972   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
27973   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
27974   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
27975   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
27976   case ISD::SHL:
27977   case ISD::SRA:
27978   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
27979   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
27980   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
27981   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
27982   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
27983   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
27984   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
27985   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
27986   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
27987   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
27988   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
27989   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
27990   case ISD::FNEG:           return PerformFNEGCombine(N, DAG, Subtarget);
27991   case ISD::TRUNCATE:       return PerformTRUNCATECombine(N, DAG, Subtarget);
27992   case X86ISD::FXOR:
27993   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
27994   case X86ISD::FMIN:
27995   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
27996   case ISD::FMINNUM:
27997   case ISD::FMAXNUM:        return performFMinNumFMaxNumCombine(N, DAG,
27998                                                                 Subtarget);
27999   case X86ISD::FAND:        return PerformFANDCombine(N, DAG, Subtarget);
28000   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG, Subtarget);
28001   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
28002   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
28003   case ISD::ANY_EXTEND:
28004   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
28005   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
28006   case ISD::SIGN_EXTEND_INREG:
28007     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
28008   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
28009   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
28010   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
28011   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
28012   case X86ISD::SHUFP:       // Handle all target specific shuffles
28013   case X86ISD::PALIGNR:
28014   case X86ISD::BLENDI:
28015   case X86ISD::UNPCKH:
28016   case X86ISD::UNPCKL:
28017   case X86ISD::MOVHLPS:
28018   case X86ISD::MOVLHPS:
28019   case X86ISD::PSHUFB:
28020   case X86ISD::PSHUFD:
28021   case X86ISD::PSHUFHW:
28022   case X86ISD::PSHUFLW:
28023   case X86ISD::MOVSS:
28024   case X86ISD::MOVSD:
28025   case X86ISD::VPERMILPI:
28026   case X86ISD::VPERM2X128:
28027   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
28028   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
28029   case ISD::MGATHER:
28030   case ISD::MSCATTER:       return PerformGatherScatterCombine(N, DAG);
28031   }
28032
28033   return SDValue();
28034 }
28035
28036 /// isTypeDesirableForOp - Return true if the target has native support for
28037 /// the specified value type and it is 'desirable' to use the type for the
28038 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
28039 /// instruction encodings are longer and some i16 instructions are slow.
28040 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
28041   if (!isTypeLegal(VT))
28042     return false;
28043   if (VT != MVT::i16)
28044     return true;
28045
28046   switch (Opc) {
28047   default:
28048     return true;
28049   case ISD::LOAD:
28050   case ISD::SIGN_EXTEND:
28051   case ISD::ZERO_EXTEND:
28052   case ISD::ANY_EXTEND:
28053   case ISD::SHL:
28054   case ISD::SRL:
28055   case ISD::SUB:
28056   case ISD::ADD:
28057   case ISD::MUL:
28058   case ISD::AND:
28059   case ISD::OR:
28060   case ISD::XOR:
28061     return false;
28062   }
28063 }
28064
28065 /// This function checks if any of the users of EFLAGS copies the EFLAGS. We
28066 /// know that the code that lowers COPY of EFLAGS has to use the stack, and if
28067 /// we don't adjust the stack we clobber the first frame index.
28068 /// See X86InstrInfo::copyPhysReg.
28069 bool X86TargetLowering::hasCopyImplyingStackAdjustment(
28070     MachineFunction *MF) const {
28071   const MachineRegisterInfo &MRI = MF->getRegInfo();
28072
28073   return any_of(MRI.reg_instructions(X86::EFLAGS),
28074                 [](const MachineInstr &RI) { return RI.isCopy(); });
28075 }
28076
28077 /// IsDesirableToPromoteOp - This method query the target whether it is
28078 /// beneficial for dag combiner to promote the specified node. If true, it
28079 /// should return the desired promotion type by reference.
28080 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
28081   EVT VT = Op.getValueType();
28082   if (VT != MVT::i16)
28083     return false;
28084
28085   bool Promote = false;
28086   bool Commute = false;
28087   switch (Op.getOpcode()) {
28088   default: break;
28089   case ISD::LOAD: {
28090     LoadSDNode *LD = cast<LoadSDNode>(Op);
28091     // If the non-extending load has a single use and it's not live out, then it
28092     // might be folded.
28093     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
28094                                                      Op.hasOneUse()*/) {
28095       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
28096              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
28097         // The only case where we'd want to promote LOAD (rather then it being
28098         // promoted as an operand is when it's only use is liveout.
28099         if (UI->getOpcode() != ISD::CopyToReg)
28100           return false;
28101       }
28102     }
28103     Promote = true;
28104     break;
28105   }
28106   case ISD::SIGN_EXTEND:
28107   case ISD::ZERO_EXTEND:
28108   case ISD::ANY_EXTEND:
28109     Promote = true;
28110     break;
28111   case ISD::SHL:
28112   case ISD::SRL: {
28113     SDValue N0 = Op.getOperand(0);
28114     // Look out for (store (shl (load), x)).
28115     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
28116       return false;
28117     Promote = true;
28118     break;
28119   }
28120   case ISD::ADD:
28121   case ISD::MUL:
28122   case ISD::AND:
28123   case ISD::OR:
28124   case ISD::XOR:
28125     Commute = true;
28126     // fallthrough
28127   case ISD::SUB: {
28128     SDValue N0 = Op.getOperand(0);
28129     SDValue N1 = Op.getOperand(1);
28130     if (!Commute && MayFoldLoad(N1))
28131       return false;
28132     // Avoid disabling potential load folding opportunities.
28133     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
28134       return false;
28135     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
28136       return false;
28137     Promote = true;
28138   }
28139   }
28140
28141   PVT = MVT::i32;
28142   return Promote;
28143 }
28144
28145 //===----------------------------------------------------------------------===//
28146 //                           X86 Inline Assembly Support
28147 //===----------------------------------------------------------------------===//
28148
28149 // Helper to match a string separated by whitespace.
28150 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
28151   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
28152
28153   for (StringRef Piece : Pieces) {
28154     if (!S.startswith(Piece)) // Check if the piece matches.
28155       return false;
28156
28157     S = S.substr(Piece.size());
28158     StringRef::size_type Pos = S.find_first_not_of(" \t");
28159     if (Pos == 0) // We matched a prefix.
28160       return false;
28161
28162     S = S.substr(Pos);
28163   }
28164
28165   return S.empty();
28166 }
28167
28168 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
28169
28170   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
28171     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
28172         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
28173         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
28174
28175       if (AsmPieces.size() == 3)
28176         return true;
28177       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
28178         return true;
28179     }
28180   }
28181   return false;
28182 }
28183
28184 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
28185   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
28186
28187   std::string AsmStr = IA->getAsmString();
28188
28189   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
28190   if (!Ty || Ty->getBitWidth() % 16 != 0)
28191     return false;
28192
28193   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
28194   SmallVector<StringRef, 4> AsmPieces;
28195   SplitString(AsmStr, AsmPieces, ";\n");
28196
28197   switch (AsmPieces.size()) {
28198   default: return false;
28199   case 1:
28200     // FIXME: this should verify that we are targeting a 486 or better.  If not,
28201     // we will turn this bswap into something that will be lowered to logical
28202     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
28203     // lower so don't worry about this.
28204     // bswap $0
28205     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
28206         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
28207         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
28208         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
28209         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
28210         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
28211       // No need to check constraints, nothing other than the equivalent of
28212       // "=r,0" would be valid here.
28213       return IntrinsicLowering::LowerToByteSwap(CI);
28214     }
28215
28216     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
28217     if (CI->getType()->isIntegerTy(16) &&
28218         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28219         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
28220          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
28221       AsmPieces.clear();
28222       StringRef ConstraintsStr = IA->getConstraintString();
28223       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28224       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28225       if (clobbersFlagRegisters(AsmPieces))
28226         return IntrinsicLowering::LowerToByteSwap(CI);
28227     }
28228     break;
28229   case 3:
28230     if (CI->getType()->isIntegerTy(32) &&
28231         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28232         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
28233         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
28234         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
28235       AsmPieces.clear();
28236       StringRef ConstraintsStr = IA->getConstraintString();
28237       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28238       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28239       if (clobbersFlagRegisters(AsmPieces))
28240         return IntrinsicLowering::LowerToByteSwap(CI);
28241     }
28242
28243     if (CI->getType()->isIntegerTy(64)) {
28244       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
28245       if (Constraints.size() >= 2 &&
28246           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
28247           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
28248         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
28249         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
28250             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
28251             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
28252           return IntrinsicLowering::LowerToByteSwap(CI);
28253       }
28254     }
28255     break;
28256   }
28257   return false;
28258 }
28259
28260 /// getConstraintType - Given a constraint letter, return the type of
28261 /// constraint it is for this target.
28262 X86TargetLowering::ConstraintType
28263 X86TargetLowering::getConstraintType(StringRef Constraint) const {
28264   if (Constraint.size() == 1) {
28265     switch (Constraint[0]) {
28266     case 'R':
28267     case 'q':
28268     case 'Q':
28269     case 'f':
28270     case 't':
28271     case 'u':
28272     case 'y':
28273     case 'x':
28274     case 'Y':
28275     case 'l':
28276       return C_RegisterClass;
28277     case 'a':
28278     case 'b':
28279     case 'c':
28280     case 'd':
28281     case 'S':
28282     case 'D':
28283     case 'A':
28284       return C_Register;
28285     case 'I':
28286     case 'J':
28287     case 'K':
28288     case 'L':
28289     case 'M':
28290     case 'N':
28291     case 'G':
28292     case 'C':
28293     case 'e':
28294     case 'Z':
28295       return C_Other;
28296     default:
28297       break;
28298     }
28299   }
28300   return TargetLowering::getConstraintType(Constraint);
28301 }
28302
28303 /// Examine constraint type and operand type and determine a weight value.
28304 /// This object must already have been set up with the operand type
28305 /// and the current alternative constraint selected.
28306 TargetLowering::ConstraintWeight
28307   X86TargetLowering::getSingleConstraintMatchWeight(
28308     AsmOperandInfo &info, const char *constraint) const {
28309   ConstraintWeight weight = CW_Invalid;
28310   Value *CallOperandVal = info.CallOperandVal;
28311     // If we don't have a value, we can't do a match,
28312     // but allow it at the lowest weight.
28313   if (!CallOperandVal)
28314     return CW_Default;
28315   Type *type = CallOperandVal->getType();
28316   // Look at the constraint type.
28317   switch (*constraint) {
28318   default:
28319     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
28320   case 'R':
28321   case 'q':
28322   case 'Q':
28323   case 'a':
28324   case 'b':
28325   case 'c':
28326   case 'd':
28327   case 'S':
28328   case 'D':
28329   case 'A':
28330     if (CallOperandVal->getType()->isIntegerTy())
28331       weight = CW_SpecificReg;
28332     break;
28333   case 'f':
28334   case 't':
28335   case 'u':
28336     if (type->isFloatingPointTy())
28337       weight = CW_SpecificReg;
28338     break;
28339   case 'y':
28340     if (type->isX86_MMXTy() && Subtarget->hasMMX())
28341       weight = CW_SpecificReg;
28342     break;
28343   case 'x':
28344   case 'Y':
28345     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
28346         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
28347       weight = CW_Register;
28348     break;
28349   case 'I':
28350     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
28351       if (C->getZExtValue() <= 31)
28352         weight = CW_Constant;
28353     }
28354     break;
28355   case 'J':
28356     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28357       if (C->getZExtValue() <= 63)
28358         weight = CW_Constant;
28359     }
28360     break;
28361   case 'K':
28362     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28363       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
28364         weight = CW_Constant;
28365     }
28366     break;
28367   case 'L':
28368     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28369       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
28370         weight = CW_Constant;
28371     }
28372     break;
28373   case 'M':
28374     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28375       if (C->getZExtValue() <= 3)
28376         weight = CW_Constant;
28377     }
28378     break;
28379   case 'N':
28380     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28381       if (C->getZExtValue() <= 0xff)
28382         weight = CW_Constant;
28383     }
28384     break;
28385   case 'G':
28386   case 'C':
28387     if (isa<ConstantFP>(CallOperandVal)) {
28388       weight = CW_Constant;
28389     }
28390     break;
28391   case 'e':
28392     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28393       if ((C->getSExtValue() >= -0x80000000LL) &&
28394           (C->getSExtValue() <= 0x7fffffffLL))
28395         weight = CW_Constant;
28396     }
28397     break;
28398   case 'Z':
28399     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28400       if (C->getZExtValue() <= 0xffffffff)
28401         weight = CW_Constant;
28402     }
28403     break;
28404   }
28405   return weight;
28406 }
28407
28408 /// LowerXConstraint - try to replace an X constraint, which matches anything,
28409 /// with another that has more specific requirements based on the type of the
28410 /// corresponding operand.
28411 const char *X86TargetLowering::
28412 LowerXConstraint(EVT ConstraintVT) const {
28413   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
28414   // 'f' like normal targets.
28415   if (ConstraintVT.isFloatingPoint()) {
28416     if (Subtarget->hasSSE2())
28417       return "Y";
28418     if (Subtarget->hasSSE1())
28419       return "x";
28420   }
28421
28422   return TargetLowering::LowerXConstraint(ConstraintVT);
28423 }
28424
28425 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
28426 /// vector.  If it is invalid, don't add anything to Ops.
28427 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
28428                                                      std::string &Constraint,
28429                                                      std::vector<SDValue>&Ops,
28430                                                      SelectionDAG &DAG) const {
28431   SDValue Result;
28432
28433   // Only support length 1 constraints for now.
28434   if (Constraint.length() > 1) return;
28435
28436   char ConstraintLetter = Constraint[0];
28437   switch (ConstraintLetter) {
28438   default: break;
28439   case 'I':
28440     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28441       if (C->getZExtValue() <= 31) {
28442         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28443                                        Op.getValueType());
28444         break;
28445       }
28446     }
28447     return;
28448   case 'J':
28449     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28450       if (C->getZExtValue() <= 63) {
28451         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28452                                        Op.getValueType());
28453         break;
28454       }
28455     }
28456     return;
28457   case 'K':
28458     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28459       if (isInt<8>(C->getSExtValue())) {
28460         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28461                                        Op.getValueType());
28462         break;
28463       }
28464     }
28465     return;
28466   case 'L':
28467     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28468       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
28469           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
28470         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
28471                                        Op.getValueType());
28472         break;
28473       }
28474     }
28475     return;
28476   case 'M':
28477     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28478       if (C->getZExtValue() <= 3) {
28479         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28480                                        Op.getValueType());
28481         break;
28482       }
28483     }
28484     return;
28485   case 'N':
28486     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28487       if (C->getZExtValue() <= 255) {
28488         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28489                                        Op.getValueType());
28490         break;
28491       }
28492     }
28493     return;
28494   case 'O':
28495     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28496       if (C->getZExtValue() <= 127) {
28497         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28498                                        Op.getValueType());
28499         break;
28500       }
28501     }
28502     return;
28503   case 'e': {
28504     // 32-bit signed value
28505     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28506       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28507                                            C->getSExtValue())) {
28508         // Widen to 64 bits here to get it sign extended.
28509         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
28510         break;
28511       }
28512     // FIXME gcc accepts some relocatable values here too, but only in certain
28513     // memory models; it's complicated.
28514     }
28515     return;
28516   }
28517   case 'Z': {
28518     // 32-bit unsigned value
28519     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28520       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28521                                            C->getZExtValue())) {
28522         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28523                                        Op.getValueType());
28524         break;
28525       }
28526     }
28527     // FIXME gcc accepts some relocatable values here too, but only in certain
28528     // memory models; it's complicated.
28529     return;
28530   }
28531   case 'i': {
28532     // Literal immediates are always ok.
28533     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
28534       // Widen to 64 bits here to get it sign extended.
28535       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
28536       break;
28537     }
28538
28539     // In any sort of PIC mode addresses need to be computed at runtime by
28540     // adding in a register or some sort of table lookup.  These can't
28541     // be used as immediates.
28542     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
28543       return;
28544
28545     // If we are in non-pic codegen mode, we allow the address of a global (with
28546     // an optional displacement) to be used with 'i'.
28547     GlobalAddressSDNode *GA = nullptr;
28548     int64_t Offset = 0;
28549
28550     // Match either (GA), (GA+C), (GA+C1+C2), etc.
28551     while (1) {
28552       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
28553         Offset += GA->getOffset();
28554         break;
28555       } else if (Op.getOpcode() == ISD::ADD) {
28556         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28557           Offset += C->getZExtValue();
28558           Op = Op.getOperand(0);
28559           continue;
28560         }
28561       } else if (Op.getOpcode() == ISD::SUB) {
28562         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28563           Offset += -C->getZExtValue();
28564           Op = Op.getOperand(0);
28565           continue;
28566         }
28567       }
28568
28569       // Otherwise, this isn't something we can handle, reject it.
28570       return;
28571     }
28572
28573     const GlobalValue *GV = GA->getGlobal();
28574     // If we require an extra load to get this address, as in PIC mode, we
28575     // can't accept it.
28576     if (isGlobalStubReference(
28577             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
28578       return;
28579
28580     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
28581                                         GA->getValueType(0), Offset);
28582     break;
28583   }
28584   }
28585
28586   if (Result.getNode()) {
28587     Ops.push_back(Result);
28588     return;
28589   }
28590   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
28591 }
28592
28593 std::pair<unsigned, const TargetRegisterClass *>
28594 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
28595                                                 StringRef Constraint,
28596                                                 MVT VT) const {
28597   // First, see if this is a constraint that directly corresponds to an LLVM
28598   // register class.
28599   if (Constraint.size() == 1) {
28600     // GCC Constraint Letters
28601     switch (Constraint[0]) {
28602     default: break;
28603       // TODO: Slight differences here in allocation order and leaving
28604       // RIP in the class. Do they matter any more here than they do
28605       // in the normal allocation?
28606     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
28607       if (Subtarget->is64Bit()) {
28608         if (VT == MVT::i32 || VT == MVT::f32)
28609           return std::make_pair(0U, &X86::GR32RegClass);
28610         if (VT == MVT::i16)
28611           return std::make_pair(0U, &X86::GR16RegClass);
28612         if (VT == MVT::i8 || VT == MVT::i1)
28613           return std::make_pair(0U, &X86::GR8RegClass);
28614         if (VT == MVT::i64 || VT == MVT::f64)
28615           return std::make_pair(0U, &X86::GR64RegClass);
28616         break;
28617       }
28618       // 32-bit fallthrough
28619     case 'Q':   // Q_REGS
28620       if (VT == MVT::i32 || VT == MVT::f32)
28621         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
28622       if (VT == MVT::i16)
28623         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
28624       if (VT == MVT::i8 || VT == MVT::i1)
28625         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
28626       if (VT == MVT::i64)
28627         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
28628       break;
28629     case 'r':   // GENERAL_REGS
28630     case 'l':   // INDEX_REGS
28631       if (VT == MVT::i8 || VT == MVT::i1)
28632         return std::make_pair(0U, &X86::GR8RegClass);
28633       if (VT == MVT::i16)
28634         return std::make_pair(0U, &X86::GR16RegClass);
28635       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
28636         return std::make_pair(0U, &X86::GR32RegClass);
28637       return std::make_pair(0U, &X86::GR64RegClass);
28638     case 'R':   // LEGACY_REGS
28639       if (VT == MVT::i8 || VT == MVT::i1)
28640         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
28641       if (VT == MVT::i16)
28642         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
28643       if (VT == MVT::i32 || !Subtarget->is64Bit())
28644         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
28645       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
28646     case 'f':  // FP Stack registers.
28647       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
28648       // value to the correct fpstack register class.
28649       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
28650         return std::make_pair(0U, &X86::RFP32RegClass);
28651       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
28652         return std::make_pair(0U, &X86::RFP64RegClass);
28653       return std::make_pair(0U, &X86::RFP80RegClass);
28654     case 'y':   // MMX_REGS if MMX allowed.
28655       if (!Subtarget->hasMMX()) break;
28656       return std::make_pair(0U, &X86::VR64RegClass);
28657     case 'Y':   // SSE_REGS if SSE2 allowed
28658       if (!Subtarget->hasSSE2()) break;
28659       // FALL THROUGH.
28660     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
28661       if (!Subtarget->hasSSE1()) break;
28662
28663       switch (VT.SimpleTy) {
28664       default: break;
28665       // Scalar SSE types.
28666       case MVT::f32:
28667       case MVT::i32:
28668         return std::make_pair(0U, &X86::FR32RegClass);
28669       case MVT::f64:
28670       case MVT::i64:
28671         return std::make_pair(0U, &X86::FR64RegClass);
28672       // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28673       // Vector types.
28674       case MVT::v16i8:
28675       case MVT::v8i16:
28676       case MVT::v4i32:
28677       case MVT::v2i64:
28678       case MVT::v4f32:
28679       case MVT::v2f64:
28680         return std::make_pair(0U, &X86::VR128RegClass);
28681       // AVX types.
28682       case MVT::v32i8:
28683       case MVT::v16i16:
28684       case MVT::v8i32:
28685       case MVT::v4i64:
28686       case MVT::v8f32:
28687       case MVT::v4f64:
28688         return std::make_pair(0U, &X86::VR256RegClass);
28689       case MVT::v8f64:
28690       case MVT::v16f32:
28691       case MVT::v16i32:
28692       case MVT::v8i64:
28693         return std::make_pair(0U, &X86::VR512RegClass);
28694       }
28695       break;
28696     }
28697   }
28698
28699   // Use the default implementation in TargetLowering to convert the register
28700   // constraint into a member of a register class.
28701   std::pair<unsigned, const TargetRegisterClass*> Res;
28702   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
28703
28704   // Not found as a standard register?
28705   if (!Res.second) {
28706     // Map st(0) -> st(7) -> ST0
28707     if (Constraint.size() == 7 && Constraint[0] == '{' &&
28708         tolower(Constraint[1]) == 's' &&
28709         tolower(Constraint[2]) == 't' &&
28710         Constraint[3] == '(' &&
28711         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
28712         Constraint[5] == ')' &&
28713         Constraint[6] == '}') {
28714
28715       Res.first = X86::FP0+Constraint[4]-'0';
28716       Res.second = &X86::RFP80RegClass;
28717       return Res;
28718     }
28719
28720     // GCC allows "st(0)" to be called just plain "st".
28721     if (StringRef("{st}").equals_lower(Constraint)) {
28722       Res.first = X86::FP0;
28723       Res.second = &X86::RFP80RegClass;
28724       return Res;
28725     }
28726
28727     // flags -> EFLAGS
28728     if (StringRef("{flags}").equals_lower(Constraint)) {
28729       Res.first = X86::EFLAGS;
28730       Res.second = &X86::CCRRegClass;
28731       return Res;
28732     }
28733
28734     // 'A' means EAX + EDX.
28735     if (Constraint == "A") {
28736       Res.first = X86::EAX;
28737       Res.second = &X86::GR32_ADRegClass;
28738       return Res;
28739     }
28740     return Res;
28741   }
28742
28743   // Otherwise, check to see if this is a register class of the wrong value
28744   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
28745   // turn into {ax},{dx}.
28746   // MVT::Other is used to specify clobber names.
28747   if (Res.second->hasType(VT) || VT == MVT::Other)
28748     return Res;   // Correct type already, nothing to do.
28749
28750   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
28751   // return "eax". This should even work for things like getting 64bit integer
28752   // registers when given an f64 type.
28753   const TargetRegisterClass *Class = Res.second;
28754   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
28755       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
28756     unsigned Size = VT.getSizeInBits();
28757     if (Size == 1) Size = 8;
28758     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, Size);
28759     if (DestReg > 0) {
28760       Res.first = DestReg;
28761       Res.second = Size == 8 ? &X86::GR8RegClass
28762                  : Size == 16 ? &X86::GR16RegClass
28763                  : Size == 32 ? &X86::GR32RegClass
28764                  : &X86::GR64RegClass;
28765       assert(Res.second->contains(Res.first) && "Register in register class");
28766     } else {
28767       // No register found/type mismatch.
28768       Res.first = 0;
28769       Res.second = nullptr;
28770     }
28771   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
28772              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
28773              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
28774              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
28775              Class == &X86::VR512RegClass) {
28776     // Handle references to XMM physical registers that got mapped into the
28777     // wrong class.  This can happen with constraints like {xmm0} where the
28778     // target independent register mapper will just pick the first match it can
28779     // find, ignoring the required type.
28780
28781     // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28782     if (VT == MVT::f32 || VT == MVT::i32)
28783       Res.second = &X86::FR32RegClass;
28784     else if (VT == MVT::f64 || VT == MVT::i64)
28785       Res.second = &X86::FR64RegClass;
28786     else if (X86::VR128RegClass.hasType(VT))
28787       Res.second = &X86::VR128RegClass;
28788     else if (X86::VR256RegClass.hasType(VT))
28789       Res.second = &X86::VR256RegClass;
28790     else if (X86::VR512RegClass.hasType(VT))
28791       Res.second = &X86::VR512RegClass;
28792     else {
28793       // Type mismatch and not a clobber: Return an error;
28794       Res.first = 0;
28795       Res.second = nullptr;
28796     }
28797   }
28798
28799   return Res;
28800 }
28801
28802 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
28803                                             const AddrMode &AM, Type *Ty,
28804                                             unsigned AS) const {
28805   // Scaling factors are not free at all.
28806   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
28807   // will take 2 allocations in the out of order engine instead of 1
28808   // for plain addressing mode, i.e. inst (reg1).
28809   // E.g.,
28810   // vaddps (%rsi,%drx), %ymm0, %ymm1
28811   // Requires two allocations (one for the load, one for the computation)
28812   // whereas:
28813   // vaddps (%rsi), %ymm0, %ymm1
28814   // Requires just 1 allocation, i.e., freeing allocations for other operations
28815   // and having less micro operations to execute.
28816   //
28817   // For some X86 architectures, this is even worse because for instance for
28818   // stores, the complex addressing mode forces the instruction to use the
28819   // "load" ports instead of the dedicated "store" port.
28820   // E.g., on Haswell:
28821   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
28822   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
28823   if (isLegalAddressingMode(DL, AM, Ty, AS))
28824     // Scale represents reg2 * scale, thus account for 1
28825     // as soon as we use a second register.
28826     return AM.Scale != 0;
28827   return -1;
28828 }
28829
28830 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
28831   // Integer division on x86 is expensive. However, when aggressively optimizing
28832   // for code size, we prefer to use a div instruction, as it is usually smaller
28833   // than the alternative sequence.
28834   // The exception to this is vector division. Since x86 doesn't have vector
28835   // integer division, leaving the division as-is is a loss even in terms of
28836   // size, because it will have to be scalarized, while the alternative code
28837   // sequence can be performed in vector form.
28838   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
28839                                    Attribute::MinSize);
28840   return OptSize && !VT.isVector();
28841 }
28842
28843 void X86TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
28844   if (!Subtarget->is64Bit())
28845     return;
28846
28847   // Update IsSplitCSR in X86MachineFunctionInfo.
28848   X86MachineFunctionInfo *AFI =
28849     Entry->getParent()->getInfo<X86MachineFunctionInfo>();
28850   AFI->setIsSplitCSR(true);
28851 }
28852
28853 void X86TargetLowering::insertCopiesSplitCSR(
28854     MachineBasicBlock *Entry,
28855     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
28856   const X86RegisterInfo *TRI = Subtarget->getRegisterInfo();
28857   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
28858   if (!IStart)
28859     return;
28860
28861   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
28862   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
28863   for (const MCPhysReg *I = IStart; *I; ++I) {
28864     const TargetRegisterClass *RC = nullptr;
28865     if (X86::GR64RegClass.contains(*I))
28866       RC = &X86::GR64RegClass;
28867     else
28868       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
28869
28870     unsigned NewVR = MRI->createVirtualRegister(RC);
28871     // Create copy from CSR to a virtual register.
28872     // FIXME: this currently does not emit CFI pseudo-instructions, it works
28873     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
28874     // nounwind. If we want to generalize this later, we may need to emit
28875     // CFI pseudo-instructions.
28876     assert(Entry->getParent()->getFunction()->hasFnAttribute(
28877                Attribute::NoUnwind) &&
28878            "Function should be nounwind in insertCopiesSplitCSR!");
28879     Entry->addLiveIn(*I);
28880     BuildMI(*Entry, Entry->begin(), DebugLoc(), TII->get(TargetOpcode::COPY),
28881             NewVR)
28882         .addReg(*I);
28883
28884     for (auto *Exit : Exits)
28885       BuildMI(*Exit, Exit->begin(), DebugLoc(), TII->get(TargetOpcode::COPY),
28886               *I)
28887           .addReg(NewVR);
28888   }
28889 }